The switch statement actually acts as if () else, which is a choice statement with the following syntax:
switch (expression) {case constant expression 1: statement 1; Case constant Expression 2: statement 2; ... case constant expression N: statement n; Default: statement n+1;}
It is important to note that the type of the expression in switch can be byte,short,char,int,enum type, after Java7
You can make the string type also supported as an expression, and you can study the following principle:
Public class stringinswitchcase { public static void main (String[] args) { String mode = args[0]; switch (Mode) { case "ACTIVE": system.out.println ("Application is running on active mode"); break; case "PASSIVE": system.out.println ("Application is running on passive mode "); break; case "SAFE": system.out.println ("Application Is running on safe mode "); } } }
To decompile the above code:
public class stringinswitchcase{ public Stringinswitchcase () { } public static void Main (string args[]) { String mode = args[0]; String s; switch ((S = mode). Hashcode ()) { default: break; case -74056953: if (S.equals ("PASSIVE") { system.out.println ("Application is running on passive mode "); } break; case 2537357: if (S.equals ("SAFE") { system.out.println (" Application is running on safe mode "); } break; case 1925346054: if (S.equals ("ACTIVE")) { system.out.priNtln ("Application is running on active mode"); } break; } } }
As you can see clearly, the Java bottom is called the Hashcode () method on string, and the returned hashcode is an int type, in fact it is hashcode
The case is then compared with equals, and the corresponding statement is executed when the condition is met.
This shows that using string as an expression is not as straightforward as using shaping or enumeration efficiency, because using string will call the Hashcode method extra, and in exchange for possible
A hash conflict occurred. In fact, we use enumerations more in our programming to make conditional judgments.
Switch in Java