This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Boxing

 
Quirino Gervacio
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,



Why? >= and == are both comparison operators right?
 
Henry Wong
author
Marshal
Pie
Posts: 20907
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the title of your topic, you already know that boxing has taken place -- which means that you are comparing objects, not primatives. If you want them to be treated as primatives, you will need to unbox the values.

Henry
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


System.out.println(s >= i);
after compilation becomes
System.out.println(short1.shortValue() >= integer.intValue());

but in case of == unboxing is not done automatically... This is because the == operator is allowed on objects but not the >= operator. So on compilation the compiler knows that >= needs unboxing as >= is only allowed on primitive types but the == is allowed on objects.

The solution is
System.out.println((short)s == i);

Now the compiler knows that you are trying to compare primitives. so i is automatically unboxed.....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic