0

I have this statement and I'm trying to remove the first character and replace it with a blank string but for some reason this returns false. It seems like it's just setting it equal then asking if it's equal to me.

public class Test1
{
    public static void main(String[] args)
    {
        String aString = "123";
        String sub = Character.toString(aString.charAt(0));
        System.out.println(sub == Character.toString(aString.charAt(0)));
    }
}
ToxicGLaDOS
  • 441
  • 5
  • 16

3 Answers3

2

Try .equals instead of ==, because == is for reference check and .equals is for checking value. After seeing your code, I think you need value check. So, use .equals as follows,

sub.equals(Character.toString(aString.charAt(0))); //this will return true.
Abhishek
  • 6,912
  • 14
  • 59
  • 85
0

Try .equals() method instead of == operator.

ELITE
  • 5,815
  • 3
  • 19
  • 29
0

With respect to the String class:

The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn't make a difference. Its the "value" (that is: the contents of the character array) inside each String instance that is being compared.

On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".

-- Credits to Jacques Colmenero See What is the difference between == vs equals() in Java?

Community
  • 1
  • 1
NuWin
  • 276
  • 5
  • 15