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.