String str1 = “abc“;和String str3 = new String(“abc“);的区别

String str1 = "abc";
String str2 = "abc";
String str3 = new String("abc");
System.out.println(str1==str2);//true
System.out.println(str1==str3);//false
  • 第一种方式创建多个”abc”字符串,在内存中其实只存在一个对象而已(对象在堆内存的字符串常量池中,这种写法节省内存空间, 同时它可以在一定程度上提高程序的运行速度,因为JVM会自动根据栈中数据的实际情况俩决定是否有必要创建型对象)
  • 而对于String str = new String(“abc”);每次在堆中创建新对象,而不管字符串是否相等,是否有必要创建新对象,从而加重程序负担
  • 这里粗略的表示jvm内存

猜你喜欢

转载自blog.csdn.net/weixin_42581455/article/details/121433046