new String、String、String.intern()

String s1 = new String("")

String s1 = new String(“abc”) 是直接在java队中创建对象然后返回引用,就像我们创建普通对象一样

public static void testNewString() {
    String s1 = new String("abc");	// java堆中创建的对象1
    String s2 = new String("abc");	// java堆中创建的对象2
    String s3 = "abc";	// 常量池中对象3
    // false----false
    System.out.println((s1 == s2) + "----" + (s2 == s3));
}

String s2 = “abc”

String s2 = "abc" 是先从常量池中查找是否有“abc”这个常量,有则返回引用,无则在常量池中创建一个常量并返回其引用

public static void testConstString() {
    String s1 = "abc";
    String s2 = "abc";
    // true
    System.out.println(s1 == s2);
}

String s3 = s1.intern()

调用此方法,先重常量池中查找是否有 s1 这个字符串,若有,返回其在常量池中的引用,若无,在常量池中创建一个相同字符串对象并返回其引用

public static void testIntern() {
    String s1 = new String("abc");	// 在java队中创建对象s1
    String s2 = s1.intern();	// 将s1拷贝到常量池中并返回其引用
    String s3 = "abc";	// 从常量池中寻找"abc"并返回其引用
    // false---true
    System.out.println((s1 == s2) + "---" + (s2 == s3));
}
发布了17 篇原创文章 · 获赞 1 · 访问量 643

猜你喜欢

转载自blog.csdn.net/c_c_y_CC/article/details/104976160
今日推荐