Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

public class SwitchDemo {

public static void main(String[] args) {

int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}

, SwitchDemo2 ,:
The following code example, SwitchDemo2, shows how a statement can have multiple case labels. The code
example calculates the number of days in a particular month:

class SwitchDemo2 {
public static void main(String[] args) {

int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
This is the output from the code:

Number of Days = 29

Using Strings in switch Statements

In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code
example, StringSwitchDemo, displays the number of the month based on the value of
the String named month:

public class StringSwitchDemo {

public static int getMonthNumber(String month) {

int monthNumber = 0;

if (month == null) {
return monthNumber;
}

switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}

return monthNumber;
}

public static void main(String[] args) {

String month = "August";

int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);

if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
The output from this code is 8.

Switch Examples: 1. Example of Use


public class decison_making {

public static void main(String []args) {

byte numDay;

numDay=7;

switch (numDay){

case 1 :{

System.out.println("Its Monday");

break;

case 2 :{

System.out.println("Its Tuesday");

break;
}

case 3 :{

System.out.println("Its Wednesday!");

break;
}

case 4 :{

System.out.println("Its Thursday");

break;

case 5 :{

System.out.println("Its Friday");

break;

case 6 :{
System.out.println("Its Saturday!");

break;

case 7 :{

System.out.println("Hurray, Its Sunday!");

break;
}

default :{

System.out.println("Wrong entry!");

Switch Examples: 2. Example of Use


Let’s say, we have the following nested if-else statements:
1
2 public String exampleOfIF(String animal) {
String result;
3
if (animal.equals("DOG") || animal.equals("CAT")) {
4 result = "domestic animal";
5 } else if (animal.equals("TIGER")) {
6 result = "wild animal";
7 } else {
result = "unknown animal";
8 }
9 return result;
10 }
11

To improve readability we could make use of a switch statement here:


1
2
public String exampleOfSwitch(String animal) {
3 String result;
4 switch (animal) {
5 case "DOG":
6 result = "domestic animal";
break;
7 case "CAT":
8 result = "domestic animal";
9 break;
10 case "TIGER":
11 result = "wild animal";
break;
12 default:
13 result = "unknown animal";
14 break;
15 }
return result;
16 }
17
18

Switch Examples: 3. The break Statement


If we forget to write a break, the blocks underneath will be executed.
To demonstrate this let’s omit the break statements and add the output to
the console for each block:
1
public String forgetBreakInSwitch(String animal) {
2 switch (animal) {
3 case "DOG":
4 System.out.println("domestic animal");
5 default:
6 System.out.println("unknown animal");
}
7 }
8
We can also take advantage of this behavior to omit break when we want
the same code executed for several case statements. Let’s rewrite the
example in the previous section by grouping together the first 2 cases:
public String exampleOfSwitch(String animal) {
1 String result;
2 switch (animal) {
3 case "DOG":
4 case "CAT":
5 result = "domestic animal";
break;
6 case "TIGER":
7 result = "wild animal";
8 break;
default:
9 result = "unknown animal";
10 break;
11 }
12 return result;
}
13
14
15
16

4. switch Argument and case Values


Now let’s discuss the allowed types of switch argument and case values,
the requirements for them and how the switch statement works with
Strings.

4.1. Data Types


We can’t compare all the types of objects and primitives in
the switch statement. A switchworks only with four primitives and their
wrappers, as well as with the enum type and the String class:

● byte and Byte


● short and Short
● int and Integer
● char and Character
● enum
● String

String type is available in the switch statement starting with Java 7.


enum type was introduced in Java 5 and has been available in
the switch statement since then.
Wrapper classes have also been available since Java 5.
Of course, switch argument and case values should be of the same type.
4.2. No null Values
We can’t pass the null value as an argument to a switch statement. If we
do it, the program will throw NullPointerException, using our
first switch example:
1 @Test(expected=NullPointerException.class)

2 public void whenSwitchAgumentIsNull_thenNullPointerException() {

3 String animal = null;

4 Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));

}
5

Of course, we can’t also pass null as a value to the case label of


a switch statement. If we do it, the code will not compile.

4.3. Case Values as Compile-Time Constants


If we try to replace the DOG case value with the variable dog the code
won’t compile until we mark the dog variable as final:
1
final String dog="DOG";
2 String cat="CAT";

4 switch (animal) {

5 case dog: //compiles

6 result = "domestic animal";

7 case cat: //does not compile

result = "feline"
8
}
9
4.4. String Comparison
If a switch statement used the equality operator to compare strings we
couldn’t compare a String argument created with the new operator to
a String case value correctly.
Luckily, the switch operator uses the equals() method under the hood.
Let’s demonstrate this:
1 @Test

2 public void whenCompareStrings_thenByEqual() {

3 String animal = new String("DOG");

4 assertEquals("domestic animal", s.exampleOfSwitch(animal));

}
5

5. New switch Expression


Java 12 is available and with it the preview of a new feature – a less
verbose switch expression.
In order to enable it, we need to pass –enable-preview to the compiler.
Let’s take a look:
1
var month = JUN;
2 var value = switch(month) {

3 case JAN, JUN, JUL -> 3;

4 case FEB, SEP, OCT, NOV, DEC -> 1;

5 case MAR, MAY, APR, AUG -> 2;

};
6

7
System.out.println(value); // 3
8
In order to leverage the new syntax, we no longer use a colon, but the
operator known from Lambda Expressions. Notice the lack
of break keyword and that fall-through cases is not happening.
But there’s still a possibility to obtain fine-grained control over what’s
happening on the right side of the expression by using code blocks. In
such a case, we need to manually break from it and specify a return value:
1
public static void switchLocalVariable() {
2
var month = Month.AUG;
3
int i = switch (month){
4 case JAN,JUN, JUL -> 3;

5 case FEB,SEP, OCT, NOV, DEC -> 1;

6 case MAR,MAY, APR, AUG -> {

7 int j = month.toString().length() * 4;

8 break j;

}
9
};
10
System.out.println(i); //12
11
}
12

You might also like