The rules of case
usage say:
The case expression must evaluate to a
Compile Time Constant
.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?