-4

I have java syntax. Sory I'm still not figure out why this happen.

public class TestString {
  public static void main(String [] args){
    int i=-1;
    String a=((Object)i).toString();
    if(a=="-1"){
        System.out.println("Same");
    }else{
        System.out.println("Not");
    }
  }
}

And then the result is "Not" what the problems why -1 string different with -1 int in object?

mrhands
  • 1,473
  • 4
  • 22
  • 41

5 Answers5

5

You have to use .equals() on string to compare.

String's equal method overridden in such a way.

Try

public class TestString {
  public static void main(String [] args){
    int i=-1;
    String a=((Object)i).toString();
    if(a.equals("-1")){
        System.out.println("Same");
    }else{
        System.out.println("Not");
    }
  }
}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Strings have to be compared with the .equals() method.

tom
  • 2,735
  • 21
  • 35
0

You are using reference equality instead of object equality.

Since "-1" in the literal table has a different heap address than a newly allocated a, it returns false.

If for some reason you find yourself allocating a lot of String objects that share the same value(s) and want to test them by reference instead, consider using String#intern():

final String a = [...].intern(); // allocated
if (a == SOME_INTERNED_STRING_1) {
  [...]
else if (a == SOME_INTERNED_STRING_2) {
  [...]
}
Tadas S
  • 1,955
  • 19
  • 33
0

==

compares reference which is not same in your case so if you want to compare string values then use

.equals() method

ankit
  • 4,919
  • 7
  • 38
  • 63
0

The == operator checks to see if two objects are exactly the same object . You can go for equals method to check if the value are equal or not

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
  • The objects are not even accessed when using `==` (reference equals) operator. The only thing being tested is their heap addresses. – Tadas S Sep 06 '13 at 08:45