How do I compare strings in Java?

Asked 1 years ago, Updated 1 years ago, 131 views

How do I compare strings in Java? I've used the == operator to compare strings until now. But as I continued to use it, there were often situations where bugs occurred, and some of them.Fixed bug after changing to equals(). == Is the operator the problem? When should I use the == operator and when should I not? What is the difference between == and .equals?

equality string java

2022-09-21 18:40

1 Answers

== checks if the reference is the same (whether it is the same object) .equals() checks to see if the values are the same (logical or not). Objcect.equals() checks whether it is null or not before calling .equals(). so you don't have to (available as of JDK7, also available in Guava).????

As a result, comparing whether two string variables have the same value is equivalent to using Objects.equals().

// The following two values are the same
new String("test").equals("test") // --> true 

// But it's not the same object
new String("test") == "test" // --> false 

// The same goes for the situation below.
new String("test") == new String("test") // --> false 

// In the case below, the two literals are constantized by the compiler
// You will refer to the same object.
"test" == "test" // --> true 

// The Objects.equals() method is a good idea.
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false

You will probably always use the Objects.equals() method. Use the == operator in very rare situations (with constant strings).


2022-09-21 18:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.