Control
Control
Control
If-else Statement
The Java if statement is used to test the condition. It checks boolean
condition: true or false. There are various types of if statement in java.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
Java IF Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
1. if(condition){
2. //code to be executed
3. }
Example:
Output:
Syntax:
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
Example:
Output:
odd number
Syntax:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
Example:
Output: C grade
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement.
Syntax:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
Example:
Example:
Syntax:
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
Example:
Output:
1
2
3
4
5
6
7
8
9
10
It works on elements basis not index. It returns element one by one in the defined
variable.
Syntax:
1. for(Type var:array){
2. //code to be executed
3. }
Example:
Output:
12
23
44
56
78
Normally, break and continue keywords breaks/continues the inner most for loop only.
Syntax:
1. labelname:
2. for(initialization;condition;incr/decr){
3. //code to be executed
4. }
Example:
Output:
1 1
1 2
1 3
2 1
If you use break bb;, it will break inner loop only which is the default behavior of any
loop.
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Syntax:
1. for(;;){
2. //code to be executed
3. }
Example:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
Syntax:
1. while(condition){
2. //code to be executed
3. }
Example:
Output:
1
2
3
4
5
6
7
8
9
10
Syntax:
1. while(true){
2. //code to be executed
3. }
Example:
The Java do-while loop is executed at least once because condition is checked after loop
body.
Syntax:
1. do{
2. //code to be executed
3. }while(condition);
Example:
Output:
1
2
3
4
5
6
7
8
9
10
Syntax:
1. do{
2. //code to be executed
3. }while(true);
Example:
Output:
Syntax:
1. jump-statement;
2. break;
Output:
1
2
3
4
Example:
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Syntax:
1. jump-statement;
2. continue;
Output:
1
2
3
4
6
7
8
9
10
Example:
Output:
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3