• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Block

 
kamlesh tayade
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Santana Iyer
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic