java中比较两字符串是否相等

字符串比较的三种方式:==,equals,Objects.equals

==判断字符串的索引值是否相同

public class StringTest {
	public static void main(String[] args) {
		String a=new String("abc");
		String b=new String("abc");
		if(a==b) {                //使用“==”来判断两字符串
			System.out.println("a==b为true");
		}else {
			System.out.println("a==b为false");
		}
		
	}
}

 打印结果

a==b为false

因为两个字符串的索引值不同。

equals判断两个字符串的值是否相同

public class StringTest {
	public static void main(String[] args) {
		String a=new String("abc");
		String b=new String("abc");
		if(a.equals(b)) {
			System.out.println("a.equals(b)为true");
		}else {
			System.out.println("a.equals(b)为false");
		}
		
	}
}

打印结果为 

a.equals(b)为true

因为两个字符串的值相同。

所以在java中进行字符串比较时,经常使用equals比较两字符是否相同。一个固定的字符串和字符串数组(或list集合)进行比较时,为了避免空指针异常。采用将固定的字符串放在左边的写法,如下:

public class StringTest {
	public static void main(String[] args) {
		String[] strs= {null,"a","b",null,null};
		//判断“a”是否包含在字符串数组中
		for(int i=0;i<strs.length;i++) {
			if("a".equals(strs[i])) {
				System.out.println("“a”包含在字符串数组strs中");
				break;
			}
		}
	}
}

打印结果

“a”包含在字符串数组strs中

如果将 if中的判断语句写成strs[i].equals("a")则会出现空指针异常。

当左右两边的字符串都无法保证不为空时,可以使用Objects.equals()

import java.util.Objects;
public class StringTest {
	public static void main(String[] args) {
		boolean res1=Objects.equals(new String("a"), new String("a"));
		boolean res2=Objects.equals("a", "a");
		boolean res3=Objects.equals(null, null);//注意当两边都为空时,结果为true
		System.out.println(res1);
		System.out.println(res2);
		System.out.println(res3);
		
	}
}

打印结果为

true
true
true

 Objects.equals()判断的也是字符串的值,但要注意当两个字符串都为空时,判断为true。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值