Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes shadow variable doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "shadow variable doubt" Watch "shadow variable doubt" New topic
Author

shadow variable doubt

saipraneeth nallapareddy
Ranch Hand

Joined: Dec 02, 2009
Posts: 159


most of the times with or without my knowledge i used this concept in my coding logic with the knowledge from C, but came to know the terminology for this particular concept is shadowing variable, ofcourse name doesn't matter what you get is important.

the output for the above piece of code is

but i felt the last line of the print statement must also give the value 420. ofcourse the output is not wrong the way i understand it is wrong can one please guide me the right way what actually going on there.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

Call By Reference vs Call By Value


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
saipraneeth nallapareddy
Ranch Hand

Joined: Dec 02, 2009
Posts: 159
thanks for the link, contains the info what i am looking for, cleared with issue.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

<edit>Rob beat me!</edit>
saipraneeth nallapareddy wrote:


f.myBar.barNum after changeIt is 99
ofcourse the output is not wrong the way i understand it is wrong can one please guide me the right way what actually going on there.


well, the key concept here is when you pass a reference to a method as argument, *it is always pass by copy of the reference*. we will work on your first 4 line of your changeIt method


so in first statement, myBar[say localBar] is a separate copy reference , but still it point to the same Object[say Ranch] which is already pointed by instance variable of myBar[say instanceBar]. clear? .
now if you change the object with localBar as myBar.barNum it affect the Ranch object. so now comment (2) and (3) and test , you come to know.

back to the explanation, when you say myBar = new Bar() in (2) . here you reassign the localBar object into a newly created Object(say New, which has a default value for barNum = 28)
*careful, in this point instanceBar points existing Object called Ranch and localBar points New*, so changing the barNum with localBar wont affect Ranch instead it affect New.
thus, you dont see this change in your output.

is it clear?

hth

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: shadow variable doubt
 
Similar Threads
scjp chapter3 2nd example of page 207-208
Shadowing of reference variables
shadowing an object
Shadowing of Variables
shadowing object reference variables