从一个博客上看到的6个题,先看看吧,如果都会了,这部分的知识就掌握的不错啦!输出结果在代码注释后面:
test1:
package StringTest;
publicclass test1 {
/**
* @param args
*/
publicstaticvoid main(String[] args){
String a ="a1";
String b ="a"+1;
System.out.println(a==b);
}//true
}
test2:
package StringTest;
publicclass test2 {
/**
* @param args
*/
publicstaticvoid main(String[] args){
String a ="ab";
String bb ="b";
String b ="a"+ bb; //编译器不能确定为常量
System.out.println(a==b);
}//false
}
test3:
package StringTest;
publicclass test3 {
/**
* @param args
*/
publicstaticvoid main(String[] args){
String a ="ab";
final String bb ="b";
String b ="a"+ bb; //bb加final后是常量,可以在编译器确定b
System.out.println(a==b);
}//true
}
test4:
package StringTest;
publicclass test4 {
/**
* @param args
*/
publicstaticvoid main(String[] args){
String a ="ab";
final String bb = getBB();
String b ="a"+ bb;//bb是通过函数返回的,虽然知道它是final的,但不知道具体是啥,要到运行期才知道bb的值
System.out.println(a==b);
}//false
privatestatic String getBB(){ return"b"; }
}
test5:
package StringTest;
publicclass test5 {
/**
* @param args
*/
privatestatic String a ="ab";
publicstaticvoid main(String[] args){
String s1 ="a";
String s2 ="b";
String s = s1 + s2;//+的用法
System.out.println(s == a);
System.out.println(s.intern() == a);//intern的含义
}//flase true
}
test6:
package StringTest;
publicclass test6 {
/**
* @param args
*/
privatestatic String a =new String("ab");
publicstaticvoid main(String[] args){
String s1 ="a";
String s2 ="b";
String s = s1 + s2;
System.out.println(s == a);
System.out.println(s.intern() == a);
System.out.println(s.intern() == a.intern());
}//flase false true
}