• 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

scjp chapter3 2nd example of page 207-208

 
Greenhorn
Posts: 14
  • 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 now " + 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("f.myBar.barNum after changeIt is "
+ f.myBar.barNum);
}
}


The preceding code prints out this:
f.myBar.barNum is 28
myBar.barNum in changeIt is 99
myBar.barNum in changeIt is now 420
f.myBar.barNum after changeIt is 99

here I am getting confuse that why in the last Sop it is printing 99 instead of 28.
plzzzzzzzzzz tell asap.
 
Ranch Hand
Posts: 294
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Pooja,

Welcome to the forum. First off, could you plzzzzzz use code tags when quoting source code examples so the 100,000,000 readers don't get sore eyes

You should review the topic covering shadowing and passing arguments to methods in whichever materials your using for your studies. The reference original reference to myBar in changeIt() is lost after the first SOP in the method.

Aloha,
Doug

-- Nothing is impossible if I'mPossible
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy, Pooja,

welcome to the Ranch!




In your example
in the bold line there is a re-reference of the locally used variable. Now "myBar" points to a different object, a new local object just created within the scope of the method.
All changes now apply on the new object, so the original Bar never gets a "barnum"-value of 420.

Yes. The tags work...



Yours,
Bu.
reply
    Bookmark Topic Watch Topic
  • New Topic