String类型字符串是一个不可变量,一旦赋值后便不可改变值内容,但可改变引用地址。
String两种赋值方式的区别
①String a=“a”;这种方式会先在字符串常量池寻找是否有字符串a,有的话就引用其地址,否则新建(new String())并返回新的引用地址。如下的地址是相等的。
String a="a";
String b="a";
//String b="c"等价于String b=new String(c);
if(a==b)System.out.println(true);
else System.out.println(false);
②String a=new String(“a”)这种方式直接新开辟一个内存空间存放字符串,每次都会返回新地址,如下返回false;
String a=new String("a");
String b=new String("a");
if(a==b)System.out.println(true);
else System.out.println(false);
String类型字符串是一个不可变量,一旦赋值后便不可改变值内容。
public class Main {
public static void main(String[] args) throws InterruptedException {
String b = "a";
String d = b;
String e = b;
if (d == e)
System.out.println(true);
else
System.out.println(false);
}
}
输出结果:true
再来看以下
public class Main {
public static void main(String[] args) throws InterruptedException {
String b = "a";
String d = b;
b="b";//改变b的值,在常量池找不到"b",则新建b=new String("b"),新建了一个String类型,b的引用地址改变
String e = b;
if (d == e)
System.out.println(true);
else
System.out.println(false);
}
}
此时输出结果:false
由此得出结论:String类型是不可变量,但重新赋值后其实是重新new了一个String,然后返回新的引用地址。这也可以解释为什么当一个String作为参数传入方法中改变值后,原先的值不改变。
public static void main(String[] args) throws InterruptedException {
String a = "1";
if (a == changString(a))
System.out.println(true);
else
System.out.print(false);
}
private static String changString(String str) {
// str = "2";// 该种赋值方式,常量池无"2",新建字符串,返回新地址,结果false
// str = "1";// 常量池存在字符串"1",结果true
// str = new String("1");// 该种赋值方式直接新建字符串,返回新地址,结果false
// str = new String("2");// 该种赋值方式直接新建字符串,返回新地址,结果false
return str;
}