Aman Arora Aman Arora - 1 month ago 11
Java Question

Compile Time Constant Usage in Switch Case Java

The rules of

case
usage say:


  1. The case expression must evaluate to a
    Compile Time Constant
    .

  2. case(t) expression must have same type as that of switch(t), where t
    is the type (String).



If i run this code :

public static void main(String[] args) {
final String s=new String("abc");
switch(s)
{
case (s):System.out.println("hi");
}

}


It gives Compile-error as:
"case expression must be a constant expression"

On the other hand if i try it with
final String s="abc";
, it works fine.


As per my knowledge,
String s=new String("abc")
is a reference to a
String
object located on heap. And
s
itself is a compile-time constant.

Does it mean that
final String s=new String("abc");
isn't compile time constant?

dbw dbw
Answer

Use this,

    String s= new String("abc");
    final String lm = "abc";

    switch(s)
    {
       case lm:
           case "abc": //This is more precise as per the comments
           System.out.println("hi");
           break;
    }

As per the documentation

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable

The problem is your code final String s= new String("abc"); does not initializes a constant variable.

Comments