Has*_* K. 10 java compiler-construction string jvm
我的问题是关于Java处理字符串文字的方式.从Java语言规范(JLS)可以清楚地看出,字符串文字是隐式实现的 - 换句话说,就是在堆的String常量池部分中创建的对象,与调用时创建的基于堆的对象形成对比new String("whatever").
似乎与JLS所说的不一致的是,当使用字符串连接创建一个新的String时,使用一个转换的常量String类型,根据JLS应该将其视为一个常量String,显然JVM正在创建一个新的String对象而不是隐式实现它.我感谢有关此特定行为的任何解释以及这是否是特定于平台的行为.我在Mac OSX Snow Leopard上运行.
public class Test
{
public static void main(String args[])
{
/*
Create a String object on the String constant pool
using a String literal
*/
String hello = "hello";
final String lo = "lo"; // this will be created in the String pool as well
/*
Compare the hello variable to a String constant expression
, that should cause the JVM to implicitly call String.intern()
*/
System.out.println(hello == ("hel" + lo));// This should print true
/*
Here we need to create a String by casting an Object back
into a String, this will be used later to create a constant
expression to be compared with the hello variable
*/
Object object = "lo";
final String stringObject = (String) object;// as per the JLS, casted String types can be used to form constant expressions
/*
Compare with the hello variable
*/
System.out.println(hello == "hel" + stringObject);// This should print true, but it doesn't :(
}
}
Run Code Online (Sandbox Code Playgroud)
Object编译时常量表达式中不允许转换为.唯一允许的演员阵容是String和原始人.JLS(Java SE 7版)第15.28节:
(实际上,有一个第二个原因.object不final那么不能可能由被认为是恒定的变量."基本类型或类型的变量String,即final,用一个编译时间常量表达式(§15.28初始化),被称为恒定变量. " - 第4.12.4节.)