DEV Community

Preethi Nandhagopal
Preethi Nandhagopal

Posted on

Switch statement , for and while loop

Switch statement:
The switch statement in java served as a multi-way branch statement, allowing the execution of different code blocks based on the value of an expression. It required explicit break statement to prevent fall through behaviour in pre java 12.
It will match only with variable assigning. We can't use operator (i.e, conditional ,relational etc).
If we didn't use break then it will print next line also.
In java version one they allowed primitive data type only contains byte, short, int, char.
In version 7 only they allowed non primitive data type String.
Java 12 introduced switch expression as a preview feature, allowing switch to be used as an expression that return value.
To simplify the syntax and reduce the boilerplak code.
These new form eliminate the need for break statement and support multiple labels per case.
default is optional and runs if no match is found.
Syntax:
switch(){
case 1:
System.out.println();
break;
case 2:
System.out.println();
break;
default:
System.out.println();
}

Syntax of preview switch:
switch(){
case 1->System.out.println();
case 2->System.out.println();
case 3->System.out.println();
default->System.out.println();
}

While loop:
It is a fundamental entry control loop. It repeatedly executes a block of code only as long as a specified boolean condition remains true.Once the condition becomes false, execution statement jumps to following the loop block.
Syntax:
while(condition){
}
Before each iteration, condition is evaluted. If true, the loop body runs, afterwards control returns to evaluate condition again.
If false (even before the first iteration) the body is skipped entirely.

for loop:
Syntax:
for(initialization;terimination;increment){
}
initialization-> executed once at the start.
terimination->a boolean expression checked before each iteration. If false the loop exist.
increment->executed after each iteration.

Top comments (0)