-2

How can it be possible, that If statement doesn't understand two equal things that they are the same?

Situation: I write into txfName field only letter b and then push button "Ok".

Code:

String letter = "b";
boolean same = false;
if (letter == txfName.getText()) {
same == true;
}

After if statement program shows me that variable same is false. Why? How can it be possible?

If I write code like this:

String letter = "b";
boolean same = false;
if (letter == "b") {
same == true;
}

Then after if statement program shows me that variable same is true. I don't understand, how it can be possible.

Toms Bugna
  • 502
  • 2
  • 10
  • 30
  • Compare `String` values with `String`'s `equals` method, not with the `==` operator. Also, use `=` to assign `true` to your `boolean`. – rgettman Nov 15 '13 at 00:48
  • Note: `same == true;` is not an assignment statement, but I suspect that's just a typo when you asked your question. – ajb Nov 15 '13 at 00:51
  • Do people even search before posting? "string equality" gives many questions that answer this. – clcto Nov 15 '13 at 00:52
  • it's done now. I'm confused. But thanks for it! ;) – Toms Bugna Nov 15 '13 at 00:52
  • @clcto The problem is that while we who already know the answer also know exactly what search terms will work, those with less experience might not. And searching for "if statement equality" (based on the title) isn't likely to lead to the right answer. It's sort of like telling someone to look in the dictionary to find out how to spell a word--if you don't know how to spell it, how can you find it in the dictionary? – ajb Nov 15 '13 at 17:24

3 Answers3

1

== compares to see if two objects are the same. When you are dealing with strings they are objects, so they may not have the same reference event though they can have the same value. You want to use .equals() instead.

For more details, Strings are special in java, as there are some internal workings that have a String pool. So in some cases the == may actually seem to be working, but in other cases it may not be. The reason is the String pool tries to cache recently used Strings to reduce the memory overhead. Anyway .equals() is what you are looking for.

James Oravec
  • 19,579
  • 27
  • 94
  • 160
1

for your first question

String letter = "b";
boolean same = false;
if (letter.equals( txfName.getText())) {
 same = true;
}
return same;

will return true if txfName.getText() returns "b"

Ismail Sahin
  • 2,640
  • 5
  • 31
  • 58
0

To compare objects in java use .equals() method instead of "==" operator

Replace the following code

if (letter == txfName.getText()) 

to

if (letter.equals(txfName.getText()))
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64