NOTE
switch
Supported types and source analysis of switch over int, char, and String.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Supported Functionality
Supports conditional branches for byte, short, int, char, String, and enum.
2. Source Analysis
2.1. int
int a = 5;
switch (a)
{
case 1:
System.out.println(1);
break;
case 5:
System.out.println(5);
break;
default:
break;
}
After compilation, viewing the class file with IDEA shows no change, which indicates that int values are compared directly.
2.2. char
char a = 'b';
switch (a)
{
case 'a':
System.out.println('a');
break;
case 'b':
System.out.println('b');
break;
default:
break;
}
- After decompilation
char a = 98;
switch(a) {
case 97:
System.out.println('a');
break;
case 98:
System.out.println('b');
}
The ASCII code of the char is compared.
2.3. String
String str = "world";
switch (str)
{
case "hello":
System.out.println("hello");
break;
case "world":
System.out.println("world");
break;
default:
break;
}
- After decompilation
String str = "world";
byte var3 = -1;
switch(str.hashCode()) {
case 99162322:
if (str.equals("hello")) {
var3 = 0;
}
break;
case 113318802:
if (str.equals("world")) {
var3 = 1;
}
}
switch(var3) {
case 0:
System.out.println("hello");
break;
case 1:
System.out.println("world");
}
It first compares the String’s hashCode, then uses equals to compare for equality.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub