1.String s = new String(“hello”)和String s = “hello”的区别?
--首先这是java创建字符串对象的两种方式
(1)格式一:直接赋值法
String 字符串名称=“字符串内容”
--用这种方式在创建,先去String缓冲池中寻找有没有和将要创建的字符串内容相同的字符串
如果有则不会在String缓冲区中创建,若没有则在缓冲区中创建。
--如果当缓冲区中存在将要创建的字符串的时候会自动引用,例如:
String a = "hello";
String b ="hello";
则 a==b 为true
(2)格式二:使用String类的构造方法
String 字符串名=new String("字符串内容“);
--用这种方式创建,首先会在String缓冲池中查找有没有要和将要创建的字符串
内容相同的字符串,若没有则创建该对象(若有则不创建),之后在在堆里面创建一个对象
,堆中的地址指向String缓冲池中创建的对象,而”字符串名“则引用堆中的地址
--例如:
String a = new String("hello");
String b =new String("hello");
a==b 为false
a和b在堆中指向同一个字符串缓冲区当中的对象,但是由于时new出来的对象,所以在堆中地址并不相同,所以a==b 为false
两种方式创建过程如图:
原文链接:https://blog.csdn.net/tiantiandjava/article/details/46309163;
https://blog.csdn.net/qq_42776429/article/details/82318535;
2.
String str1="hello";
String str2="world";
String str3 = "helloworld";
String str4 = str1+str2;
String str5 ="hello"+"world";
if(str4==str3) {
System.out.println("true");
}else {
System.out.println("false");
}
if(str3==str5) {
System.out.println("true");
}else {
System.out.println("false");
}
运行结果:false true
第一个str4==str3 字符串变量加上常量或者变量加上变量,会创建 StringBuilder 对象,然后调用 append 方法,结果在堆中。
第二个str3==str5 字符串常量相加,在编译的时候jvm 会进行优化,也就是hello+world优化过后会直接变成helloworld,不会创建 StringBuilder 对象