-2

Possible Duplicate:
Why are these == but not `equals()`?

why this code will print

true

true

public class Test {
        public static void main(String[] args){
            String st1 = "abc";
            String st2 = "abc";

            Integer k1 = 100;
            Integer k2 = 100;

            System.out.println(st1 == st2);
            System.out.println(k1 == k2);
        }
    }

To compare objects we use method equals(). But why it is ok in this way?

Community
  • 1
  • 1
Mary Ryllo
  • 2,321
  • 7
  • 34
  • 53

3 Answers3

2

== compares object references. Because of you're Strings being hardcoded, they are interned and both use the same reference, therefor the 1st true. Also Integer caches commonly used numbers, so both of your Integers also reference the same object, which makes the second reference comparison true.

jlordo
  • 37,490
  • 6
  • 58
  • 83
1
        System.out.println(st1 == st2);

st1 is stored in the string constant pool (when first created); when the compiler sees st2="abc" it will just point st2 to the previously created object in the string constant pool. i.e., st1 and st2 point to the same object ("abc") in the String constant pool and == operator checks if two reference variables point to the same object.

        System.out.println(k1 == k2);

In this case, your wrapper instances are cached to small range thus == returns true.

Wug
  • 12,956
  • 4
  • 34
  • 54
PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

1) Both strings will be treated as string literals which will be interned and stored to same memory location.

== checks for reference equality, so both references point to same object and returns true.

2) Integer instances are cached for small range that is why k1 == k2 returns true for 100.

kosa
  • 65,990
  • 13
  • 130
  • 167