• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Static variable confusion.

 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys.. Need some help with a confusion..

1) static int x;
void some_method() { System.out.print(x); } //prints 0. MUST not static variables be initialized?? How come it prints 0?

2)static int x=10;
staic { int x=99; }
void some_method() {System.out.print(x); } // prints 10 !! why not 99?

3) static { int x=10; }
void some_method() { System.out.print(x); } // compiler error saying "x" not found.
What happens when I put the declaration in paranthesis to give this error?

Thanks a lot guys.. Really need your help..
 
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It seems like in general you have two uses of the word "static" confused. In one sense, when used like this before a variable declaration:

static int x;

it is a modifier that changes the scope of the variable - instead of there being one copy of the variable for every instance (object) of your class, you get one copy that belongs to the class, shared by all instances of the class.

In another sense, when it's placed before a block (defined by the curly braces) like this:

static {
int x = 99;
}

it is defining some code that will run when the class is first loaded, to initialize the class, before instances of the class are created. These are called static initializer blocks, and are typically used to initialize static (class) variables to something that can't be determined until runtime (do a database lookup, or read a property file...).

In terms of scope of variables declared within them, static initializer blocks are like other blocks (think of variables defined within a loop, for example - they are gone when the code finishes the iteration of the loop block). You can think of static initializers kind of like "constructors" for the class, as opposed to the object instance constructors you normally define like this:

public MyCoolClass () {
initializeThisNewInstance();
}


Hopefully, that has made sense, then let's look back at your questions:

1. static int x;
void some_method() { System.out.print(x); } //prints 0. MUST not static variables be initialized??



Variables defined outside of a block (class or instance variables) get a default value:
- 0 for numeric values
- null for object types (references)
- false for booleans

This is true whether the variable is static or not. The thing that might make that confusing is that it works differently for "local" variables (that is, variables declared within a method). If local variables are not assigned before they are referenced, the compiler will generate the error you were expecting. (For local reference variables, even assigning them with null will bypass the error.) But for class (static) or instance variables, that is not the case - they are automatically initialized to a default value.

Another interesting twist is that array elements (once an array is instantiated) are given a default value, even if the array is defined within a method. Note that I'm not talking about the array reference variable, though: if that is a local variable, it must be assigned (even with null) before it is referenced... and an actual array must be instantiated before there are any elements in the array to be automatically initialized.

2. static int x=10;
staic { int x=99; } // SIC: I assume you meant "static"
void some_method() {System.out.print(x); } // prints 10 !! why not 99?



Because your static initializer block is not setting the same "int x" as is defined above it.

You have one "int x" defined on your first line, and assigned a value of 10. Then you define another "int x" in the static initializer block, which "hides" the class-level variable with this version, which only has scope within this block. It is assigned the value 99, and then promptly goes out of scope and ceases to matter at all...

When some_method() is called, the "int x" that is in scope is the class variable defined in the first line. To see the difference, try removing the "int" from "int x" within the static block... then, instead of defining a new int variable, you'll be referencing (and updating the value of) the one declared in the first line... then your method will see the value 99.

3. static { int x=10; }
void some_method() { System.out.print(x); } // compiler error saying "x" not found.
What happens when I put the declaration in paranthesis to give this error?



This is very similar to your second question... what you have there is the second question, minus the first line that actually defines a class variable... so all you are left with is the local variable defined in the scope of the static initializer block... which then goes out of scope as soon as that block has completed - it's temporary because it's not defined outside that block. So then, when some_method() is called, it can't find any variable "x" at all.


Hope this helps.
-- Jon
 
Maduranga Liyanage
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jon..

Thanks a lot for the reply.. Cleared all my doubts.. Thanks again.. U guys r great :-)
 
Ranch Hand
Posts: 817
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ya ..good point

but one must also not another point that

change in location of static block also changes the result...
like


prints 10 and

if we reverse the location of static block and static int=10 like

static int x=10;
static { x=99; }

it produces 99

...

why ..any comments...

is it because ...in this case ..java runs with the up-down flow and and first take intialize x=10 as forward refernce ( but i think it must be declared non-local somewhere below ) and then re-initailize with 99

?
any comments
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic