File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "passing primitve variables" Watch "passing primitve variables" New topic

passing primitve variables

hrithik sharma

Joined: Oct 25, 2008
Posts: 3
class Bar{

int barNum=28;

class Foo{

Bar myBar=new Bar();

void changeIt (Bar myBar) {

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);
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.


~Currently preparing for SCJP6
I agree. Here's the link:
subject: passing primitve variables
It's not a secret anymore!