String

原文:http://blog.csdn.net/pwair/article/details/654284

常量池(constant pool):指的是在编译期被确定,并被保存在已编译的.class文件中的一些数据。它包括了关于类、方法、接口等中的常量,也包括字符串常量。 

Java确保一个字符串常量只有一个拷贝。因此:

public static void main(String[] args) {
  String a = "Hello";
  String b = "Hello";
  System.out.println(a == b);
}
结果: true

同理:
public static void main(String[] args) {
  String a = "Hello";
  String b = "He" + "llo";
  System.out.println(a == b);
}
结果: true

例1中的a和b中的”Hello”都是字符串常量,它们在编译期就被确定了,所以a == b结果为true;
例2中的”He”和”llo”也都是字符串常量,当一个字符串由多个字符串常量连接而成时,它自己也是字符串常量,所以b也同样在编译期就被解析为一个字符串常,所以b也是常量池中”Hello”的一个引用。  


public static void main(String[] args) {
  String a = "Hello";
  String b = new String("Hello");
  String c = "He" + new String("llo");
  System.out.println(a == b);
  System.out.println(a == c);
  System.out.println(c == b);
}
结果:
false
false
false

例3中的a仍旧是常量池中的常量“Hello”的引用。b因为无法在编译期确定,所以是运行时创建的新对象"Hello“的引用。c也因为new String("llo")而无法在编译期被确定。

=================================================================================

String.intern():  
  存在于.class文件中的常量池,在运行时被JVM装载,并且可以扩充。String的intern()方法就是扩充常量池的一个方法;当一个String实例str调用intern()方法时,Java查找常量池中是否有相同Unicode的字符串常量,如果有,则返回其的引用,如果没有,则在常量池中增加一个Unicode等于str的字符串常量并返回它的引用;

public static void main(String[] args) {
  String a = "Hello";
  String b = new String("Hello");
  System.out.println(a == b);
  System.out.println(a == b.intern());
}
结果:
false
true

原文地址:https://www.cnblogs.com/shindo/p/5284533.html