Java String a=new String("ABC")的建立

题目

String s = new String(“hello”)和String s = “hello”;的区别?spa

区别

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

引入

==与equals()的区别:对象

  1. ==:比较引用类型比较的是地址值是否相同
  2. equals:比较引用类型默认也是比较地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同。

Demo

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

内存图

这里写图片描述

代码详解

  1. 首先,经过main()方法进栈。
  2. 而后再栈中定义一个对象s1,去堆中开辟一个内存空间,将内存空间的引用赋值给s1,“hello”是常量,而后去字符串常量池 查看是否有hello字符串对象,没有的话分配一个空间存放hello,而且将其空间地址存入堆中new出来的空间中。
  3. 在栈中定义一个对象s2,而后去字符串常量池中查看是否有”hello”字符串对象,有,直接把”hello”的地址赋值给s2.
  4. 即s1中存的是堆中分配的空间,堆中分配的空间中存的是字符串常量池中分配空间存放”hello”的空间的地址值。而s2中之间存的是字符串常量池中分配空间存放”hello”的空间的地址值。
  5. 因为s1与s2中存放的地址不一样,因此输出false。由于,类String重写了equals()方法,它比较的是引用类型的 的值是否相等,因此输出true。即结果为false、true。

Demo1

public class StringDemo1 { public static void main(String[] args) { String s1 = new String("hello"); String s2 = new String("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 } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

这里写图片描述

Demo1详解

s1~s6用equals()的比较不解释,都是比较的值,均为true。如下讲解==blog

  1. s一、s2:两者均为new出来的,各自在堆中分配有空间,并各自将内存地址赋值给s一、s2。空间地址不一样,==比较为false。可是各自在堆中空间中保存的值均为在字符串常量池中的同一个对象的地址。根据Demo处的图即解释不难理解。
  2. s三、s4同上Demo出解释。
  3. s五、s6都是在常量池中取值,两者都指向常量池中同一对象,其地址值相同,因此结果为true。

Demo2

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 System.out.println(s3.equals((s1 + s2)));// true System.out.println(s3 == "hello" + "world");//false System.out.println(s3.equals("hello" + "world"));// true } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

这里写图片描述

Demo2详解

equals()比较方法不解释,比较值,均相等,均为true。图片

  1. s1与s2相加是先在字符串常量池中开一个空间,而后拼接,这个空间的地址就是s1与s2拼接后的地址。与s3的地址不一样,因此输出为false。
  2. s3与”hello”+”world”做比较,”hello”+”world”先拼接成”helloworld”,而后再去字符串常量池中找是否有”helloworld”,有,因此和s3共用一个字符串对象,则为true。

总结

    1. String s = new String(“hello”)会建立2(1)个对象,String s = “hello”建立1(0)个对象。 
      注:当字符串常量池中有对象hello时括号内成立!
    2. 字符串若是是变量相加,先开空间,在拼接。
    3. 字符串若是是常量相加,是先加,而后在常量池找,若是有就直接返回,不然,就建立。
相关文章
相关标签/搜索