How do I compare strings in Java?

  1. melbel profile image94
    melbelposted 12 months ago

    How do I compare strings in Java?

    I've always used == to compare strings until now. I ran into an error, so I decided to change one of the equals signs to .equals() and this solved my problem. Why didn't == work? Are there cases where == should not be used and .equals() should be used instead (obviously aside from fixing the bug.) I'm not sure I really see a difference between the two operators. What's the difference?

  2. techa2zsolution profile image61
    techa2zsolutionposted 12 months ago

    ==    is a reference, values comparison, i.e. both objects point to the same memory location.

    .equals() -> evaluates to the comparison of values in the objects.

  3. Shubhankar Sharma profile image47
    Shubhankar Sharmaposted 10 months ago

    You have two options
    1- use equals method
    2- equals to
    Both are used for string matching