aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static initializers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static initializers" Watch "static initializers" New topic
Author

static initializers

jonas okwara
Ranch Hand

Joined: Jun 22, 2004
Posts: 58
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

Joined: Sep 06, 2004
Posts: 6
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

Joined: Aug 31, 2004
Posts: 11343

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 ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static initializers
 
Similar Threads
one Construtor's problem?
why cant the output of the code is 2
What is the difference between these methods?
Magic numbers in code
access to static intilization variables