Java Equality

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anon538
    New Member
    • Sep 2007
    • 23

    Java Equality

    I am new to Java, and I am really confused by equality. Here is my current code:

    Code:
    String dm = JOptionPane.showInputDialog("Yes or no?");  
    if(dm=="yes") 
    {
       System.out.println("You chose yes.");
    }
    else
    {
       System.out.println("You chose no.");
    }
    Even if I type in yes at the prompt, it always prints "You chose no". Is there something I don't understand about equality comparisons in Java? Please give me a modified version of my code that will work.

    Thanks,
    Anon
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by anon538
    I am new to Java, and I am really confused by equality. Even if I type in yes at the prompt, it always prints "You chose no". Is there something I don't understand about equality comparisons in Java? Please give me a modified version of my code that will work.

    Thanks,
    Anon
    In Java all variables that are 'objects' (i.e. an instance of a class) are actually
    just pointers to the real objects. Primitives such as ints, doubles etc. are stored
    in the variable themselves.

    Suppose you and I both point to a String "yes". Most likely I'm pointing to another
    instance of a "yes" String than you are. Are we both pointing to the same
    thing? I'd say no; that's exactly what the == operator does. It checks whether
    or not both pointers are equal, i.e. if they point to the same thing.

    What you want is to check whether or not those two separate things *represent*
    the same thing. This ----> "yes" is another one than that ----> "yes", but they
    both represent the same String wih content/value "yes".

    Checking whether or not two different things represent the same value, you
    should use the equals() method.

    For primitives you can use the == operator again if you want to check them for
    equality, e.g. 42 == 42 is true.

    kind regards,

    Jos

    Comment

    • anon538
      New Member
      • Sep 2007
      • 23

      #3
      Thanks, it works perfectly.

      Comment

      Working...