java 判断字符串相等
时间: 2023-12-15 22:06:11 浏览: 39
在 Java 中,判断字符串相等需要使用 equals 方法,例如:
```java
String s1 = "hello";
String s2 = "world";
if (s1.equals(s2)) {
System.out.println("s1 equals s2");
} else {
System.out.println("s1 not equals s2");
}
```
需要注意的是,如果使用 == 操作符判断字符串相等,实际上比较的是两个字符串对象的引用是否相同,而不是字符串的内容是否相同。
相关问题
java判断字符串相等
在 Java 中,判断两个字符串是否相等有两种方法:
1. 使用 equals() 方法
```java
String str1 = "hello";
String str2 = "world";
if (str1.equals(str2)) {
System.out.println("两个字符串相等");
} else {
System.out.println("两个字符串不相等");
}
```
2. 使用 equalsIgnoreCase() 方法(忽略大小写)
```java
String str1 = "HELLO";
String str2 = "hello";
if (str1.equalsIgnoreCase(str2)) {
System.out.println("两个字符串相等");
} else {
System.out.println("两个字符串不相等");
}
```
注意:使用 == 来判断字符串是否相等是错误的,因为它比较的是两个字符串对象的引用地址是否相同,而不是字符串的内容是否相同。
Java判断字符串是否相等
在Java中,判断两个字符串是否相等可以使用equals方法。该方法返回一个boolean类型的值,如果两个字符串相等则返回true,否则返回false。需要注意的是,不能使用==运算符来判断两个字符串是否相等,因为这个运算符只能够确定两个字符串是否存放在同一个位置上。而equals方法则是比较两个字符串的内容是否相等。下面是一个例子:
String str1 = "hello";
String str2 = "world";
if(str1.equals(str2)){
System.out.println("两个字符串相等");
}else{
System.out.println("两个字符串不相等");
}
输出结果为“两个字符串不相等”。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)