3 Replies Latest reply: Feb 20, 2013 2:56 AM by PhHein RSS

    Please Help with Integer type

    Stanislav
      Hello, all!
      Please help!
      Please take a look to this code. Why 3rd string is not in the output but №5 does?
      public static void main (String [] args) {
              Integer x = new Integer(10);
              Integer y = new Integer(10);
              if (x==10)
                  System.out.println("1. x=10");
              if (y==10)
                  System.out.println("2. y=10");
              if (x==y)
                  System.out.println("3. x=y");
              if (x.equals(y))
                  System.out.println("4. x.equals(y)");
              x=10;
              y=10;
              if (x==y)
                  System.out.println("5. x=y");
          }
      Results
      1. x=10
      2. y=10
      4. x.equals(y)
      5. x=y
        • 1. Re: Please Help with Integer type
          DrClap
          Because in the first case x and y refer to two different objects, and in the second case they refer to the same object.

          And I don't see what this has to do with Generics.
          • 2. Re: Please Help with Integer type
            Stanislav
            Sorry!
            how i can replace this thread to category: Java Essentials

            and take a look at this code and results
            public static void main (String [] args) {        
                    Integer x1;
                    Integer y1;
                    Integer a;
            
                    a = new Integer(127);
                    x1 = a.intValue();
                    y1 = a.intValue();        
                    System.out.println("x1==y1 " + (x1==y1));
                    System.out.println("x1.equals(y1) " + (x1.equals(y1)));
                    a = new Integer(128);
                    x1 = a.intValue();
                    y1 = a.intValue();
                    System.out.println("x1==y1 " + (x1==y1));
                    System.out.println("x1.equals(y1) " + (x1.equals(y1)));
                }
            results
            x1==y1 true
            x1.equals(y1) true
            x1==y1 false
            x1.equals(y1) true
            • 3. Re: Please Help with Integer type
              PhHein
              Have a look at the source code of Integer.IntegerCache, then you'll understand.

              Moderator action: moved from Generics.