Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 7

Class - XII

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

The break Keyword The default Keyword


When Java reaches a break keyword, The default keyword specifies some
it breaks out of the switch block. code to run if there is no case match
This will stop the execution of more
code and case testing inside the
block.
When a match is found, and the job is
done, it's time for a break. There is no
need for more testing.
Java While Loop

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.

The while loop loops through a block public class WhileExample {


of code as long as a specified public static void main(String[] args) {
condition is true:
int i=1;
Syntax: while(i<=10){
while (condition) System.out.println(i);
{ i++;
// code block to be executed }
} }
}
Java For Loop
When you know exactly how many times you want to loop through a block of code,
use the for loop instead of a while loop:
Syntax

for (statement 1; statement 2; statement 3)


{
// code block to be executed

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

public class ForExample {


public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Pyramid Example 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
}
}
}

You might also like