Java Switch Loop
Java Switch Loop
Information Technology
Java
Topic: Switch Case
Java Switch Statements
Use the switch statement to select one of many code blocks to be
executed.
This is how it works:
Syntax: The switch expression is evaluated
switch(expression) { once.
case x: The value of the expression is
// code block compared with the values of
break; each case.
case y: If there is a match, the associated
// code block block of code is executed.
break; The break and default keywords are
default: optional, and will be described later
// code block in this chapter
}
Java Switch Statements
Loops
Loops can execute a block of code as long as a specified
condition is reached.
Loops are handy because they save time, reduce errors,
and they make code more readable.
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example1: Example2:
for (int i = 0; i < 5; i++)
{
System.out.println(i); Java Program to demonstrate the example
} of for loop
//which prints table of 1
PyramidExample.java Output:
*
public class PyramidExample { *
public static void main(String[] args) { ***
for(int i=1;i<=5;i++){ ****
for(int j=1;j<=i;j++){ *****
System.out.print("* ");
}
System.out.println();//new line
}
}
}