Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,
Please why is the code below returning true ?
Integer num1 = new Integer(5);
   int num2 = 5;
   if(num1 == num2) {
   System.out.println(true);
   }
   else{
   System.out.println(false);
   }

I was thinking that an object created with the new keyword would be on the heap and a primitive data type would be on the stack ? I know that the "==" test for the references and not the value of the data. Thanks for any help in advance.

What I have tried:

Integer num1 = new Integer(5);
   int num2 = 5;
   if(num1 == num2) {
   System.out.println(true);
   }
   else{
   System.out.println(false);
Posted
Updated 21-Feb-23 18:50pm
Comments
Richard MacCutchan 22-Feb-23 3:59am    
It would be a pretty stupid language if it told you that 5 does not equal 5.

1 solution

No, integers are primitives, so they are value types, not reference which means that the variable is the value rather than a reference to the value and is not stored on the heap as a separate object.
Primitive and reference variables[^]
 
Share this answer
 
Comments
UT7 22-Feb-23 1:48am    
@OriginaGriff, thanks for your response but I taught that Integer (wrapper class) wraps a primitive data type into objects and objects are located on the heap ? Please clarify. Thanks.
OriginalGriff 22-Feb-23 2:15am    
Because when you compare an int with an Integer, the system unboxes the int field that the Integer contains and compares the two primitive values.
Since a primitive doesn't (and can't) have a reference that's the only type of comparison it can do!
UT7 22-Feb-23 2:28am    
@OriginalGriff, okay, thanks a lot. I'm grateful

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900