user3282758 user3282758 - 2 months ago 16
Java Question

Why in Java 'final String' initialized as String.toString() is not considered as constant

I wrote the following code in Java which runs fine :

public class test {
public static void main(String[] args) {
final String s1 = "s1" ;
final String s2 = "s2" ;

String s = "s1" ;
switch(s) {
case s1 : System.out.println("s1") ;
break ;
case s2 : System.out.println("s2") ;
break ;
}
}
}


But when I write the following code :

public class test {
public static void main(String[] args) {
final String s1 = "s1".toString() ;
final String s2 = "s2".toString() ;

String s = "s1" ;
switch(s) {
case s1 : System.out.println("s1") ;
break ;
case s2 : System.out.println("s2") ;
break ;
}
}
}


I get the following error :

test.java:8: error: constant string expression required
case s1 : System.out.println("s1") ;
^
test.java:10: error: constant string expression required
case s2 : System.out.println("s2") ;


I am looking for an explanation for this as I could not understand why is the second code giving me this error.

Answer

Because "s1".toString() is not a compile-time constant expression. Only compile-time constants (or enum constant names) can be used as labels in a switch statement. See the Java Language Specification, Section 15.28 for the rules for what constitutes a constant expression. (And see JLS ยง14.11 for the rules for the switch statement.)

Comments