File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

shadowing an variable

 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From p-217 kathy sierra



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

i think it should give the output as
size=7;
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
 
Prasad Kharkar
Ranch Hand
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
now
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic