Reputation:
When I use JLabel string comparison with ==
works fine
private JLabel someJLabel = new JLabel("some text");
...
System.out.println (someJLabel.getText() == "some text"); // returns true
but when I use JTextField
private JTextField someJTextField = new JTextField("some text");
...
System.out.println (someJTextField.getText() == "some text"); // returns false
I know that if I used someJTextField.getText().equals("some text");
it would work fine.
So why it works with JLabel but not JTextField
EDIT: yes I know that I should use .equals
with string, I have read this article http://javatechniques.com/blog/string-equality-and-interning/ but it's known already that I will use "some text" so it could refer to same string object
Upvotes: 2
Views: 3348
Reputation: 11
There is a bit difference in == operator and.equals method. == operator compares two objects while .equals method compare values in two object.
In your case you are comparing two different object although both may be holding same values. In your case you may use .equals method .This will definitely help!
Upvotes: 0
Reputation: 95
Compare Strings with .equals(Object obj)
==
should mostly be used with only primitive objects.
Upvotes: 0
Reputation: 9317
JTextField internally copies the string to its modifiable document object to support editing so you don't get back the same string in getText().
Upvotes: 1
Reputation: 3519
It's not related to JTextField and JLabel.
JVM uses String pool internally and sometimes == operator works because different strings (in your case "some text") points to the same string in pool. Look at question here
Never compare strings with == !!!
Upvotes: 3