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.
You need to override toString() in the Node class. Save this answer. Show activity on this post. Your Node class does not override the toString() method and falls back to use the Object.
To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.
The offset is the first index of the storage that is used. Internally a String is represented as a sequence of chars in an array. This is the first char to use from the array. It has been introducted because some operations like substring create a new String using the original char array using a different offset.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With