• 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
  • Himai Minh
  • Carey Brown
  • salvin francis

scjp chapter3 2nd example of page 207-208

Posts: 14
  • 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 now " + 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("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
  • 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.


-- Nothing is impossible if I'mPossible
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • 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...

It runs on an internal combustion engine. This ad does not:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic