String 对象个数

来源:https://www.cnblogs.com/taochen-go/p/9475947.html 【内存图画的很好】

String s = new String(“hello”)和String s = “hello”;

String s = new String(“hello”)会创建2(1)个对象,String s = “hello”创建1(0)个对象。 
注:当字符串常量池中有对象hello时括号内成立!

public class StringDemo2 {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = "hello";
        System.out.println(s1 == s2);// false
        System.out.println(s1.equals(s2));// true
    }
}
**运行结果:**

> false 
> true

    1. String s = new String(“hello”)会创建2(1)个对象,String s = “hello”创建1(0)个对象。 
      注:当字符串常量池中有对象hello时括号内成立!
    2. 字符串如果是变量相加,先开空间,在拼接。
    3. 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建
原文地址:https://www.cnblogs.com/junbaba/p/14167512.html