DK7 switch’s support for string

Time:2021-3-7

Before JDK7, switch can only support byte, short, char, int or their corresponding encapsulation classes and enum types. After JDK7, switch supports string type.

In the switch statement, the value of the expression cannot be null, otherwise NullPointerException will be thrown at runtime. Null cannot be used in the case clause, otherwise compilation errors will occur.

At the same time, the value of case sentence cannot be repeated. The same is true for string types, but strings can contain Unicode escape characters. Duplicate values are checked after the java compiler performs the relevant lexical transformation on the Java source code. That is to say, although the values of some case sentences look different in the source code, they are the same after lexical conversion, resulting in compilation errors. For example, “male” and “u7537” mean the same thing.

Now let’s take a look at how switch is implemented.

1、 Implementation of integer support by switch

Here is a very simple java code, define an int variable a, and then use the switch statement to judge. Execute this code, the output content is 5, then we will decompile the following code to see how it is implemented.

public class switchDemoInt {
    public static void main(String[] args) {
        int a = 5;
        switch (a) {
        case 1:
            System.out.println(1);
            break;
        case 5:
            System.out.println(5);
            break;
        default:
            break;
        }
    }
}
//output 5

The decompiled code is as follows:

public class switchDemoInt
{
    public switchDemoInt()
    {
    }
    public static void main(String args[])
    {
        int a = 5;
        switch(a)
        {
        case 1: // '
public class switchDemoInt
{
public switchDemoInt()
{
}
public static void main(String args[])
{
int a = 5;
switch(a)
{
case 1: // '\001'
System.out.println(1);
break;
case 5: // '\005'
System.out.println(5);
break;
}
}
}
1'
System.out.println(1); break; case 5: // '
public class switchDemoInt
{
public switchDemoInt()
{
}
public static void main(String args[])
{
int a = 5;
switch(a)
{
case 1: // '\001'
System.out.println(1);
break;
case 5: // '\005'
System.out.println(5);
break;
}
}
}
5'
System.out.println(5); break; } } }

We find that there is no difference between the decompiled code and the previous code except for two more lines of comments,Switch judges int by directly comparing the values of integers

2、 The implementation of switch to support character type

Direct code:

public class switchDemoInt {
    public static void main(String[] args) {
        char a = 'b';
        switch (a) {
        case 'a':
            System.out.println('a');
            break;
        case 'b':
            System.out.println('b');
            break;
        default:
            break;
        }
    }
}

The compiled code is as follows: ` public class switchdemochar

public class switchDemoChar
{
    public switchDemoChar()
    {
    }
    public static void main(String args[])
    {
        char a = 'b';
        switch(a)
        {
        case 97: // 'a'
            System.out.println('a');
            break;
        case 98: // 'b'
            System.out.println('b');
            break;
        }
  }
}

By comparing the above codes, we find that when comparing char types, it is actually comparing ASCII codes, and the compiler will convert char type variables into corresponding int type variables

3、 Realization of string support by switch

Or code first:

public class switchDemoString {
    public static void main(String[] args) {
        String str = "world";
        switch (str) {
        case "hello":
            System.out.println("hello");
            break;
        case "world":
            System.out.println("world");
            break;
        default:
            break;
        }
    }
}

Decompile the code:

public class switchDemoString
{
    public switchDemoString()
    {
    }
    public static void main(String args[])
    {
        String str = "world";
        String s;
        switch((s = str).hashCode())
        {
        default:
            break;
        case 99162322:
            if(s.equals("hello"))
                System.out.println("hello");
            break;
        case 113318802:
            if(s.equals("world"))
                System.out.println("world");
            break;
        }
    }
}

See this code, you know that the switch of the original string is through theequals()andhashCode()Method.Remember, only integers can be used in switchFor examplebyteshortchar(ackii codes are integers) andint. not so badhashCode()Method returnsintInstead oflong. It’s easy to remember through thishashCodeWhat is returned isintThis is a fact. If you look at it carefully, you can see that it’s going onswitchThe actual value of the hash is the hash value, and then the security check is carried out by using the equals method comparison. This check is necessary because the hash may collide. Therefore, its performance is not as good as switching with enumeration or using pure integer constants, but this is not too bad. Because the java compiler only adds oneequalsMethod, if you compare the literal amount of a string, it will be very fast, such as “ABC” = “ABC”. If you puthashCode()Method calls are also taken into account, so there will be another call overhead, because once a string is created, it will cache the hash value. So if thisswitchStatements are used in a loop, such as processing a value item by item, or the game engine rendering the screen in a loophashCode()The call cost of method is not very large.

OK, so that’s how switch supports integers, characters, and strings,In fact, switch only supports one data type, that is, integer. Other data types are converted to integer before switch is used.

Reference

JDK | switch’s support for string

After java version 1.7, the switch condition supports strings


jdk

This work adoptsCC agreementReprint must indicate the author and the link of this article