Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dout on boxing

 
karnatam narendraprasad
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Boxing {
public static void main(String args[]) {
Integer i1 = new Integer(10);
Integer i2 = 10;
System.out.println("Lessthan: " + (i1 <= i2));
System.out.println("Greaterthan: " + (i1 >= i2));
System.out.println("Equality: " + (i1 == i2));
}
}

it compiles fine.and give output as

Lessthan: true
Greaterthan: true
Equality: false


why they are not equal...
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by karnatam narendraprasad:
public class Boxing {
public static void main(String args[]) {
Integer i1 = new Integer(10);
Integer i2 = 10;
System.out.println("Lessthan: " + (i1 <= i2));
System.out.println("Greaterthan: " + (i1 >= i2));
System.out.println("Equality: " + (i1 == i2));
}
}

it compiles fine.and give output as

Lessthan: true
Greaterthan: true
Equality: false


why they are not equal...


When == is applied to two object references, then what is being tested is whether those two references point to the same object.

The first reference refers to a new Integer. The second refers to an Integer object created from boxing.

Unless one of the operands is a primitive in ==, then unboxing will not occur.
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For testing if two objects are meanfully the same you should use the equals command. You're using the == command which checks if the two references are referring to the same object which is not true.

Maybe the code below can help you
 
Ram Reddy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

why these two are giving out put as true ?

System.out.println("Lessthan: " + (i1 <= i2));
System.out.println("Greaterthan: " + (i1 >= i2));
 
Pinkal Patel
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

why these two are giving out put as true ?

System.out.println("Lessthan: " + (i1 <= i2));
System.out.println("Greaterthan: " + (i1 >= i2));

Here Auto Boxing come in picture and Integer wrapper class convert to normal int type and than compare two int variable so It will return True in this case.
 
Ram Reddy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks patel.

then for "==" unboxing wont happen ?
 
Chris Stann
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
then for "==" unboxing wont happen ?


That is correct. Not for a reference comparison.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic