String values are compared using '!=', not 'equals()'
时间: 2024-01-17 12:05:22 浏览: 24
You are correct! When comparing the values of two String objects in Java, it is recommended to use the `.equals()` method instead of the `!=` operator. This is because `!=` only compares the memory address of the two objects, whereas `.equals()` compares the actual values of the Strings. Using `!=` can lead to unexpected behavior, especially when dealing with user input or dynamically created Strings.
Here is an example of how to use `.equals()` to compare two String objects:
```
String str1 = "hello";
String str2 = "world";
if(str1.equals(str2)) {
System.out.println("The two strings are equal");
} else {
System.out.println("The two strings are not equal");
}
```
In this example, the output would be "The two strings are not equal" because the values of `str1` and `str2` are different.