应使用equals()方法比较字符串内容,因为==比较的是引用地址;equals()比较字符序列是否相同且区分大小写,如str1.equals(str2)返回true;忽略大小写可用equalsIgnoreCase(),如str1.equalsIgnoreCase(str2)返回true;注意避免空指针,推荐"abc".equals(str)写法。

在Java中比较字符串内容是否相等,不能使用 == 运算符,因为 == 比较的是两个字符串对象的引用地址,而不是它们的内容。要正确比较字符串内容,应使用 equals() 方法。
该方法用于判断两个字符串对象的字符序列是否完全相同,区分大小写。
示例:<pre class="brush:php;toolbar:false;">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
即使 str3 是通过 new 创建的新对象,equals() 仍能正确返回 true,因为它比较的是内容。
如果需要忽略大小写进行比较,可以使用 equalsIgnoreCase() 方法。
立即学习“Java免费学习笔记(深入)”;
示例:<pre class="brush:php;toolbar:false;">String str1 = "Hello"; String str2 = "HELLO"; System.out.println(str1.equalsIgnoreCase(str2)); // true
基本上就这些。只要记住用 equals() 判断内容,不用 ==,就不会出错。
以上就是在Java中如何比较字符串内容是否相等的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号