Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static initializers

 
jonas okwara
Ranch Hand
Posts: 58
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please could someone explain to me what static initializer is in this example:

class Test {

int a = 20;

static {
int b = 10;

}
 
Emilio Botella
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In static block you've declarated a local variable, you may use it within a loop, for example to initiate others static variables.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static variables are initialized and static block is executed at class load time, which occurs either when the first object of that class is created or when a static member of the class is accessed (even if no object is created). If an object is being created, then instance variables are initialized and non-static initializer block is executed. After this, the body of the constructor executes.

See thread: http://www.coderanch.com/t/246269/java-programmer-SCJP/certification/Initializers

However, as Emilio pointed out, your int b is local to the block. If you want it accessible as a class variable, then you need to declare it as static outside of that block, even if you're going to initialize it using a static block.



( Barry change static b; to static int b; )

[ September 10, 2004: Message edited by: Barry Gaunt ]

Thanks, Barry...
[ September 10, 2004: Message edited by: marc weber ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic