aspose file tools*
The moose likes Beginning Java and the fly likes Static variable vs Static initializer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static variable vs Static initializer" Watch "Static variable vs Static initializer" New topic
Author

Static variable vs Static initializer

Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
Hi
I have simple question.I know the static initializer block will run first when the class is loaded.But when the value of static field is assigned after the initializer block
for eg.

class{
static {
stint = 100;
stint1=1000;
}
private static int stint = 10;
private static int stint1;

public static void main(String[] args) {
System.out.println(stint);
System.out.println(stint1);
}
}

If i run this class why it is showing the outputp as 10 and 1000 instead of 100 and 1000.

If the order is matter i.e (first initializer block then static variables) then it should display 0 for stint1 right?

But if i place both the private statements before the static block then i m getting output as 100 and 1000?
Please Explain.


SCJP 6,SCWCD 5,SCBCD 5

Failure is not an option.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 3950
    
  17

Order does matter for the assignments. The static initialization goes like this:

1) Static variables are declared
2) Static variable assignments and static blocks are executed in the order they are declared.

So in your example:


Acts like:


Steve
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static variable vs Static initializer
 
Similar Threads
same with super
basic question about static initializer block
Question on scope
question about code in { }
static block