==和equals区别小练习

 	(1)
        String s1 = new String("abc");
        String s2 = "abc";
        System.out.println(s1 == s2);       //false
        System.out.println(s1.equals(s2));  //true       
    (2)
        String s1 = "abc";
        String s2 = "abc";
        System.out.println(s1 == s2);         //true
        System.out.println(s1.equals(s2));       //true
    (3)
        String s1 = "a" + "b" + "c";
        String s2 = "abc";
        System.out.println(s1 == s2);         //true
        System.out.println(s1.equals(s2));      //true
    (4)
        String s1 = "ab";
        String s2 = "abc";
        String s3 = s1 + "c";
        System.out.println(s3 == s2);        //false
        System.out.println(s3.equals(s2));   //true
public class StringDemo1 {
    public static void main(String[] args) {
        String s1 = new String("hello");//在常量池中查找"hello",如果没有则在常量池中创建“hello”字符串
        String s2 = new String("hello");//此时常量池中已经存在"hello"字符串,所以不需要新创建,直接拿过来
        System.out.println(s1 == s2);// false
        System.out.println(s1.equals(s2));// true

        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 StringDemo2{
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "world";
        String s3 = "helloworld";
        System.out.println(s3 == s1 + s2);// false--s1、s2都是变量,做字符串拼接时,是先开空间再拼接,新的空间地址值肯定不一样了
        System.out.println(s3.equals((s1 + s2)));// true

        System.out.println(s3 == "hello" + "world");// true---先把"hello" 和 "world"两个常量加起来,看方法区中的常量池中是否有相应的,这时在常量池中找到了"helloworld",
        System.out.println(s3.equals("hello" + "world"));// true

        
    }
}
package cn.itcast;

public class Demo {
    public static void main(String[] args) {
        String s1 = "ab";
        String s2 = "abc";
        String s3 = s1 + "c";
        System.out.println(s3 == s2);//false
    }
}

猜你喜欢

转载自blog.csdn.net/Qioooba/article/details/88975617