File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Block 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 Block" Watch "Static Block" New topic
Author

Static Block

kamlesh tayade
Ranch Hand

Joined: Sep 21, 2005
Posts: 34
public class StaticTest {
static {
System.out.println("Hi there");
}//1
public void print() {
System.out.println("Hello");
}//2
public static void main(String args []) {
StaticTest st1 = new StaticTest();
st1.print();
StaticTest st2 = new StaticTest();
st2.print();
}//2
}//3

Output:
Hi there
Hello
Hello

As the above class is execute and give the output. I am not able to define the thing which is comment as 1. As we all known the things at comment as 2 is method and comment as 3 is class.and the constructor is type classname{}.

If we specify some veriable or method in this static block, is it become static veriable or static method.
if yes, then how to access them in main method.


Kamlesh
Be oN edGE SCJP 1.4, on edGE for SCWCD 1.4
Santana Iyer
Ranch Hand

Joined: Jun 13, 2005
Posts: 335
class SomeClass
{
static
{
System.out.print("Static Initializer block");
}

{
System.out.print("Instance initializer block");
}

public SomeClass()
{
// constructor
}
}


block preceding with static keyword is static initializer block
used to initialize static instance variables it gets executed when class loaded, and not every time new instance is created as static variable are shared by all instances.

while instance initializer block executes every time new instance is created and you can use it to initialize static as well non static member variables.

you may ask than why constructor answer is you can place common initialization code in initializer block.
[ September 30, 2005: Message edited by: Santana Iyer ]
A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 978
HI,

Check this out.....

http://www.coderanch.com/t/400491/java/java/Non-static-initializer-vs-Constructor

Forgot to post the link first time around
[ September 30, 2005: Message edited by: A Kumar ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static Block
 
Similar Threads
Static Questions
static
Static
When is a class loaded?
Just a doubt on static methods