字符串有一个容易混淆的地方,下面我们就这个容易混淆的地方,做一些代码解释.
字符串一旦被赋值就不能被改动。
注意:这里的改动指的是字符串的内容,而不是字符串对象的引用。
B:String s = new String("hello");和String s = "hello";有区别吗?是什么呢?
new 出出来的字符串是现在堆内存中创建对象,然后再指向常量池中的对象;
直接赋值是将引用直接指向字符串常量池的对象;
前者创建了两个对象。
后者创建了一个对象。
看程序,写结果
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
String s7 = "hello";
String s8 = "world";
String s9 = "helloworld";
System.out.println(s9==s7+s8);
System.out.println(s9=="hello"+"world");
|
|