Get the tools you need to learn Java skills fast!
Video tutorials, eBooks, hands-on lab exercises, sample code.
Get started
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 The Software Craftsman this week in the Agile 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: 19532
    
  42

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: 41601
    
  31
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: 19532
    
  42

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 !
 
Have you tried LearnNowOnline? http://www.learnnowonline.com/
 
subject: static variable and static block