Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

passing primitve variables

 
hrithik sharma
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Bar{

int barNum=28;
}

class Foo{

Bar myBar=new Bar();

void changeIt (Bar myBar) {

myBar.barNum=99;
System.out.println("mybar.barnum in changeit is "+myBar.barNum);

myBar = new Bar();
myBar.barNum =420;

System.out.println("mybar.barnum in changeit is "+myBar.barNum);
}

public static void main (String [] args){

Foo f = new Foo();
System.out.println("f.myBar.barNum is "+f.myBar.barNum);
f.changeIt(f.myBar);
System.out.println("mybar.barnum after changeit is "+f.myBar.barNum);
}
}

this program is giving an output like
f.myBar.barNum is 28
mybar.barnum in changeit is 99
mybar.barnum in changeit is 420
mybar.barnum after changeit is 99


i am not getting why the out put of the last SOP is 99

why it is not 28.



 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output of the last one is 99 because "void changeIt (Bar myBar)" declares a local Bar variable named myBar. This local variable is passed the reference to your Foo.Bar object. What this means is that "myBar.barNum=99;" says take the Bar object that myBar is referencing (which is Foo.Bar object) and set the barNum to 99. Then "myBar = new Bar();" says take our local Bar object and have it reference a brand new Bar object instead of the Foo.Bar object. Next you change the barNum value of your new Bar object which has no effect on Foo.Bar at all.

I think the main confusion comes from the fact that the local variable myBar is givin a reference to another variable with the same name. This is allowed but can get confusing when changing references AND values.

Also, if you didn't write this code please state your sources.

HTH
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic