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

时间:2025-02-15 14:10:25

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

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

public class StringTest {
	public static void main(String[] args) {
		String a=new String("abc");
		String b=new String("abc");
		if(a==b) {                //使用“==”来判断两字符串
			("a==b为true");
		}else {
			("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((b)) {
			("(b)为true");
		}else {
			("(b)为false");
		}
		
	}
}

打印结果为 

(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<;i++) {
			if("a".equals(strs[i])) {
				("“a”包含在字符串数组strs中");
				break;
			}
		}
	}
}

打印结果

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

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

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

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

打印结果为

true
true
true

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