Java的String进行比较时(==和.equals)
1、使用==进行比较时,并不是在比较字符串内容, 而是比较两个引用是否是指向同一个对象
例:此时输出结果为true,因为字符串"hello"是在字符串常量池中,两个String类型变量都指向了字符串常量池中的"hello"
String str1="hello";
String str2="hello";
System.out.print(str1==str2);
例:此时输出结果为false,因为使用了new关键字,相当于在字符串常量池中创建了两个字符串"hello",两个String类型变量都指向字符串常量池中不同的"hello"
String str1=new String("hello");
String str2=new String("hello");
System.out.print(str1==str2);
2、使用.equals进行比较时,是在比较两个字符串真正的内容
例:此时输出结果为true
String str1=new String("hello");
String str2=new String("hello");
System.out.print(str1.equals(str2));