Compile Time Constant Usage in Switch Case Java(Switch Case Java 中的编译时间常数用法)
问题描述
case的使用规则说:
case 表达式的计算结果必须为
Compile Time Constant.
case(t) 表达式必须与 switch(t) 的类型相同,其中 t是类型(字符串).
case(t) expression must have same type as that of switch(t), where t is the type (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";,它可以正常工作.
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.
据我所知,String s=new String("abc") 是对位于堆上的 String 对象的引用.而 s 本身就是一个编译时常量.
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.
是不是说final String s=new String("abc");不是编译时间常数?
Does it mean that final String s=new String("abc");isn't compile time constant?
推荐答案
用这个,
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 类型的变量,即 final 和用编译时常量表达式(§15.28)初始化,是称为常量变量
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
问题是您的代码 final String s= new String("abc"); 没有初始化常量变量.
The problem is your code final String s= new String("abc"); does not initializes a constant variable.
这篇关于Switch Case Java 中的编译时间常数用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Switch Case Java 中的编译时间常数用法
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
