java中判断字符串相等
时间: 2023-11-22 10:05:07 浏览: 36
在Java中,可以使用equals()方法来判断两个字符串是否相等,示例如下:
```java
String str1 = "hello";
String str2 = "world";
if(str1.equals(str2)) {
System.out.println("str1和str2相等");
} else {
System.out.println("str1和str2不相等");
}
```
需要注意的是,字符串属于对象类型,在Java中使用“==”进行比较时,比较的是两个对象的引用是否相等。因此,如果要比较两个字符串是否相等,必须使用equals()方法。
相关问题
java 怎么判断字符串相等
在Java中,要判断字符串相等,可以使用equals()方法。这个方法会比较两个字符串的内容是否相同,而不是比较两个字符串对象的引用是否相同。例如:
String str1 = "hello";
String str2 = "Hello".toLowerCase(); //将字符串转换成小写
boolean isEqual = str1.equals(str2); //isEqual的值为true,因为str1和str2的内容相同
还可以使用equalsIgnoreCase()方法来忽略大小写进行比较。
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("两个字符串不相等");
}
```
注意:使用 == 来判断字符串是否相等是错误的,因为它比较的是两个字符串对象的引用地址是否相同,而不是字符串的内容是否相同。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)