定义四个变量
package chiji; public class dianbing { public static void main(String[] args) { String str1="wan"; String str2="yan"; String str3=new String("wan"); String str4="wan";
进行比较
package chiji; public class dianbing { public static void main(String[] args) { String str1="wan"; String str2="yan"; String str3=new String("wan"); String str4="wan"; System.out.println(str1==str2); System.out.println(str1==str3); System.out.println(str1==str4);
运行结果:
str1的变量值是"wang",str3的变量值是"yan";变量不同所以云行结果是fales
str1和str4的变量值都是"wang";所以变量相同 运行结果是true
str1和str3的变量虽然都是"wang",但str3的变量值是在堆内存里重新开辟了一个空间,不在常量池里,所以运行结果是fales
当用到String .equals
str1就和str3相同
package chiji; public class dianbing { public static void main(String[] args) { String str1="wan"; String str2="yan"; String str3=new String("wan"); String str4="wan"; System.out.println(str1==str2); System.out.println(str1.equals(str3)); System.out.println(str1==str4);
运行结果: