-2

Why does (("+k").split("k"))[0] not equal "+"? I am so confused.

Program:

//The Control Test
String a = "+";
System.out.println(a);
System.out.println((byte) a.charAt(0));
System.out.println(a == "+");

//The Error
a = (("+k").split("k"))[0];
System.out.println(a);
System.out.println((byte) a.charAt(0));
System.out.println(a == "+");

Output:

+
43
true
+
43
false  -- Why?

So why in the world does a "+" not equal a "+"?!

DT7
  • 1,615
  • 14
  • 26
Dude Dude
  • 33
  • 1
  • 4

2 Answers2

3

You shouldn't compare Strings with ==. You should compare them with .equals() instead.

if(a.equals("+"))
{
    // ...
}

This person explained it very well so there is no need for me to explain it again: look at this answer to a similar question.

Community
  • 1
  • 1
RaptorDotCpp
  • 1,425
  • 14
  • 26
0

String literals (strings placed directly in code) are stored in String pool and if some string literal is used few times same object from String pool is used. Since == compares references it will return true for

String a = "+";
System.out.println(a == "+");

Now Strings that are results of methods are separate objects that are not placed in String pool so in

String a = (("+k").split("k"))[0];

String object stored in a is different then "+" from String pool that is why == returns false.

To get rid of this problem you need to use equals method which will compare characters stored in String objects.

Pshemo
  • 122,468
  • 25
  • 185
  • 269