1. SWITCH STATEMENT:
The switch statement in Java is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions.
It is an alternative to an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The expression can be of type byte, short, char, int, long, enums[TBD], String, or wrapper classes (Integer, Short, Byte, Long).
Note: Java switch expression must be of byte, short, int, long(with its Wrapper type), enums and string. Beginning with JDK7, it also works with enumerated types (Enums in java), the String class, and Wrapper classes.[TBD]
SYNTAX:
switch(expression)
{
case value1 :
// Statements
break; // break is optional
case value2 :
// Statements
break; // break is optional
....
....
....
default :
// default Statement
}
//Break-It will moves to next statement.
FLOWCHART:
EXAMPLE PROGRAM:
public class Days {
public static void main(String[] args)
{
int day = 5;
String dayString;
switch (day)
{
case 1:
dayString = "Monday";
break;
case 2:
dayString = "Tuesday";
break;
case 3:
dayString = "Wednesday";
break;
case 4:
dayString = "Thursday";
break;
case 5:
dayString = "Friday";
break;
case 6:
dayString = "Saturday";
break;
case 7:
dayString = "Sunday";
break;
default:
dayString = "Invalid day";
}
System.out.println(dayString);
}
}
output:Friday
2.TERNARY STATEMENT:
In Java, the ternary operator is a type of Java conditional operator.
The ternary operator (? :) consists of three operands. It is used to evaluate Boolean expressions. The operator decides which value will be assigned to the variable. It is the only conditional operator that accepts three operands. It can be used instead of the if-else statement. It makes the code much more easy, readable, and shorter.
Note: Every code using an if-else statement cannot be replaced with a ternary operator.
SYNTAX:
variable = (condition) ? expression1 : expression2
The above statement states that if the condition returns true, expression1 gets executed, else the expression2 gets executed and the final result stored in a variable.
FLOWCHART:
EXAMPLE PROGRAM:
public class TernaryOperator
{
public static void main(String args[])
{
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y);
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y);
}
}
output:
Value of y is: 90
Value of y is: 61
REFERENCE:
https://www.javatpoint.com/java-switch
https://www.geeksforgeeks.org/switch-statement-in-java/
Top comments (0)