Today i have learnt the working of if loop and for loop in java.
June 17,2016
Java 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.
- if statement
- if-else statement
- nested if statement
- if-else-if ladder
Java IF Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
- if(condition){
- //code to be executed
- }
Java IF-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.
Syntax:
- if(condition){
- //code if condition is true
- }else{
- //code if condition is false
- }
Java IF-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
- if(condition1){
- //code to be executed if condition1 is true
- }else if(condition2){
- //code to be executed if condition2 is true
- }
- else if(condition3){
- //code to be executed if condition3 is true
- }
- …
- else{
- //code to be executed if all the conditions are false
- }
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement.
Syntax:
- switch(expression){
- case value1:
- //code to be executed;
- break; //optional
- case value2:
- //code to be executed;
- break; //optional
- ……
- default:
- code to be executed if all cases are not matched;
- }
Java For Loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.
There are three types of for loop in java.
- Simple For Loop
- For-each or Enhanced For Loop
- Labeled For Loop
Java Simple For Loop
The simple for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value.
Syntax:
- for(initialization;condition;incr/decr){
- //code to be executed
- }
Java For-each Loop
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don’t need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
- for(Type var:array){
- //code to be executed
- }
Java Labeled For Loop
We can have name of each for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop.
Normally, break and continue keywords breaks/continues the inner most for loop only.
Syntax:
- labelname:
- for(initialization;condition;incr/decr){
- //code to be executed
- }