-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,207
  • 2
  • 13
  • 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
  • 47,782
  • 11
  • 87
  • 106
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
  • 62,134
  • 8
  • 100
  • 147
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
  • 27,144
  • 16
  • 62
  • 82
0

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

Like this:

DeamonMain.threadNameFinal.equals(getName())
nkukhar
  • 1,975
  • 2
  • 18
  • 37
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,317
  • 1
  • 18
  • 24