If you have already register Login here.
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement.
This is an easier implementation to the if-else statements. The keyword "switch" is followed by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression that creates labels for the case must be unique. The switch expression is matched with each case label. Only the matched case is executed ,if no case matches then the default statement (if present) is executed.
switch ( expression )
{
case value1 :
// code executed
break;
case value2:
// code executed
break;
...
...
case valueN:
// code executed
break;
...
...
default:
// code executed
break;
}
public class SwitchCaseExample
{
public static void main(String[] args)
{
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thrusday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid entry");
break;
}
}
}
Output :
Wednesday
import java.util.Scanner; //Needed for Scanner object
public class SwitchCaseExWithUserInput
{
public static void main(String[] args)
{
Scanner scanNumber= new Scanner(System.in);
// Get the Day.
System.out.print("Enter a Day Number 1 to 7 : ");
int dayN = scanNumber.nextInt();
switch (dayN) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thrusday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid entry");
break;
}
}
}
Output :
Enter a Day Number 1 to 7 : Friday
The java switch statement is fall-through. It means it executes all statement after first match if break statement is not used with switch cases.
Java Switch Statement Example:
public class SwitchExample3 {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output :
20
30
Not in 10, 20 or 30
© 2022 Easy To Learning. All Rights Reserved | Design by Easy To Learning