主要就是string literals
1 及constant pool问题了,看以下代码。
public
class
StringExample
...
{

public static void main(String[] args) ...{
String s0 = "Programming";
String s1 = "Program"+"ming";
String s2 = new String("Programming");
String s3 = new String("Programming").intern();
System.out.println("s0 == s1 :"+(s0==s1));
System.out.println("s0 == s2 :"+(s0==s2));
System.out.println("s0 == s3 :"+(s0==s3));
}
}

运行结果:
s0
==
s1 :
true
s0
==
s2 :
false
s0
==
s3 :
true
public
class
StringTest
...
{
String s1;

public StringTest()...{
s1 = "Programming";
}
}


public
class
StringExample
...
{
String s0;

public StringExample()...{
s0 = "Programming";
}

public static void main(String[] args) ...{
System.out.println(new StringExample().s0 == new StringTest().s1);
}
}

运行结果:
ture










































1From the Java Language Specification: “A string literal consists of zero or more characters enclosed in double quotes. Each character may be represented by an escape sequence.”
The “constant pool” is something that is computed at compile time and stored with the compiled .class file. It contains information on methods, classes, interfaces, …, and string literals. When the JVM loads the .class file and the s0 and s2 variables are resolved, the JVM does something called constant pool resolution. The process of constant pool resolution for string follows these steps, as taken from the Java Virtual Machine Specification (5.4):
-
• If another constant pool entry tagged
CONSTANT_String2 and representing the identical sequence of Unicode characters has already been resolved, then the result of resolution is a reference to the instance of class
String created for that earlier constant pool entry.
2This is used internal to the .class file to identify literals.
- • Otherwise, if the method intern has previously been called on an instance of class String containing a sequence of Unicode characters identical to that represented by the constant pool entry, then the result of resolution is a reference to that same instance of class String.
- • Otherwise, a new instance of class String is created containing the sequence of Unicode characters represented by the CONSTANT_String entry; that class instance is the result of resolution.