/*
 * String s = new String(“hello”)和String s = “hello”;的区别?
 * 有。前者会创建2个对象,后者创建1个对象。
 * 
 * ==:比较引用类型比较的是地址值是否相同
 * equals:比较引用类型默认也是比较地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同。
 */
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

}

}

原理如下图所示:

string直接赋值:首先从方法区的常量池里面查找(有直接赋值(地址的指向) 没有创建之后再赋值)

new 创建一个对象 首先在堆内存里面开辟一块空间 --再到方法区的常量池里面去寻找

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

相关文章:

  • 2021-09-13
  • 2021-06-15
  • 2021-11-29
  • 2021-08-24
  • 2021-10-17
  • 2021-10-15
  • 2021-09-19
猜你喜欢
  • 2021-12-20
  • 2021-09-05
  • 2021-08-10
  • 2022-12-23
  • 2022-12-23
  • 2021-06-02
  • 2021-12-12
相关资源
相似解决方案