If ( condition ) {
//do work if condition is true
} else {
// do work if condition is true
}
Example:int number = 10;
if(number==10){ //== means if number is 10 then
System.out.println("You Score 10");
} else {
System.out.println("You Didnt Score 10");
}Nested If else statement:
Example:
int a = 100;
int b = 201;
if(a == 100){
if(b == 200){
System.out.print("a is 100 and b is 200");
} else {
System.out.print("a is 100 and b is not 200");//true
}
} else {
System.out.print("a is not 100");
} If_ else if_ else statement:
Syntax:If (condition) {
//do work if condition 1 is true
} else if (condition) {
//do work if condition 2 is true
} else {
//do work if none of the above condition is true
}
Example: int number = 5;
if(number == 10) {
System.out.println("You Score 10");
} else if(number < 10) {
System.out.println("Your Score is less than 10");//true
} else {
System.out.println("You Didn’t Score 10");
}
Example 2 (if else if):
int a = 10 , b = 15 , c = 25;
if(a>b && a>c){
System.out.println("a is Greater");
} else if(b>a && b>c) {
System.out.println("b is Greater");
} else if(c>a && c>b) {
System.out.println("c is Greater"); //c is Greater
}
switch statement:
Syntax:
Switch ( key / expression ) {
case value :
//do work
break;
case value :
//do work
break;
…..
default: //not necessary
//do work
}
Example:int key = 2;
switch (key) {
case 1:
System.out.println("1 is selected");
break;
case 2:
System.out.println("2 is selected");//it is selected
break;
default:
break;
}
break statement:
int[] decimals = {10,20,60,80,100};
for (int i = 0 ; i < decimals.length ; i++){
if(decimals[i] == 80){
break;
}
System.out.print(decimals[i] + "\n");
}
OUTPUT: //because when it finds 80 in array it breaks
10
20
60
continue statement:
int[] decimals = {10,20,60,80,100};
for (int i = 0 ; i < decimals.length ; i++){
if(decimals[i] == 80){
continue;
}
System.out.print(decimals[i] + "\n");
}
OUTPUT: //because when it finds 80 it skips it and continues printing to end of array
10
20
60
100
0 comments:
Post a Comment