1

Possible Duplicate:
Java String.equals versus ==

i am new to java so don't expect things to be easy but this has me totally shell shocked. why on earth doesn't the if statement evaluate properly:

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class StringMystery extends JFrame {

    JTextArea txt = new JTextArea();
    String string1 = "abcde";
    String string2 = string1.substring(0,4);

    public StringMystery() {

        setLayout(null);

        txt.setBounds(20, 20, 100, 100);
        add(txt);

        txt.setText(string2);

        //string 2 is definitely equal to "abcd" but this doesn't evaluate:
        if (string2 == "abcd"){     
            txt.setText("string2 = abcd");          
        }

    }


    public static void main(String[] args) {

        StringMystery jtxt = new StringMystery();
        jtxt.setSize(200,200);
        jtxt.setTitle("String Mystery");

        jtxt.setVisible(true);

    }
}
Community
  • 1
  • 1
Gimli
  • 29
  • 4

2 Answers2

8

Do not (ever) use == for comparison unless you want to compare the actual references. You need to use the .equals() method. And for String you may consider writing "abcd".equals(myStr) - because myStr can potentially be null.

Note that in Java strings are interned and == might sometimes give correct results, but by no means you should rely on that.

Anonymous
  • 18,162
  • 2
  • 41
  • 64
  • amazingly quick response. thanks. are all oop s languages like this? why can't they just make it work with == – Gimli Apr 20 '12 at 12:36
  • 1
    @Gimli: No. C# and C++ support operator overloading, and Javascript treats strings specially. – SLaks Apr 20 '12 at 12:40
6

== compares objects by reference, not by value.

You have two different string objects that contain the same value, so == returns false.

You need to call .equals().

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964