有一个考试题,我对其很不理解,希望高手们帮帮,谢谢!class StringTest
{ //在一个字符串中查找子串
public static void main(String args[])
{
String S = "def545";
String subS = "def";
String S2 = S.substring(0,3);//此时S2 = “def"
System.out.print(S2); if(S2==subS)
System.out.println(S.substring(0,3));
else
System.out.println("找不到");
}
}
//输出结果是: 找不到
class StringTest
{ //在一个字符串中查找子串
public static void main(String args[])
{
String S = "def";
String subS = "def";
String S2 = S.substring(0,3);//此时S2 也等于 “def"
System.out.print(S2); if(S2==subS)
System.out.println(S.substring(0,3));
else
System.out.println("找不到");
}
}
//输出结果是: def
请问上面两段代码为什么结果不同?
{ //在一个字符串中查找子串
public static void main(String args[])
{
String S = "def545";
String subS = "def";
String S2 = S.substring(0,3);//此时S2 = “def"
System.out.print(S2); if(S2==subS)
System.out.println(S.substring(0,3));
else
System.out.println("找不到");
}
}
//输出结果是: 找不到
class StringTest
{ //在一个字符串中查找子串
public static void main(String args[])
{
String S = "def";
String subS = "def";
String S2 = S.substring(0,3);//此时S2 也等于 “def"
System.out.print(S2); if(S2==subS)
System.out.println(S.substring(0,3));
else
System.out.println("找不到");
}
}
//输出结果是: def
请问上面两段代码为什么结果不同?
== 比较的是对象 equals 比较的值
1.一般==只简单的比较对象的reference,而第一个是两个不同的对象,所以不相等。要比较String的值应该用equals
2.第二个就涉及到java里String初始化的内部机制了,因为String为final class,一经初始化就不能再改变值了,所以当同时初始化两个相同String时,内存中只有一份拷贝,两个对象共用它,所以就出现了它们的reference相同的情况了
因为这个substring第一个是0,而结束是它的长度的话就会返回它本身.String S = "def";
String subS = "def";
String S2 = S.substring(0,3);//此时S2 也等于 “def"
System.out.print(S2);
刚好第一个是0,而3而正好是S的长度,所以,S.substring(0,3);返回的是S本身;
相当于String S2=S;一样了.而S与subs是相等的.
所以S2与subS也是相等的.也就是S2==subS是true而:
String S = "def545";
String subS = "def";
String S2 = S.substring(0,3);//此时S2 = “def" 这里的S.substring(0,3);这里的3并不是S的长度,所以它会返回一个新的String对象,虽然它的内容也是"def",但是地址不相等.
像:String str1 = new String("def");String str2 = new String("def");
str1与str2内容都是"def"但地址不一样,也就是str1==str2是false
正是如此,所以subS与S2虽然内容相同,但地址不一样.而使用==比较的时候都是判断地址的.
所以S2与subS使用==比较并不是true,使用S2是一个新new 出来的String.相关内容可以看JDK String的substring方法源代码.
同时希望明白字符串池的概念:
String str="def";
String str2="def";
str==str2是true.
{ //在一个字符串中查找子串
public static void main(String args[])
{
String S = "def545";
String subS = "def";
//这里再申明个subS2内容跟subS一样,这样subS2和subS会共用一个内存地址
String subS2 = "def";
//这里的S2对象地址跟subS的不一样
String S2 = S.substring(0,3);//此时S2 = “def"
System.out.println(S2); if(S2==subS)
System.out.println("S2,subS指向同一地址");
else
System.out.println("S2,subS指向不同地址"); if(S2.equals(subS))
System.out.println("S2,subS内容相等");
else
System.out.println("S2,subS内容不相等");
if(subS==subS2)
System.out.println("subS,subS2指向同一地址");
else
System.out.println("subS,subS2指向不同地址");
//subS,subS2都加个“a” ,内容还是一样但是地址就不一样了
subS=subS+"a";
subS2=subS2+"a";
if(subS==subS2)
System.out.println("subS,subS2指向同一地址");
else
System.out.println("subS,subS2指向不同地址");
}
}