• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Junilu Lacar
  • Liutauras Vilda
Sheriffs:
  • Paul Clapham
  • Jeanne Boyarsky
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
Bartenders:
  • Jesse Duncan
  • Frits Walraven
  • Mikalai Zaikin

Scope

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
I don't understand why declaring the second int x does not cause a compiler error. I know it's local but isn't the static x available inside the main method too??
<CODE>class ScopeTest
{
static int x = 5;
public static void main(String[] args)
{ int x = ( x=3 ) * 4;
System.out.println(x);
}
}</CODE>
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ash,
I think you are not getting a compile error because the local variable is shadowing the member variable. The Java Specification says
"A declaration d of a field, local variable, method parameter, constructor parameter or exception handler parameter named n shadows the declarations of any other
fields, local variables, method parameters, constructor parameters or exception handler parameters named n that are in scope at the point where d occurs
throughout the scope of d."
Try the following code:

The output is
12
5
because the local i shadows the member i, which can be referred to by class name because it is static.
Hope this helps.
 
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic