This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Refrence Types Assignment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Refrence Types Assignment" Watch "Refrence Types Assignment" New topic
Author

Refrence Types Assignment

Tarek Moustafa
Greenhorn

Joined: Oct 15, 2012
Posts: 2
I have a question regarding wrapper classes assignment.

When I try the following, it prints false :-
Integer i = 4005;
Integer i2 = 4005;
System.out.println((i == i2) );

while thisone prints true:-
Integer i = 45;
Integer i2 = 45;
System.out.println((i == i2) );
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4164
    
  21

First: when comparing Objects of any type, you should use .equals() rather than ==. If you use .equals() you will get consistent results.

Second: The reason == works with some Integer values (those close to 0) and not others (those farther from 0) is because of 'Integer Caching'. See this discussion on the topic.


Steve
Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
The same question has been asked many times, so i would request you to search first and if you have any further doubt after searching you can surely ask.
And Welcome to Ranch.
Tarek Moustafa
Greenhorn

Joined: Oct 15, 2012
Posts: 2
Thanks, Steve.
And sorry for repetition.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Refrence Types Assignment
 
Similar Threads
Can someone help me with this
"==" on Wrapper Class
Doubt on != and == when boxing and unboxing is used
HashSet question
Small doubt in Boxing & == & equals()