So today, is day nine of my learning Java journey and today I will discuss the another part of Program control statements in Java as said yesterday. So, let's get rolling.
Switch statements -
- it can be said as a more enhanced as well as efficient version of if else condition as when there are multiple situations and pertaining to each of them there is a statement.
- it works like as soon as a match to the condition is found then the statement related to it is executed and rest are discarded and if none then a default statement is executed.
- also with each statement of by-conditions pertaining to an input break has to be used if break is not used then all statements will be executed.
- *Syntax - *
switch(expression){
case constantOne:
statement sequence
break;
case constantTwo:
statementSequenceTwo
break;
.
.
.
.
default:
statementSequenceDefault
}
- here duplicate values are not allowed.
- also the nesting can be implemented of switch case statements in Java just like the nesting of if-statements.
- example -
public class usingSwitchCase {
/*
*here we enter a day number and by using switch case statement we return the corresponding day name.
*/
public static void main(String[] args) {
int dayNumber = 5;
System.out.println("For day number "+ dayNumber +" from week the day name is: ");
scanner.close();
String dayName;
switch (dayNumber) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day number input.";
}
System.out.println("The day is " + dayName);
}
}
Let's halt it here for the day today and will continue tomorrow from the next topic in program control structure that is loops.
Till then keep learning, keep growing. and feel free to point or add anything related to the topic that I may have missed.
Top comments (0)