-1

I have two strings, one is inputted by the user and one is the name of a thread. I inputted the name which should be the same as the thread. To verify this I have the program output

System.out.println("DS:" + DeamonMain.threadNameFinal + "CN:" +getName());

Which prints

DS:Thread-66CN:Thread-66

Now these appear to be the same string. However, when I have it test the validity of this using

boolean factChecker = DeamonMain.threadNameFinal == getName();
System.out.println(factChecker);

it prints false...

Why is this? Does this have to do with getName()? How are the string different and why so?

user760220
  • 1,187
  • 2
  • 11
  • 12

5 Answers5

2

You need to use String.equals to compare String equality, not the == sign.

As in:

boolean factChecker = DeamonMain.threadNameFinal.equals(getName());

The == operator checks for reference equality, while the equals method checks for the equality of your String values.

See also here for an older thread on the matter.

Community
  • 1
  • 1
Mena
  • 46,817
  • 11
  • 84
  • 103
1

Again, and again...

Strings in Java are compared with equals(), not with ==.

Change your comparison to:

boolean factChecker = DeamonMain.threadNameFinal.equals(getName());
Konstantin Yovkov
  • 60,548
  • 8
  • 97
  • 143
0

You should use the .equals() method to compare strings, rather than ==

boolean factChecker = DeamonMain.threadNameFinal.equals(getName());

The reason is that the .equals() tests for value equality (the strings have the same characters), while the == tests for reference equality.

jh314
  • 25,902
  • 15
  • 60
  • 80
0

You need to use equals() method instead of ==

Like this:

DeamonMain.threadNameFinal.equals(getName())
nkukhar
  • 1,935
  • 2
  • 16
  • 36
0

Use equals() for String comparision instead of == operator

  boolean factChecker = DeamonMain.threadNameFinal.equals(getName());
  System.out.println(factChecker);

equals() method is used for content comparison where as == is reference comparison.

Prabhaker A
  • 8,029
  • 1
  • 17
  • 24