java 如何判断字符串相等
判断字符串相等的方法
在Java中,判断字符串相等通常涉及两种方式:使用==运算符和使用equals()方法。两者有不同的适用场景和底层逻辑。
使用equals()方法
equals()方法用于比较两个字符串的内容是否相同。这是最常用的字符串比较方式,因为它比较的是字符串的实际字符序列。
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");
System.out.println(str1.equals(str2)); // 输出 true
System.out.println(str1.equals(str3)); // 输出 true
对于忽略大小写的比较,可以使用equalsIgnoreCase()方法:
String str1 = "Hello";
String str2 = "hello";
System.out.println(str1.equalsIgnoreCase(str2)); // 输出 true
使用==运算符
==运算符比较的是两个字符串对象的引用是否指向同一内存地址,而不是内容。因此,它通常不适用于直接比较字符串内容。
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");
System.out.println(str1 == str2); // 输出 true(字符串常量池优化)
System.out.println(str1 == str3); // 输出 false
使用compareTo()方法
compareTo()方法按字典顺序比较两个字符串,返回一个整数表示比较结果。如果返回值为0,表示两个字符串内容相同。
String str1 = "hello";
String str2 = "hello";
System.out.println(str1.compareTo(str2) == 0); // 输出 true
使用Objects.equals()方法
Objects.equals()是Java 7引入的工具方法,可以安全地比较两个对象(包括字符串),避免空指针异常。
String str1 = "hello";
String str2 = null;
System.out.println(Objects.equals(str1, str2)); // 输出 false
注意事项
- 对于内容比较,优先使用
equals()或equalsIgnoreCase()方法。 - 避免使用
==比较字符串内容,除非明确需要比较引用。 - 处理可能为
null的字符串时,使用Objects.equals()更安全。







