Explore BrainMass

Explore BrainMass

    Why aren't relational operator (==) and the .equals method interchangeable?

    Not what you're looking for? Search our solutions OR ask your own Custom question.

    This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!

    Why aren't the relational operator (==) and the .equals method interchangeable? Why isn't the following code correct?

    String myName = "Ken";
    if (myName == "Ken")
    //do something

    © BrainMass Inc. brainmass.com March 4, 2021, 8:44 pm ad1c9bdddf
    https://brainmass.com/computer-science/java/why-aren-t-relational-operator-and-the-equals-method-interchangeable-190481

    Solution Preview

    The "==" operator and the .equals method are not interchangeable.
    "==" operator is to compare the references of two variables, .equals method is to compare the value of the two objects.

    In your example, ...

    Solution Summary

    This response provides a tutorial correcting the relational operation and the .equals method.

    $2.49

    ADVERTISEMENT