Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Refrence Types Assignment

 
Tarek Moustafa
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rameshwar Soni
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Steve.
And sorry for repetition.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic