Java字符串比较:equals()方法和==运算符
在Java中,可以使用equals()方法来判断两个String字符串值是否一致。下面是一个示例代码:
String str1 = "Hello";
String str2 = "Hello";
if (str1.equals(str2)) {
System.out.println("两个字符串值一致");
} else {
System.out.println("两个字符串值不一致");
}
输出结果为:"两个字符串值一致"。
需要注意的是,equals()方法比较的是两个字符串的内容,而不是引用地址。如果要比较两个字符串的引用地址是否一致,可以使用"=="运算符。例如:
String str1 = "Hello";
String str2 = "Hello";
if (str1 == str2) {
System.out.println("两个字符串引用地址一致");
} else {
System.out.println("两个字符串引用地址不一致");
}
输出结果为:"两个字符串引用地址一致"。
原文地址: https://www.cveoy.top/t/topic/pWXG 著作权归作者所有。请勿转载和采集!