1207-08、String字面值对象和构造方法创建对象的区别

1、 String s = new String("hello") 和 String s = "hello"; 的区别?
  有区别,前者创建2个或1个对象,如果常量池中有"hello",则只需创建new String(),否则还需创建常量"hello"; 后者创建0或1个对象
==:比较引用类型的地址值是否相同 equals:比较引用类型 默认也是比较地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同

相关面试题:

 public class StringDemo{
         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  比较内容
     }
 }

画图解释:

看程序写结果:

public class StringDemo3 {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1 == s2);// false s1,s2都是 new 出来的,地址值不一样
        System.out.println(s1.equals(s2));// true  s1,s2最终指向的内容是一样的

        String s3 = new String("hello");
        String s4 = "hello";
        System.out.println(s3 == s4);// false  地址值不同
        System.out.println(s3.equals(s4));// true 最终指向的内容相同

        String s5 = "hello";
        String s6 = "hello";
        System.out.println(s5 == s6);// true  地址值一样,都是直接从常量池中拿
        System.out.println(s5.equals(s6));// true  内容也一样
    }
}

面试提升题:

/*
 * 看程序写结果
 * 字符串如果是变量相加,先开空间,在拼接。
 * 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。
 */
public class StringDemo4 {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "world";
        String s3 = "helloworld";
        System.out.println(s3 == s1 + s2);// false 因为这里是s1+s2 s1,s2都是变量 字符串如果是变量相加,先开空间,在拼接。
        System.out.println(s3.equals((s1 + s2)));// true

        System.out.println(s3 == "hello" + "world");// true 因为"hello" 和 "world"是常量 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。
        System.out.println(s3.equals("hello" + "world"));// true

        // 通过反编译看源码,我们知道这里已经做好了处理。
        // System.out.println(s3 == "helloworld");
        // System.out.println(s3.equals("helloworld"));
    }
}

反编译文件:

// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space 
// Source File Name:   StringDemo4.java

package com.string02;

import java.io.PrintStream;

public class StringDemo4
{

    public StringDemo4()
    {
    }

    public static void main(String args[])
    {
        String s1 = "hello";
        String s2 = "world";
        String s3 = "helloworld";
        System.out.println(s3 == (new StringBuilder()).append(s1).append(s2).toString());
        System.out.println(s3.equals((new StringBuilder()).append(s1).append(s2).toString()));
        System.out.println(s3 == "helloworld");
        System.out.println(s3.equals("helloworld"));
    }
}

猜你喜欢

转载自www.cnblogs.com/hanlu0516/p/10916647.html
今日推荐