How do I compare strings?

Asked 2 years ago, Updated 2 years ago, 169 views

I always used == when comparing strings, but when I changed it to .equals() because of a bug while coding last time, It's fixed. Why did == get a bug? What's the difference from equals()

string java equality

2022-09-22 22:36

1 Answers

In Java, == is a comparison of objects. It's a comparison of whether they have the same reference .equals() is a comparison of values. The reason why there was a bug is probably because the string value of the object was the same, but the two objects were different objects, so when compared with ==, I think there was a bug because the false was returned I'll give you an example, so I think it'd be good to study the difference between the two.

 // They both have the same value 
    new String("test").equals("test") // --> true 

    //  Create a new object with new String and "test" is a different object, so false
    new String("test") == "test" // --> false 

    // Create both objects with the value "test" and false
    new String("test") == new String("test") // --> false 

    // The compiler sees "test" as the same object 
    "test" == "test" // --> true 

    // // checks for nulls and calls .equals()
    Objects.equals("test", new String("test")) // --> true
    Objects.equals(null, "test") // --> false


2022-09-22 22:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.