Aman Arora Aman Arora - 2 months ago 19
Java Question

Compile Time Constant Usage in Switch Case Java

The rules of

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");
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
object located on heap. And
itself is a compile-time constant.

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

dbw dbw

Use this,

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

       case lm:
           case "abc": //This is more precise as per the comments

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.