Monday, 30 May 2016

Switch(x) Rules

Java really have many rules, that is why it is the most hard lang. to dominate.


In java, x can only be

1) primitive type: byte, short, char, int
2) and their wrapper classes.
3) reference type: String and Enum.

please note: x cannot be boolean, long, float, and double.

5) x can be an expression, like a+b etc; but it must return types above.

6) Case values: a) the value of a case label must be compiling-time constant. the following case is not valid. however, you may make variable final, for the final variable won't be changed once it is declared and initialized. I guess the reason it is easy to understand. On compiling time, the case number are variables, then how to determine the case brunches?

int a=10, b=20, c=30;
 switch (a) {
 case b+c: System.out.println(b+c); break;
 case 10*7: System.out.println(10*7512+10); break;
}



the following is valid, for b and c are constants on compiling time.
final int a = 10;
final int b = 20;
final int c = 30;
switch (a) {
 case b+c: System.out.println(b+c); break;
}

how about the following case? it is not considered as compiling time constants, for the constant a and b, not initialized as declaring.

public class VarCase {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        final int a, b;
        a = 20;
        b = 10;
        int x = a + b;
        switch (x) {
            case a + b:
                System.out.println("" + (a + b));
                break;
        }
    }
}





b) null cannot be case number. c) case number should have the same type as switch input type.

(7) switch body can only contain case and default brunch
(8) case type must fit the type of x
(9) case cannot be duplicated.
(10) x cannot be Object type, even though x could be String and Enum
(11) when x matches a case; it will be handled there; when a case has no break then it will falling down to implement the rest cases until a break is met.
(12) default can have break or not have; however, if default is located before or among cases, it should have a break.

Actually, I don't know why switch has been created so complicated; more than necessary?

No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...