0

Why is this ok? What exactly does it compare?

    int i = 10; 
    char c = 10;
    if( c == i)
       System.out.println("We are Equal");

And the same in this situation:

    String s1 = "Null"; 
    String s2 = new String(s1);
    if( s1 == s2)
       System.out.println("We are Equal");

I get that we're not comparing the contents of the variable.

Lorena Sfăt
  • 215
  • 2
  • 7
  • 18
  • 1
    No, the first is OK but use `s.equals()` for Strings. – markspace Nov 27 '14 at 16:31
  • The first part is covered by [JLS-4.2.1 Integral Types and Values](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.1) – Elliott Frisch Nov 27 '14 at 16:33
  • For Strings you need to use `.equals` because Strings in Java are objects. Use `==` only on primitive data types. – user3437460 Nov 27 '14 at 16:34
  • 1
    In the first case it is comparing casted value char c i.e into (int)c==i so it is true but in second i.e String it compares whether both reference of string i.e s1 and s2 are pointing to same location in String pool. and which is false – Prakhar Asthana Nov 27 '14 at 16:35
  • @PrakharAsthana your second case is wrong. `s1` and `s2` are two totally different references, and by using `==` you're comparing the references, which will return `false`. They don't point to the same *location* in String pool. – Luiggi Mendoza Nov 27 '14 at 16:37
  • s1 and s2 POINTS to a value, while i and c is the value itself. While s1 and s2 point to the same thing, they are two different entities of the VM world. – Attila Neparáczki Nov 27 '14 at 16:38
  • @Luiggi Mendoza That is what am saying. Read it In the first case it is comparing casted value char c i.e into (int)c==i so it is true but in second i.e String it compares whether both reference of string i.e s1 and s2 are pointing to same location in String pool or not (which is not) and hence is false – Prakhar Asthana Nov 27 '14 at 16:40
  • Yeah I got it now, thank you :) – Lorena Sfăt Nov 27 '14 at 16:41
  • @PrakharAsthana *s1 and s2 are pointing to same location in String pool. and which is false* I mean this part is wrong. If indeed `s1` and `s2` *point to the same location in the String pool* then the `==` comparison would be `true`, not `false`. – Luiggi Mendoza Nov 27 '14 at 16:41

2 Answers2

1

In the first example, the two literal values of the integers are being compared, I.e. 10 == 10.

In the second example, your are comparing String objects, meaning the value of the actual Objects, not its content, are getting compared. In order to compare the content of these string objects, I.e. "Blah" == "Blah", you should use the string method String.compare(String strToCompare

David.Jones
  • 1,413
  • 8
  • 16
0

Strings are objects. You are comparing references for the strings. Char/ints are primitives so no objects.

robert
  • 1,921
  • 2
  • 17
  • 27