3

So I need to simply check whether a clicked button's text is "X" or "O" (making tic tac toe) This code doesn't work:

if (jButton1.getText()=="X")

However the following code does work:

String jButText = jButton1.getText();
if (jButText=="X")

Why doesn't the first bit of code work when the second does? Does it need to be something more like if (jButton1.getText().toString=="X")? By the way, I don't think toString exists in Java. That is just somewhat the equivalent in Visual Basic, which is what I normally use to create GUIs.

4
  • equals("X") and not == "X" Nov 19, 2013 at 21:09
  • 1
    This is NOT a duplicate of the same String comparison question that gets asked several times per day. The question here is why the second snippet works, but not the first. If it is in fact true that the second snippet works and not the first, then I don't know the answer. I would have expected them to generate the same byte code. Nov 19, 2013 at 21:18
  • toString() do exist in java, however getText() already returns a String so it wouldn't make much sense to run toString() on it.
    – spydon
    Nov 19, 2013 at 21:21
  • Which version of java are you using? This is not reproducible with java 1.7.0_45.
    – spydon
    Nov 19, 2013 at 23:01

4 Answers 4

3

This behavior is not reproducible in java 1.7.0_45 or 1.7.0_25, it might be a weird occurrence of String interning for your java version.

In order for your code to work properly on all java versions you have to use equals()

== compares objects meanwhile .equals() compares the content of the string objects.

jButton1.getText().equals("X")
8
  • Interning is what I thought first too but it doesn't explain why the first condition doesn't work. If "X" is an intern then getText returns "X" whether you assign it to a variable or not.
    – Radiodef
    Nov 19, 2013 at 21:59
  • It is because jButton1.setText() explicitly creates a new string object which is used in that comparison.
    – spydon
    Nov 19, 2013 at 22:01
  • I'm not convinced. OP doesn't say that he/she wrote new String(jButton1.getText()), so this doesn't seem to apply. It certainly doesn't explain why OP's two original snippets behave differently from each other. My honest suspicion is that OP has made a mistake understanding his/her results. Nov 19, 2013 at 22:02
  • If setText creates a new String object, then that still doesn't explain why the second snippet works. Nov 19, 2013 at 22:03
  • Hmm you're right and I checked the source code for AbstractButton, it doesn't create a new string object on setText() it simply does String oldValue = this.text; this.text = text; and getText() only returns text.
    – spydon
    Nov 19, 2013 at 22:14
1

This was also driving me nuts when using AWT Button class... Here's the answer: There is no .getText() method for a Button... you need to use .getLabel()

Now, the story for JButtons: Depending on your version of java, getLabel() was deprecated, and finally replaced by getText... Aren't namespaces wonderful?

1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyFrame extends JFrame{
    JButton equalsButton;
    JLabel ansLabel;
    JLabel addLabel;
    JTextField text1;
    JTextField text2;

    MyFrame (){
        setSize(300,300); 
        setDefaultCloseOperation(3);
        setLayout(new FlowLayout());
        text1=new JTextField(10);
        add(text1);
        addLabel=new JLabel("+");
        add(addLabel);
        text2=new JTextField(10);
        add(text2);     
        equalsButton=new JButton("=");
        equalsButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                int num1=Integer.parseInt(text1.getText());
                int num2=Integer.parseInt(text2.getText());
                int tot=num1+num2;
                ansLabel.setText(Integer.toString(tot));
            }
        });
        add(equalsButton);
        ansLabel=new JLabel("    "); 
        add(ansLabel);
        pack();
        setVisible(true);
    }
}

class Demo{
    public static void main(String args[]){
        MyFrame f1=new MyFrame();

    }
}
0

in java when you compare strings using == , you're comparing their memory addresses, to check if two strings contains same text you should call .equals()

if ("X".equals(jButton1.getText()))
3
  • 1
    You wont get a NullPointerException in the last case as getText() will return an empty string.
    – spydon
    Nov 19, 2013 at 21:13
  • This doesn't answer the question. See my comment under the question. Nov 19, 2013 at 21:20
  • you're rigth @spydon, my mistake. ;) Nov 19, 2013 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.