在Switch Case Java中编译时间常量用法

case使用规则说:

  1. case表达式必须求值为Compile Time Constant

  2. case(t)表达式必须与switch(t)的表达式相同,其中t是类型(String)。

如果我运行此代码:

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

它给出了编译错误: "case expression must be a constant expression"另一方面,如果我尝试使用final String s="abc"; ,它工作正常。

据我所知, String s=new String("abc")是对位于堆上的String对象的引用。 而s本身就是一个编译时常量。

这是否意味着final String s=new String("abc"); 是不是编译时间常数?

用这个,

  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; } 

根据文档

原始类型或类型String的变量,是最终的并使用编译时常量表达式(第15.28节)初始化,称为常量变量

问题是你的代码final String s= new String("abc"); 不初始化常量变量。

在Java SE 7及更高版本中,您可以在switch语句的表达式中使用String对象。

您只能在案例中使用常量表达式而不能使用变量。

使用构造函数创建String不被视为常量。

它不认为new String()是一个常量(即使String是不可变的)。

尝试这个:

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

编辑:我猜你的switch (s)是一个错字,没有多大意义。

另外,如果你在switch语句中使用常量,那么将它们作为常量字段提取可能会更加清晰,例如private static final String s = "abc"; 。 如果你使用枚举而不是字符串,甚至更清楚,但我意识到这并不总是可行的。

问题是您可以在switch任何位置更改variable S的值,因此这可能会执行所有cases 。 所以它给出"case expression must be a constant expression"错误,如果变量是final那么它的值不能改变。

编辑

case您需要编译时间常量,并且final变量被认为是运行时常量。 由于最终变量可能会被延迟初始化而编译器无法确定。

问题是你试图切换测试案例变量s 。 哪个,正在抛出错误。 "case expression must be a constant expression" 。 这与s本身无关……但是使用s作为case变量。 了解?

这是使用相同变量正常工作的示例。

 private void switchTest() { final String s = new String("abc"); switch (s) { case "abc": System.out.println("This works fine... woohoo."); break; default: System.out.println("Do something default."); } } 

如何将int或其他原始数据类型作为switch语句的编译时常量?

 public class MainClass{ public static void main(String[] argv){ final int a = 1; final int b; b = 2; int x = 0; switch (x) { case a: // ok case b: // compiler error } } }