String比较
public class Demo {
public static void main(String args[]) { String str=new String("hello"); if(str=="hello") { System.out.println("true"); } else { System.out.println("false"); } }}-
答案:false
链接:https://www.nowcoder.com/questionTerminal/aab7300da6d1455caffcbda21c10fca5
来源:牛客网
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class Demo { public static void main(String args[]) { String str1 = new String("hello"); String str2 = new String("hello"); String str3 = "hello"; String str4 = "hello"; String str5 = "he"+"llo"; String str6 = "he"; String str7 = "llo"; System.out.println(str1==str2); System.out.println(str1==str3); System.out.println(str3==str4); System.out.println(str3=="hello"); System.out.println(str4==(str6+str7)); }} |
上面代码的输出结果是:
false
false
true
true
false
|
1
|
String str1 = new String("hello"); |
|
1
|
String str3 = "hello"; |
==用来判断两个变量是否相等时,如果两个变量是基本类型变量,且都是数值类型(不要求数据类型严格相同),则只要两个变量的值相等,就返回true;对于两个引用类型变量,必须指向同一个对象,==才会返回true。
java中使用new
String("hello")时,jvm会先使用常量池来管理"hello"常量,再调用String类的构造器创建一个新的String对象,新创建的对象被保存在堆内存中;而直接使用"hello"的字符串直接量,jvm会用常量池来管理这些字符串。故上述程序中str=="hello"返回结果为false
‘==’操作符专门用来比较两个变量的值是否相等,也就是用来比较两个变量对应的内存所存储的数值是否相同,要比较两个基本类型的数据或两个引用变量是否相等,只能用==操作。
如果一个变量指向的数据是对象类型的,那么这时候涉及了两块内存,对象本身占用一块(堆内存),变量也占用一块。对于指向类型的变量,如果要比较两个变量是否指向同一对象,即要看两个变量所对应的内存的数值是否相等,这时就需要用==操作符进行比较。
equals方法用于比较两个独立对象的内容是否相同。
在实际开发中,我们经常要比较传递过来的字符串是否相等,一般都是使用equals方法。
例如:
String a = new String(“foo”);
String b = new String(“foo”);
两条语句创建了两个对象,他们的首地址是不同的,即a和b中存储的数值是不相同的。所以,表达式a==b将返回false,而这两个对象的内容是相同的,所以表达式a.equals(b)将返回true。
梅花香自古寒来

浙公网安备 33010602011771号