java对比字符串是否相等
时间: 2024-01-31 10:02:19 浏览: 19
在Java中,可以使用equals()方法来比较两个字符串是否相等。例如:
String str1 = "hello";
String str2 = "world";
String str3 = "hello";
if(str1.equals(str2)){
System.out.println("str1 is equal to str2");
} else {
System.out.println("str1 is not equal to str2");
}
if(str1.equals(str3)){
System.out.println("str1 is equal to str3");
} else {
System.out.println("str1 is not equal to str3");
}
执行结果为:
str1 is not equal to str2
str1 is equal to str3
相关问题
java比较字符串是否相等
在Java中比较字符串是否相等,可以使用equals()方法。例如,假设有两个字符串s1和s2,可以使用以下代码比较它们是否相等:
if(s1.equals(s2)){
System.out.println("s1和s2相等");
} else {
System.out.println("s1和s2不相等");
}
需要注意的是,字符串对象之间的比较不能使用"==",因为这会比较它们在内存中的地址,而不是它们的内容。
Java判断字符串是否相等
在Java中,判断两个字符串是否相等可以使用equals方法。该方法返回一个boolean类型的值,如果两个字符串相等则返回true,否则返回false。需要注意的是,不能使用==运算符来判断两个字符串是否相等,因为这个运算符只能够确定两个字符串是否存放在同一个位置上。而equals方法则是比较两个字符串的内容是否相等。下面是一个例子:
String str1 = "hello";
String str2 = "world";
if(str1.equals(str2)){
System.out.println("两个字符串相等");
}else{
System.out.println("两个字符串不相等");
}
输出结果为“两个字符串不相等”。