File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes shadowing an variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "shadowing an variable" Watch "shadowing an variable" New topic

shadowing an variable

Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

From p-217 kathy sierra

this is the case of shadowing a variable........
output is
size in changeIt is 207
size after changeIt is 7

i think it should give the output as
size in changeIt is 207
size after changeIt is 207( but the actual is 7)

how it comes not able to understand as size is a static variable

SCJP6.0,My blog Ranchers from Delhi
Prasad Kharkar
Ranch Hand

Joined: Mar 07, 2010
Posts: 446

consider following statements

1. when we initialize a primitive or assign the value to a primitive variable the bits of the primitive are copied into the variable
2. The bits of primitive denotes the primitive value
3. so when we assign a primitive variable to another primitive variable, then the bits of first variable are copied into another variable

here in our case
when we define int size = 7
the bits of the value 7 are copied into variable size
when we are passing the size variable to the method
Always remember that when passing values to the method , always the copy of the variable is passed and not the actual variable
so when we call the changeIt method using

then the size variable is passed to the method
now the method declaration shows

then the size variable here is actually the alias variable (we can write any variable name here (confusion is because the same name is given))
here the bits are copied to size variable and that alias also contains the value 7
now in the method we add 200 to the size variable that is the method argument (not the static size variable)
and we print the variable in so it gives 207

now when the method completes
then the size variable (the method argument) is not available out of the method

and after the method we are printing the size variable again
this time the size variable is the static variable (and it was unchanged because the copy of it was passed to the method argument in changeIt(size))

hope this is clear to you now

you will find it more interesting when you study the shadowing of reference variables
happy preparation

SCJP 6 [86%], OCPWCD [84%], OCEJPAD [83%]
If you find any post useful, click the "plus one" sign on the right
I agree. Here's the link:
subject: shadowing an variable
It's not a secret anymore!