Flow Control
____________________
____________________
Flow control describes the order in which the statements will be execute at run time.
1. if else - The argument to the if statement should be boolean type, if we are providing any other type we will get compile time error
int x = 10;
if (x == 20){
System.out.print("Hello");
}else{
System.out.print("Hi");
}
} // Output - Hi
2. Switch - if several options are possible then we have to go for switch case, after every label we have to use break statement otherwise if one condition gets true from there onward all label will be execute.
int x = 3;
switch(x){
case 1: System.out.print("One");
break;
case 2: System.out.print("Two");
break;
case 3: System.out.print("Three");
break;
case 4: System.out.print("Four");
break;
case default: System.out.print("NA");
break;
} // Output - Three
1. While Loop - if we don't know the number of iteration in advance then best suitable loop is while loop, the argument in while loop must be boolean type only.
int a = 10, b = 20;
while(a<b){
System.out.print("True");
}
System.out.print("False");
}
2. do - while loop - If we want to execute loop body at least one time the we have to use do - while loop
int a = 10, b = 20;
do{
System.out.print("Hello");
}while(a>b)
System.out.print("Hi");
3. for() loop - this is the most commonly used loop, if we know the number of iteration then for loop is best choice
syntax : for(initialization;condition;increment decrement){
body }
for(int i=0;i<=10;i++){
System.out.print(x);
}
4. for-each() - also known as enhanced for loop, introduced in 1.5 version. this is the most convenient loop to retrieve the element of array and collection.
int[ ] a = {10, 20, 30, 40};
for loop
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
for-each loop
for(int x:a){
System.out.print(x);
}
1. break
for(int i=-;i<10;i++){
if(i==5)
break;
System.out.println(i);
}
2. continue
for(int i=0;i<=10;i++){
if(i%2==0)
continue;
System.out.println(i);
}