wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes passing primitve variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "passing primitve variables" Watch "passing primitve variables" New topic
Author

passing primitve variables

hrithik sharma
Greenhorn

Joined: Oct 25, 2008
Posts: 3
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

Joined: Nov 07, 2008
Posts: 488
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


SCJA
~Currently preparing for SCJP6
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: passing primitve variables
 
Similar Threads
scjp chapter3 2nd example of page 207-208
Shadowing of reference variables
shadowing an object
scjp chapter3 2nd example of page 207-208
shadowing object reference variables