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

  • Post author:
  • Post category: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。



版权声明:本文为m0_47901874原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。