-4

Can people explain why this code gives its results

public class InputTest {
    public static void main(String[] args) {
        Integer w = new Integer(1);
        Integer x = 1;
        Integer y = x;
        double z = x;
        System.out.println(w.equals(y));
        System.out.println(w == y);
        System.out.println(x == y);
        System.out.println(z == w);
    }}
Josh
  • 49
  • 8
  • possible duplicate of [Java == vs equals() confusion](http://stackoverflow.com/questions/7520432/java-vs-equals-confusion) – Turing85 Apr 18 '15 at 14:33
  • 2
    possible duplicate of [Java: Integer equals vs. ==](http://stackoverflow.com/questions/3637936/java-integer-equals-vs) – Brett Okken Apr 18 '15 at 14:34
  • 1
    could you be more specific about you question as everybody knowns what is the output. So what is the explanation you want? – Blip Apr 18 '15 at 14:41
  • u guys are really helpful arnt u – Josh Apr 18 '15 at 14:45
  • 1
    Kindly reword your question and explain what is your problem in simple words. If you do not want any more down votes. – Blip Apr 18 '15 at 14:48

1 Answers1

1
w.equals(y)

returns true since Integer.equals compares the values wrapped by the Integer objects.


w == y

yields false since you compare the references, not the values wrapped by the Integer objects. Since you explicitly create a new Integer object w (Integer w = new Integer(1)) w and y are not the same objects.


x == y

yields true since you assign x to y(y = x). x and y refer to the same Integer object.


z == w

yields true since one of the types involved in the comparison is a primitive; w is unboxed and converted to double (yields 1d). The same is done in this assignment: double z = x;. Comparing those primitives yields true.

fabian
  • 80,457
  • 12
  • 86
  • 114