Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

static variable and static block  RSS feed

 
mark I thomas
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
private static String s = null;
static {

s="abc";

}

Which is loaded first ? a static variable or static block ?
 
Henry Wong
author
Sheriff
Posts: 23275
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Naishadh Parmar
Ranch Hand
Posts: 95
C++ Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 55332
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23275
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks !
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!