Upload
bhavana16686
View
230
Download
0
Embed Size (px)
Citation preview
8/3/2019 Datatypes Operators Control Statements
1/22
Data Types
Java programming language is a language in which all the variables must be declared
first and then to be used. That means to specify the name and the type of the variable.
This specifies that Java is a strongly-typed programming language. Like
int pedal = 1;
This shows that there exists a field named 'pedal' that holds a data as a numerical value
'1'. The values contained by the variables determines its data type and to perform the
operations on it.
There are seven more primitive data types which are supported by Java language
programming in addition to int. A primitive data type is a data type which ispredefined in Java.
Following are the eight primitive data types:
int
It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648
to 2,147,483,647. This data type is used for integer values. However for wider range of
values use long.
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128
to127 (inclusive). We can save memory in large arrays using byte. We can also use
byte instead of int to increase the limit of the code.
short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768
to 32,767. short is used to save memory in large arrays.
long
The long data type is a 64-bit signed two's complement integer. It ranges from-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with
larger range of values.
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use
a float (instead of double) to save memory in large arrays. We do not use this data type
for the exact values such as currency. For that we have to use java.math.BigDecimal
class.
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
8/3/2019 Datatypes Operators Control Statements
2/22
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).
This data type is generally the default choice for decimal values.
boolean
The boolean data type is 1-bit and has only two values: true and false. We use thisdata type for conditional statements. true and false are not the same as True and False.
They are defined constants of the language.
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to65,535. They are not same as ints, shorts etc.
The following table shows the default values for the data types:
Keyword Description Size/Format
byte Byte-length integer 8-bit two's complement
short Short integer 16-bit two's complement
int Integer 32-bit two's complement
long Long integer 64-bit two's complement
floatSingle-precision floating
point32-bit IEEE
doubleDouble-precision floating
point64-bit IEEE
char A single character 16-bit Unicode character
booleanA boolean value (true or
false)true or false
When we declare a field it is not always essential that we initialize it too. The compiler
sets a default value to the fields which are not initialized which might be zero or null.However this is not recommended.
By literal we mean any number, text, or other information that represents a value. Thismeans what you type is what you get. We will use literals in addition to variables in
Java statement. While writing a source code as a character sequence, we can specify
any value as a literal such as an integer. This character sequence will specify the syntaxbased on the value's type. This will give a literal as a result. For instance
int month = 10;
In the above statement the literal is an integer value i.e 10. The literal is 10 because it
directly represents the integer value.
In Java programming language there are some special type of literals that representnumbers, characters, strings and boolean values. Lets have a closer look on each of the
following.
Integer Literals
Integer literals is a sequence of digits and a suffix as L. To represent the type as longinteger we use L as a suffix. We can specify the integers either in decimal,
hexadecimal or octal format. To indicate a decimal formatput the left most digit as
8/3/2019 Datatypes Operators Control Statements
3/22
nonzero. Similarly put the characters as ox to the left of at least one hexadecimal digit
to indicate hexadecimal format. Also we can indicate the octal formatby a zero digit
followed by the digits 0 to 7. Lets tweak the table below.
659LDecimal integer literal oftype long integer
0x4aHexadecimal integer literal
of type integer
057LOctal integer literal of typelong integer
Character Literals
We can specify a character literal as a single printable character in a pair of single
quote characters such as 'a', '#', and '3'. You must be knowing about the ASCIIcharacter set. The ASCII character set includes 128 characters including letters,
numerals, punctuations etc. There are few character literals which are not readily
printable through a keyboard. The table below shows the codes that can representthese special characters. The letter d such as in the octal, hex etc represents a number.
Escape Meaning
\n New line
\t Tab
\b Backspace
\rCarriage
return
\f Formfeed
\\ Backslash
\'Single
quotation mark
\"Doublequotation mark
\d Octal
\xd Hexadecimal
\udUnicode
character
It is very interesting to know that if we want to specify a single quote, a backslash, or anonprintable character as a character literal use an escape sequence. An escape
sequence uses a special syntax to represents a character. The syntax begins with a
single backslash character.
Lets see the table below in which the character literals use Unicode escape sequence to
represent printable and nonprintable characters both.
8/3/2019 Datatypes Operators Control Statements
4/22
'u0041' Capital letter A
'\u0030' Digit 0
'\u0022' Double quote "
'\u003b' Punctuation ;
'\u0020' Space'\u0009' Horizontal Tab
Boolean Literals
The values true and false are also treated as literals in Java programming. When we
assign a value to a boolean variable, we can only use these two values. Unlike C, we
can't presume that the value of 1 is equivalent to true and 0 is equivalent to false in
Java. We have to use the values true and false to represent a Boolean value. Likeboolean chosen = true;
Remember that the literal true is not represented by the quotation marks around it.
The Java compiler will take it as a string of characters, if its in quotation marks.
Floating-point literals
Floating-point numbers are like real numbers in mathematics, for example, 4.13179,-0.000001. Java has two kinds of floating-point numbers: float and double. The default
type when you write a floating-point literal is double.
Type Size Range Precision
name bytes bits approximate in decimal digits
float 4 32 +/- 3.4 * 1038 6-7
double 8 64 +/- 1.8 * 10308 15
A floating-point literal can be denoted as a decimal point, a fraction part, an exponent
(represented by E or e) and as an integer. We also add a suffix to the floating pointliteral as D, d, F or f. The type of a floating-point literal defaults to double-precision
floating-point.
The following floating-point literals represent double-precision floating-point andfloating-point values.
String Literals
The string of characters is represented as String literals in Java. In Java a string is not a
basic data type, rather it is an object. These strings are not stored in arrays as in Clanguage. There are few methods provided in Java to combine strings, modify strings
and to know whether to strings have the same value.
We represent string literals asString myString = "How are you?";
The above example shows how to represent a string. It consists ofa series of characters
inside double quotation marks.
Lets see some more examples of string literals:
6.5E+32 (or6.5E32)
Double-precisionfloating-point literal
7DDouble-precision
floating-point literal
.01f Floating-point literal
8/3/2019 Datatypes Operators Control Statements
5/22
"" // the empty string
"\"" // a string containing "
"This is a string" // a string containing 16 characters"This is a " + // actually a string-valued constant expression,
"two-line string" // formed from two string literals
Strings can include the character escape codes as well, as shown here:String example = "Your Name, \"Sumit\"";System.out.println("Thankingyou,\nRichards\n");
Null Literals
The final literal that we can use in Java programming is a Null literal. We specify the
Null literal in the source code as 'null'. To reduce the number of references to anobject, use null literal. The type of the null literal is always null. We typically assign
null literals to object reference variables. For instance
s = null;
An this example an object is referenced by s. We reduce the number of references to anobject by assigning null to s. Now, as in this example the object is no longer referenced
so it will be available for the garbage collection i.e. the compiler will destroy it and the
free memory will be allocated to the other object. Well, we will later learn about
garbage collection.
Introduction to Java Arrays
In this section you will be introduced to the concept of Arrays in Java Programminglanguage. You will learn how the Array class in java helps the programmer toorganize the same type of data into easily manageable format.
Program data is stored in the variables and takes the memory spaces, randomly.
However, when we need the data of the same type to store in the contiguous memory
allocations we use the data structures like arrays. To meet this feature java hasprovided an Array class which abstracts the array data-structure.
The java array enables the user to store the values of the same type in contiguous
memory allocations. Arrays are always a fixed length abstracted data structure which
can not be altered when required.
The Array class implicitly extendsjava.lang.Object so an array is an instance ofObject.
Structure of Arrays
Now lets study the structure of Arrays in java. Array is the most widely used data
structure in java. It can contain multiple values of the same type. Moreover, arrays arealways of fixed length i.e. the length of an array cannot be increased or decreased.
8/3/2019 Datatypes Operators Control Statements
6/22
Lets have a close look over the structure of Array. Array contains the values which are
implicitly referenced through the index values. So to access the stored values in an
array we use indexes. Suppose an array contains "n" integers. The first element of thisarray will be indexed with the "0" value and the last integer will be referenced by "n-
1" indexed value.
Presume an array that contains 12 elements as shown in the figure. Each element isholding a distinct value. Here the first element is refrenced by a[0] i.e. the first indexvalue. We have filled the 12 distinct values in the array each referenced as:
a[0]=1
a[1]=2
...
a[n-1]=n
...
a[11]=12The figure below shows the structure of an Array more precisely.
Array Declaration
As we declare a variable in Java, An Array variable is declared the same way. Array
variable has a type and a valid Java identifier i.e. the array's type and the array's name.By type we mean the type of elements contained in an array. To represent the variable
as an Array, we use [] notation. These two brackets are used to hold the array of a
variable.
By array's name, we mean that we can give any name to the array, however it shouldfollow the predefined conventions. Below are the examples which show how to declare
an array :-
int[] array_name; //declares
an array of integers
String[] names;int[][] matrix; //this is an
array of arrays
8/3/2019 Datatypes Operators Control Statements
7/22
It is essential to assign memory to an array when we declare it. Memory is assigned to
set the size of the declared array. for example:
int[] array_name =new int[5];
Here is an example that creates an array that has 5 elements.public class Array
{
public static void
main(String[] args)
{
int[] a = new
int[5];
}
}
Array Initialization
After declaring an array variable, memory is allocated to it. The "new" operator is usedfor the allocation of memory to the array object. The correct way to use the "new"
operator is
String names[];
names = new String[10];
Here, the new operator is followed by the type of variable and the number of elementsto be allocated. In this example [] operator has been used to place the number of
elements to be allocated.
Lets see a simple example of an array,
public class Sum{
public static voidmain(String[] args){
int[] x = new int [101]; for (int i = 0; i
8/3/2019 Datatypes Operators Control Statements
8/22
C:\tamana>java Sum
5050
C:\tamana>
Array Usage
We have already discussed that to refer an element within an array, we use the []
operator. The [] operator takes an "int" operand and returns the element at that index.We also know that the array indices start with zero, so the first element will be held by
the 0 index. For Example :-
int month = months[4]; //get
the 5th month (May)
Most of the times it is not known in the program that which elements are of interest in
an array. To find the elements of interest in the program, it is required that the program
must run a loop through the array. For this purpose "for" loop is used to examine each
element in an array. For example :-
String months[] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"July", "Aug", "Sep", "Oct", "Nov", "Dec"};
//use the length attribute to get the number
//of elements in an array
for (int i = 0; i < months.length; i++ ) {
System.out.println("month: " + month[i]);
Here, we have taken an array of months which is,
String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep",
"Oct", "Nov", "Dec"};Now, we run a for loop to print each element individually starting from the month
"Jan".
for (int i = 0; i < months.length; i++ )
In this loop int i = 0; indicates that the loop starts from the 0th position of an array andgoes upto the last position which is length-1, i < months.length; indicates the length
of the array and i++ is used for the increment in the value of i which is i = i+1.
Multi-dimensional arrays
So far we have studied about the one-dimensional and two-dimensional arrays. To
store data in more dimensions a multi-dimensional array is used. A multi-dimensionalarray of dimension n is a collection of items. These items are accessed via n subscript
expressions. For example, in a language that supports it, the element of the two-
dimensional array x is denoted by x[i,j].The Java programming language does not really support multi-dimensional arrays. It
does, however, supports an array of arrays. In Java, a two-dimensional array ' x' is an
array of one-dimensional array : For instance :-
int[][] x = new int[3][5];
8/3/2019 Datatypes Operators Control Statements
9/22
The expression x[i] is used to select the one-dimensional array; the expression x[i][j] is
ued to select the element from that array. The first element of this array will be
indexed with the "0" value and the last integer will be referenced by "length-1"indexed value. There is no array assignment operator.
Two-dimensional arrays
Two-dimensional arrays are defined as "an array of arrays". Since an array type is a
first-class Java type, we can have an array of ints, an array of Strings, or an array of
Objects. For example, an array of ints will have the type int[]. Similarly we can haveint[][], which represents an "array of arrays of ints". Such an array is said to be a two-
dimensional array.
The command
int[][] A = new int[3][4]
declares a variable, A, of type int[][], and it initializes that variable to refer to a newly
created object. That object is an array of arrays of ints. Here, the notation int[3][4]
indicates that there are 3 arrays of ints in the array A, and that there are 4 ints in each
of those arrays.To process a two-dimensional array, we use nested for loops. We already know about
for loop. A loop in a loop is called a Nested loop. That means we can run another loop
in a loop.
Notice in the following example how the rows are handled as separate objects.
Code: Java
int[][] a2 = new int[10][5];
// print array in rectangular form
for (int r=0; r
8/3/2019 Datatypes Operators Control Statements
10/22
srcIndex start position (first cell to copy) in the source array
dest the destination array
destIndex start position in the destination arraylength the number of array elements to be copied
The following program, ArrayCopyDemo(in a .java source file), uses arraycopy to
copy some elements from the copyFrom array to the copyTo array.
public class ArrayCopyDemo{public static voidmain(String[] args){ char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j'}; char[] copyTo = new char[5]; System.arraycopy(copyFrom, 2, copyTo, 0, 5);
System.out.println(new String (copyTo)); }
}
In this example the array method call begins the copy of elements from element
number 2. Thus the copy begins at the array element 'c'. Now, the arraycopy methodtakes the copie element and puts it into the destination array. The destination arraybegins at the first element (element 0) which is the destination array copyTo. The
copyTo copies 5 elements : 'c', 'd', 'e', 'f', 'g'. This method will take "cdefg" out of
"abcdefghij", like this :
Operators
Operators are symbols that performs some operations on one or more than oneoperands. Once we declare and initialize variables, we can use operators to performcertain tasks like addition, subtraction etc.
Simple Assignment Operator
= Simple assignment operator
Arithmetic Operators
+ Additive operator (also used for String concatenation)- Subtraction operator
* Multiplication operator/ Division operator% Remainder operator
Unary Operators
+ Unary plus operator; indicates positive value (numbers are positive without this,
however)
8/3/2019 Datatypes Operators Control Statements
11/22
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1! Logical compliment operator; inverts the value of a boolean
Equality and Relational Operators
== Equal to
!= Not equal to> Greater than
>= Greater than or equal to
< Less than Signed right sift>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
These operators follow some precedence to apply. The table below shows the list of
operators that follow the precedence. Operators with higher precedence are evaluated
before operators with relatively lower precedence. However, Operators on the sameline have equal precedence. The rule to deal with equal precedence operators is that allbinary operators except for the assignment operators are evaluated from left to right;
assignment operators are evaluated right to left.
Operators Precedence
postfix expr++,, expr--
unary ++expr, --expr, +expr,
8/3/2019 Datatypes Operators Control Statements
12/22
-expr ~ !
multiplicative * / %
additive + -
shift > >>>
relational < > , = instanceof equality == , !=
bitwise AND &
bitwise
exclusive OR^
bitwise
inclusive OR|
logical AND &&
logical OR ||
ternary ? :
assignment= , +=, -=, *=, /=, %=,&=, ^=, |=, =,>>, >=
Controlling your program
We all know that the execution of the statements in a program takes place from top to
bottom. We will learn how the different kinds of statement have different effects inlooping like decision-making statements (if-then, if-then-else, switch), the looping
statements (for, while, do-while), and the branching statements (break, continue,
return) in Java programming language.
Selection
In this section we will learn how to use if-then, if-the else and switch statements in
Java programming. These are the two alternative structure statements in Java.
The ifstatement
To start with controlling statements in Java, lets have a recap over the controlstatements in C++. You must be familiar with the if-then statements in C++. The if-
then statement is the most simpler form of control flow statement. It directs theprogram to execute a certain section of code. This code gets executed if and only if thetest evaluates to true. That is the if statement in Java is a test of any boolean
expression. The statement following the if will only be executed when the boolean
expression evaluates to true. On the contrary if the boolean expression evaluates tofalse then the statement following the if will not only be executed.
Lets tweak the example below:
8/3/2019 Datatypes Operators Control Statements
13/22
if (a > 1)
System.out.println("Greater than 1");
if (a < 1)System.out.println("Less than 1");
In the above example if we declare int a = 1, the statements will show some of thevalid boolean expressions to the if statement.
We are talking about if statements here so we can't forget the else statement here. Theif statement is incomplete without the else statement. The general form of the
statement is:
if (condition)statement1;
else
statement2;The above format shows that an else statement will be executed whenever an if
statement evaluates to false. For instance,
if (a>1){
System.out.println("greater than 1");}
else{
System.out.println("smaller than 1");}
Lets have a look at a slightly different example as shown below:
class compare{public static voidmain(String[] args){ int a = 20;
int b = 40; if (ajava compare
a is smaller
Theswitch statement
8/3/2019 Datatypes Operators Control Statements
14/22
Sometimes it becomes cumbersome to write lengthy programs using if and if-else
statements. To avoid this we can use Switch statements in Java. The switch statement
is used to select multiple alternative execution paths. This means it allows any numberof possible execution paths. However, this execution depends on the value of a
variable or expression. The switch statement in Java is the best way to test a single
expression against a series of possible values and executing the code.Here is the general form of switch statement:
switch (expression){
case 1:
code block1case 2:
code block2
.
.
.
default:
code default;}
The expression to the switch must be of a type byte, short, char, or int. Then there is a
code block following the switch statement that comprises of multiple case statementsand an optional default statement.
The execution of the switch statement takes place by comparing the value of the
expression with each of the constants. The comparison of the values of the expressionwith each of the constants occurs after the case statements. Otherwise, the statements
after the default statement will be executed.
Now, to terminate a statement following a switch statement use breakstatement
within the code block. However, its an optional statement. The break statement is usedto make the computer jump to the end of the switch statement. Remember, if we won't
use break statement the computer will go ahead to execute the statements associated
with the next case after executing the first statement.
Here is an example which will help you to understand more easily:
switch (P { // assume P is an integer variable
case 1:System.out.println("The number is 1.");
break;
case 2:case 4:
case 8:
System.out.println("The number is 2, 4, or 8.");System.out.println("(That's a power of 2!)");
break;
case 3:
case 6:case 9:
System.out.println("The number is 3, 6, or 9.");
8/3/2019 Datatypes Operators Control Statements
15/22
System.out.println("(That's a multiple of 3!)");
break;
case 5:System.out.println("The number is 5.");
break;
default:System.out.println("The number is 7,");
System.out.println(" or is outside the range 1 to 9.");
}
For example the following program Switch, declares an int named week whose valuerepresents a day out of the week. The program displays the name of the day, based on
the value of week, using the switch statement.
class Switch{public static voidmain(String[] args){ int week = 5; switch (week){
case 1: System.out.println("monday");break; case 2: System.out.println("tuesday");break; case 3: System.out.println("wednesday");break; case 4: System.out.println("thursday");break; case 5: System.out.println("friday");break; case 6: System.out.println("saturday");break; case 7: System.out.println("sunday");break;
default: System.out.println("Invalid week");break; }
}
}
In this case, "friday" is printed to standard output.
C:\javac>javac Switch.java
C:\javac>java Switch
friday
One other point to note here is that the body of a switch statement is known as a switchblock. The appropriate case gets executed when the switch statement evaluates its
expression.
Iteration
The concept of Iteration has made our life much more easier. Repetition of similartasks is what Iteration is and that too without making any errors. Until now we have
learnt how to use selection statements to perform repetition. Now lets have a quick
look at the iteration statements which have the ability to loop through a set of values tosolve real-world problems.
TheforStatement
8/3/2019 Datatypes Operators Control Statements
16/22
In the world of Java programming, the for loop has made the life much more easier. It
is used to execute a block of code continuously to accomplish a particular condition.
For statement consists of tree parts i.e. initialization, condition, and iteration.
initialization : It is an expression that sets the value of the loop control variable. It
executes only once.
condition : This must be a boolean expression. It tests the loop control variableagainst a target value and hence works as a loop terminator.
iteration : It is an expression that increments or decrements the loop control variable.
Here is the form of the for loop:
for(initialization; condition; iteration){
//body of the loop
}
For example, a sample for loop may appear as follows:
int i;
for (i=0; i
8/3/2019 Datatypes Operators Control Statements
17/22
Here is the output:
C:\javac>javac printDemo.java
C:\javac>java printDemoHello World!
Hello World!Hello World!Hello World!
Hello World!
Hello World!Hello World!
Hello World!
Hello World!Hello World!
After learning how to use a for loop, I would like to introduce another form of for
loop to be used for iteration through collection and arrays. This form has enhanced the
working of for loop. This is the more compact way to use a for loop.Here we will take an array of 10 numbers.
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, arrayDemo,displays the usage of for loop through arrays. Itshows the variable item that holds the the current value from the array.
class arrayDemo{public static voidmain(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println("Count is: " + item);
}
}
}
Here is the output of the program
C:\javac>javac arrayDemo.java
C:\javac>java arrayDemo
Count is: 1
Count is: 2Count is: 3
Count is: 4Count is: 5Count is: 6
Count is: 7
Count is: 8Count is: 9
Count is: 10
We would like to suggest to use this form of for loop if possible.
8/3/2019 Datatypes Operators Control Statements
18/22
The while and do-while Statements
Lets try to find out what a while statement does. In a simpler language, the whilestatement continually executes a block of statements while a particular condition is
true. To write a while statement use the following form:
while (expression) {statement(s)
}
Lets see the flow of the execution of the while statement in steps:1. Firstly, It evaluates the condition in parentheses, yielding true or false.
2. Secondly, It continues to execute the next statement if the condition is false and exit
the while statement.
3. Lastly, If the condition is true it executes each of the statements between thebrackets and then go back to step 1.
For example:
// This is the Hello program in Java
class Bonjour{public static voidmain (String args[]){ System.out.print("Bonjour "); // Say Hello
int i = 0;// Declare and initialize loop counter
while (i < args.length){ // Test and Loop System.out.print(args[i]);
System.out.print(" ");
i = i + 1; // Increment Loop Counter
}
System.out.println(); // Finish the line
}
}
In the above example, firstly the condition will be checked in the parentheses, while
(ijavac
Bonjour.java
C:\javac>javaBonjour
Bonjour
The while statement works as to for loop because the third step loops back to the top.
Remember, the statement inside the loop will not execute if the condition is false. The
statement inside the loop is called the body of the loop. The value of the variable
8/3/2019 Datatypes Operators Control Statements
19/22
should be changed in the loop so that the condition becomes false and the loop
terminates.
Have a look at do-while statement now.
Here is the syntax:
do {statement(s)
} while (expression);
Lets tweak an example of do-while loop.
class DoWhileDemo{public static voidmain (String args[]) { int i = 0;
do{ System.out.print("Bonjour"); // Say Bonjour
System.out.println(" ");
i = i + 1; // Increment LoopCounter
}while (i < 5);}}
In the above example, it will enter the loop without checking the condition first and
checks the condition after the execution of the statements. That is it will execute thestatement once and then it will evaluate the result according to the condition.
The output is as follows:
C:\javac>javac DoWhileDemo.java
C:\javac>java DoWhileDemo
BonjourBonjour
BonjourBonjour
Bonjour
You must have noticed the difference between the while and do-while loop. That is the
do-while loop evaluates its expression at the bottom of the loop. Hence, the statementin the do-while loop will be executed once.
Jumping
Sometimes we use Jumping Statements in Java. Using for, while and do-while loops is
not always the right idea to use because they are cumbersome to read. Using jumpingstatements like break and continue it is easier to jump out of loops to control otherareas of program flow.
The breakStatement
We use break statement to terminate the loop once the condition gets satisfied.
Lets see a simple example using break statement.
class BreakDemo{
8/3/2019 Datatypes Operators Control Statements
20/22
public static voidmain(String[] args) { for (int i = 0; i < 5; i++) { System.out.println(i);
if (i==3) { break ; }
}
}
}
In the above example, we want to print 5 numbers from 0 to 1 at first using for loop asshown. Then we put a condition that 'if i = = 3', the loop should be terminated. To
terminate the loop after satisfying the condition we use break.
It gives the following output:
C:\javac>javac BreakDemo.java
C:\javac>java BreakDemo
012
3
The break statement has two forms: labeled and unlabeled. You saw the labeled form
in the above example i.e. a labeled break terminates an outer statement. However, an
unlabeled break statement terminates the innermost loop like switch, for, while, or do-
while statement.
Now observe the example ofunlabeled form below. We have used two loops here two
print '*'. In this example, if we haven't use break statement thus the loop will continueand it will give the output as shown below.
class BreaklabDemo1{
public static voidmain(String[] args){
for (int i = 0; i < 10; i++) { System.out.print("\n");
for (int j = 0; jjavac BreaklabDemo1.java
C:\javac>java BreaklabDemo1
8/3/2019 Datatypes Operators Control Statements
21/22
*
*****
****
***********
*******
*****************
**********
C:\javac>
However in the following example we have used break statement. In this the inner forloop i.e. "for (int j=0; j
8/3/2019 Datatypes Operators Control Statements
22/22