今天写代码的时候遇到一个问题,结合到sun对string常量表达式的优化,所以想问一个问题,到底如何定义“常量表达式”
先看代码演示一
[code="java"]
public class Test {
public void test(int i) {
Type type = new Type();
switch(i) {
case type.decimal: //需要常量表达式
break;
case Type.octal: //此处正确
break;
}
}
}
class Type {
static final int decimal = 1;
static final int octal = 2;
}
[/code]
代码演示二
[code="java"]
public class Test {
public static void main(String args[]) {
String str = "abcd"; //存储在constant pool中
String str1 = "abc" //存储在constant pool中
String str2 = "a"+str1; //str1 为非常量表达式,编译器不优化
System.out.println((str == str1));
//result false
}
}
[/code]
[code="java"]
public class Test {
public static void main(String args[]) {
//当bb为常量表达式时时候,编译器将会对其进行优化
String a = "abc"; //存储在constant pool中
final String bb = "bc";//存储在constant pool中
String b = "a" + bb; // bb为常量表达式,编译器直接优化
System.out.println((a == b)); //result = true
}
}
[/code]
最终问题什么是常量表达式,系统是如何判断该对象是否为常量表达式的?
[b]问题补充:[/b]
代码一中的type.decimal的值也不会变啊!