Java判断命令中给出的两个字符串是否相等源代码
时间: 2023-06-27 13:05:32 浏览: 60
下面是Java中判断两个字符串是否相等的源代码:
```java
public class StringEquality {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "world";
// 使用equals()方法判断两个字符串是否相等
if (str1.equals(str2)) {
System.out.println("str1 and str2 are equal");
} else {
System.out.println("str1 and str2 are not equal");
}
// 使用compareTo()方法判断两个字符串是否相等
if (str1.compareTo(str2) == 0) {
System.out.println("str1 and str2 are equal");
} else {
System.out.println("str1 and str2 are not equal");
}
// 使用==运算符判断两个字符串是否相等
if (str1 == str2) {
System.out.println("str1 and str2 are equal");
} else {
System.out.println("str1 and str2 are not equal");
}
}
}
```
其中,使用equals()方法和compareTo()方法可以判断两个字符串是否相等,使用==运算符也可以判断,但需要注意它们的区别。equals()方法和compareTo()方法比较的是字符串的内容,而==运算符比较的是字符串的引用地址。