• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

passing primitve variables

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.



 
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic