java - is == operator meant for primitives comparing -


it's written on == checks if 2 objects share same memory reference or not. why getting output false in below code?

public class {     public static void main(string args[]) {         double d1 = new double(12.0);         double d2 = d1;         d1 = d1 + 1.0;         system.out.println(d1 == d2);     } } 

is due autoboxing double gets converted double in line d1 = d1 + 1.0 , == checks primitive values? confused. expected output true. can clear away doubts?

i think source of confusion arises line:

d1 = d1 + 1.0; 

lets start beginning. lets call references objects dx , objects ox.

to start write:

double d1 = new double(12.0); 

so have reference d1 point object o1 double 12.0.

next write:

double d2 = d1; 

so have reference d1 , reference d2 both point object o1 double 12.0.

next write:

d1 = d1 + 1.0; 

so have new object o2 , repoint reference d1 point @ o2. never forget immutable means, in java primitive wrapper types always immutable. change value new wrapper must created.

so in end have

  • d1 pointing object o2 double 13.0.
  • d2 pointing object o1 double 12.0.

so can see d1 , d2 point different objects.

the situation same if using primitive double except incorrect talk object , references, copying memory.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

php - Find a regex to take part of Email -

javascript - Function overwritting -