wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes static variable and static block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static variable and static block" Watch "static variable and static block" New topic
Author

static variable and static block

mark I thomas
Ranch Hand

Joined: Apr 07, 2008
Posts: 86
private static String s = null;
static {

s="abc";

}

Which is loaded first ? a static variable or static block ?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18498
    
  40

mark I thomas wrote:private static String s = null;
static {

s="abc";

}

Which is loaded first ? a static variable or static block ?


Initializations of static variables and executions of static initializers are done in the order that they are encountered in source code.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Naishadh Parmar
Ranch Hand

Joined: Jun 02, 2011
Posts: 95

Yes,
Because the "s" variable declaration is encountered first it will be executed first, and the static block will be executed later
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37884
    
  22
There are at least two ways you can verify that.
One is to put a print statement at the start of your static initialiser. Since the default value of fields is null, however, that is not really that informative.
The second way is to view the bytecode with javap -c Foo
The third is to find the section of the Java Language Specification (JLS) about initialisers. That’s 3 out of 2. Beware: the JLS is not easy to read.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18498
    
  40

Campbell Ritchie wrote:
The third is to find the section of the Java Language Specification (JLS) about initialisers. That’s 3 out of 2. Beware: the JLS is not easy to read.


To get more specific, see step 9 of the detailed class loading process...

http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.2

Henry
mark I thomas
Ranch Hand

Joined: Apr 07, 2008
Posts: 86
Thanks !
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static variable and static block
 
Similar Threads
initialization order
From mock...
what is the difference between static variable and static block
static block
a question