0

Here i wrote simple java code.

Integer Example

class Question {

        public static void main(String[] args) {
            Integer arr1 = 1;
            Integer arr2 = 1;

            System.out.println("arr1 == arr2 is " + (arr1 == arr2));//this check object reference - this returns true 
            System.out.println("arr1.equals(arr2) is " + arr1.equals(arr2));// this check value - this also return true
        }
    }

Integer [ ] Example

class Question {

      public static void main(String[] args) {
        Integer[] arr1 = {1, 2, 3, 4, 5};
        Integer[] arr2 = {1, 2, 3, 4, 5};

        System.out.println("arr1 == arr2 is " + (arr1 == arr2));// i know this check object reference - but this return false -how it happen ?
        System.out.println("arr1.equals(arr2) is " + arr1.equals(arr2));// i know this check value - but this also return false -how it happen ?
    }
}

For the Integer it returns both true and that is ok. But i can not understand For Integer[ ] how it return both false. thanks in advance.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Shalika
  • 1,457
  • 2
  • 19
  • 38
  • 2
    `equals` and `==` are identical for arrays, because array types do not override `Object.equals`. And 1 is inside the range of cached `Integer` values, so `arr1` and `arr2` are the same instance in the `Integer` case. – Andy Turner Feb 28 '17 at 08:56
  • 2
    You can refer to this thread : http://stackoverflow.com/questions/8777257/equals-vs-arrays-equals-in-java – Peter Guan Feb 28 '17 at 08:57
  • 2
    `arr1` and `arr2` integers actually return true on **reference equality** because of Java integer pool. It should have returned `false` in general case. The same about `arr1` and `arr2` - they return false, because they are two different objects having two different reference addresses. – Yeldar Kurmangaliyev Feb 28 '17 at 08:57
  • System.out.println("Arrays.equals(arr1, arr2) is "+ java.util.Arrays.equals(arr1, arr2)); this returns true.but why == retuns false.that is the doubt i have ? – Shalika Feb 28 '17 at 08:59
  • 1
    @Shalika that's just how `==`, `equals` and `Arrays.equals` work for arrays. – Andy Turner Feb 28 '17 at 09:07
  • can anyone describe me how the stack memory and heap memory works in both occasions ? – Shalika Feb 28 '17 at 10:45

0 Answers0