java - confused about String vs Integer -
this question has answer here:
- weird integer boxing in java 9 answers
i have question comparing string , integer objects...
a. comparing string references:
string string1 = "hi"; system.out.printf("%s \n", string1); string originalstring = string1; system.out.printf("%-9s %-9s %b \n", string1, originalstring, originalstring == string1); system.out.println(); string1 += " there"; originalstring += " there"; system.out.printf("%-9s %-9s %b \n", string1, originalstring, originalstring.equals(string1)); system.out.printf("%-9s %-9s %b \n", string1, originalstring, originalstring == string1);
produced output:
hi hi hi true hi there hi there true hi there hi there false
here, last line compares addresses , expected gives false. ok far ;)
b. comparing integer references:
integer integer1 = 10; system.out.printf("%d \n", integer1); integer originalinteger = integer1; system.out.printf("%d %d %b \n", integer1, originalinteger, originalinteger == integer1); system.out.println(); integer1++; originalinteger++; system.out.printf("%d %d %b \n", integer1, originalinteger, originalinteger == integer1);
produced output:
10 10 10 true 11 11 true
by time last line printed out, both 'integer1' , 'originalinteger' referencing different objects... nevertheless
originalinteger == integer1 --> true ???
does imply not addresses of objects the contents of objects compared? in other words, because, type wrappers, values 'unboxed' before being compared?
so, resume:
originalstring == string1 --> false originalinteger == integer1 --> true
i don't understand why originalinteger == integer1 --> true
thank you
the ==
compares reference of object (the "address", put it), understood (correctly) string
example.
when apply ++
operator integer
, in fact outboxing primitive int
, incrementing it, , autoboxing integer
, theoretically, different object there. however, integer
class plays "dirty" trick here (read: neat optimization). values 127 (inclusive), java keeps cache of integer
s , returns same object whenever value autoboxed. so, in fact, getting same object, originalinteger == integer1
return true
. if repeat example larger integer, let's 500
, you'd false
expect.
Comments
Post a Comment