Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 414
user3282758 Avatar asked Sep 05 '16 16:09

user3282758


People also ask

Why toString is not working in Java?

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.

How do you declare a constant expression in Java?

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.

What is offset in String Java?

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.


1 Answers

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.)

like image 146
Ted Hopp Avatar answered Nov 19 '22 19:11

Ted Hopp