public class tt {
static{
System.out.println("class tt");
}
}
It the first time ive come across it and im wondering what it is and what it's used for
It is the static initialiser of the class. When the class is loaded, the static initialiser is run. It is like the constructor, but for the class rather than for individual objects.
Multiple static initialisers can appear in a class, as well as direct initialisers for static variables. These will be combined into one initialiser in the order in which they are declared. For example, the following will print "foo" to stdout whenever the class is loaded (usually once per application).
public class Foo {
static String a;
static {
a = "foo";
}
static String b = a;
static {
System.println(b);
}
}
Its initilizer block
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
There is an alternative to static blocks —you can write a private static method:
class Whatever {
public static varType myVar = initializeClassVariable();
private static varType initializeClassVariable() {
//initialization code goes here
}
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
Resource
here is the static initializer tutorial http://download.oracle.com/javase/tutorial/java/javaOO/initial.html
It runs when the class is loaded before the initialization.
public class A {
static {
System.out.println("A from static initializer"); // first
}
public A(){
System.out.println("A"); // second
}
public static void main(String[] args){
new A();
}
}
It is a static initializer. The code inside that block runs when the JVM loads the class, which is immediately before the first time the program needs to do anything with that class (e.g. look up a static field, call a static method, instantiate an object,...).
It's a static initializer block. It will be executed once when the class is first loaded, along with static field initializers like this:
private static int staticField = someMethod();
The difference is that an initializer block can contain control flow structures like try/catch blocks.
Related
I want to initialize Final.value in Main method.
Is it possible to initialize static final constant in other class than
in its deceleration class?
public class Main {
public static void main(String[] args) {
//I want to initialize Final.value in Main method.
}
}
class Final {
//here is the static final variable which can be assigned vai a static block
//but how do I initialize it in the main method if I don't use the static block?
static final int value;
}
You cannot. Your perception might be that main happens before everything else, so it is safe to initialise things there, but that is incorrect.
Consider the following code.
class Scratch
{
static
{
System.out.println(Foo.i);
}
public static void main(String[] args)
{
Foo.i = 100;
}
}
class Foo
{
static int i;
}
It does not print 100. It prints 0 because there are other things which happen before main.
Making the field final does not change that fact.
You have two options for static initialization. In a static initializer block, like you showed, or in-line:
static final int value = 421
Java prevents you from doing what you want to do for a good reason: because it is likely to lead to bugs.
Considering the standard java initialization order rules it is not clear to me why the following code
public class Foo {
static { new Foo(); }
static{ System.out.println("static code"); }
{ System.out.println("non static code"); }
public Foo() { System.out.println("constructor"); }
public static void main(String[] args) {}
}
outputs this:
non static code
constructor
static code
So, the static block will execute as soon as the class loader loaded the class. So, your first static block static { new Foo(); } execute first which further calls the constructor new Foo();. As per the java docs the non-static block will be copied to every constructor by the compiler which means System.out.println("non static code"); will be copied to the constructor public Foo() { System.out.println("constructor"); }. So, it will print non static code first then constructor. After the execution of first static block it will execute the second static block which prints the last static code.
After compilation your code looks similar to below code:
public class Foo {
static { new Foo(); }
static{ System.out.println("static code"); }
public Foo() {
System.out.println("non static code");
System.out.println("constructor");
}
public static void main(String[] args) {}
}
The JLS says that
The static blocks and static variable initializations will be executed in program source code order when a class is initialized.
The instance blocks and instance variable initializations will be executed in program source code order when an instance is initialized. This happens after super instance initialization and before the constructor body is executed.
In your example, the first static creates an instance of Foo. This cause the instance block for Foo to be executed while the first static block is being executed. So, the sequence is:
The class is loaded
Static initialization for Foo is triggered
The first static block is executed which does a new Foo().
The instance block is executed - prints "non static code"
The constructor is executed - prints "constructor"
The first static block finishes.
The second static block is executed - prints "static code".
The main method is called.
Well, to refactor the code, do the following steps:
1) remove non-static initialisation block - the compiler puts it before the code in the actual constructor
public class Foo {
static { new Foo(); }
static{ System.out.println("static code"); }
public Foo() {
System.out.println("non static code");
System.out.println("constructor");
}
public static void main(String[] args) {}
}
2) Join static initialisation blocks - see here:
A class can have any number of static initialization blocks, and they
can appear anywhere in the class body. The runtime system guarantees
that static initialization blocks are called in the order that they
appear in the source code.
public class Foo {
static {
new Foo();
System.out.println("static code");
}
public Foo() {
System.out.println("non static code");
System.out.println("constructor");
}
public static void main(String[] args) {}
}
3) From there, it should be obvious.
We can put code in a constructor or a method or an initialization block. What is the use of initialization block? Is it necessary that every java program must have it?
First of all, there are two types of initialization blocks:
instance initialization blocks, and
static initialization blocks.
This code should illustrate the use of them and in which order they are executed:
public class Test {
static int staticVariable;
int nonStaticVariable;
// Static initialization block:
// Runs once (when the class is initialized)
static {
System.out.println("Static initalization.");
staticVariable = 5;
}
// Instance initialization block:
// Runs each time you instantiate an object
{
System.out.println("Instance initialization.");
nonStaticVariable = 7;
}
public Test() {
System.out.println("Constructor.");
}
public static void main(String[] args) {
new Test();
new Test();
}
}
Prints:
Static initalization.
Instance initialization.
Constructor.
Instance initialization.
Constructor.
Instance initialization blocks are useful if you want to have some code run regardless of which constructor is used or if you want to do some instance initialization for anonymous classes.
would like to add to #aioobe's answer
Order of execution:
static initialization blocks of super classes
static initialization blocks of the class
instance initialization blocks of super classes
constructors of super classes
instance initialization blocks of the class
constructor of the class.
A couple of additional points to keep in mind (point 1 is reiteration of #aioobe's answer):
The code in static initialization block will be executed at class load time (and yes, that means only once per class load), before any instances of the class are constructed and before any static methods are called.
The instance initialization block is actually copied by the Java compiler into every constructor the class has. So every time the code in instance initialization block is executed exactly before the code in constructor.
nice answer by aioobe
adding few more points
public class StaticTest extends parent {
static {
System.out.println("inside satic block");
}
StaticTest() {
System.out.println("inside constructor of child");
}
{
System.out.println("inside initialization block");
}
public static void main(String[] args) {
new StaticTest();
new StaticTest();
System.out.println("inside main");
}
}
class parent {
static {
System.out.println("inside parent Static block");
}
{
System.out.println("inside parent initialisation block");
}
parent() {
System.out.println("inside parent constructor");
}
}
this gives
inside parent Static block
inside satic block
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside main
its like stating the obvious but seems a little more clear.
The sample code, which is approved as an answer here is correct, but I disagree with it. It does not shows what is happening and I'm going to show you a good example to understand how actually the JVM works:
package test;
class A {
A() {
print();
}
void print() {
System.out.println("A");
}
}
class B extends A {
static int staticVariable2 = 123456;
static int staticVariable;
static
{
System.out.println(staticVariable2);
System.out.println("Static Initialization block");
staticVariable = Math.round(3.5f);
}
int instanceVariable;
{
System.out.println("Initialization block");
instanceVariable = Math.round(3.5f);
staticVariable = Math.round(3.5f);
}
B() {
System.out.println("Constructor");
}
public static void main(String[] args) {
A a = new B();
a.print();
System.out.println("main");
}
void print() {
System.out.println(instanceVariable);
}
static void somethingElse() {
System.out.println("Static method");
}
}
Before to start commenting on the source code, I'll give you a short explanation of static variables of a class:
First thing is that they are called class variables, they belong to the class not to particular instance of the class. All instances of the class share this static(class) variable. Each and every variable has a default value, depending on primitive or reference type. Another thing is when you reassign the static variable in some of the members of the class (initialization blocks, constructors, methods, properties) and doing so you are changing the value of the static variable not for particular instance, you are changing it for all instances. To conclude static part I will say that the static variables of a class are created not when you instantiate for first time the class, they are created when you define your class, they exist in JVM without the need of any instances. Therefor the correct access of static members from external class (class in which they are not defined) is by using the class name following by dot and then the static member, which you want to access (template: <CLASS_NAME>.<STATIC_VARIABLE_NAME>).
Now let's look at the code above:
The entry point is the main method - there are just three lines of code. I want to refer to the example which is currently approved. According to it the first thing which must be printed after printing "Static Initialization block" is "Initialization block" and here is my disagreement, the non-static initialization block is not called before the constructor, it is called before any initializations of the constructors of the class in which the initialization block is defined. The constructor of the class is the first thing involved when you create an object (instance of the class) and then when you enter the constructor the first part called is either implicit (default) super constructor or explicit super constructor or explicit call to another overloaded constructor (but at some point if there is a chain of overloaded constructors, the last one calls a super constructor, implicitly or explicitly).
There is polymorphic creation of an object, but before to enter the class B and its main method, the JVM initializes all class(static) variables, then goes through the static initialization blocks if any exist and then enters the class B and starts with the execution of the main method. It goes to the constructor of class B then immediately (implicitly) calls constructor of class A, using polymorphism the method(overridden method) called in the body of the constructor of class A is the one which is defined in class B and in this case the variable named instanceVariable is used before reinitialization. After closing the constructor of class B the thread is returned to constructor of class B but it goes first to the non-static initialization block before printing "Constructor". For better understanding debug it with some IDE, I prefer Eclipse.
Initializer block contains the code that is always executed whenever
an instance is created. It is used to declare/initialise the common
part of various constructors of a class.
The order of initialization constructors and initializer block doesn’t matter, initializer block is always executed before constructor.
What if we want to execute some code once for all objects of a class?
We use Static Block in Java.
In addition to what was said in previous answers, blocks can be synchronized .. never felt I need to use it, however,it's there
Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces. It is not at all necessary to include them in your classes.
They are typically used to initialize reference variables. This page gives a good explanation
The question is not entirely clear, but here's a brief description of ways you can initialise data in an object. Let's suppose you have a class A that holds a list of objects.
1) Put initial values in the field declaration:
class A {
private List<Object> data = new ArrayList<Object>();
}
2) Assign initial values in the constructor:
class A {
private List<Object> data;
public A() {
data = new ArrayList<Object>();
}
}
These both assume that you do not want to pass "data" as a constructor argument.
Things get a little tricky if you mix overloaded constructors with internal data like above. Consider:
class B {
private List<Object> data;
private String name;
private String userFriendlyName;
public B() {
data = new ArrayList<Object>();
name = "Default name";
userFriendlyName = "Default user friendly name";
}
public B(String name) {
data = new ArrayList<Object>();
this.name = name;
userFriendlyName = name;
}
public B(String name, String userFriendlyName) {
data = new ArrayList<Object>();
this.name = name;
this.userFriendlyName = userFriendlyName;
}
}
Notice that there is a lot of repeated code. You can fix this by making constructors call each other, or you can have a private initialisation method that each constructor calls:
class B {
private List<Object> data;
private String name;
private String userFriendlyName;
public B() {
this("Default name", "Default user friendly name");
}
public B(String name) {
this(name, name);
}
public B(String name, String userFriendlyName) {
data = new ArrayList<Object>();
this.name = name;
this.userFriendlyName = userFriendlyName;
}
}
or
class B {
private List<Object> data;
private String name;
private String userFriendlyName;
public B() {
init("Default name", "Default user friendly name");
}
public B(String name) {
init(name, name);
}
public B(String name, String userFriendlyName) {
init(name, userFriendlyName);
}
private void init(String _name, String _userFriendlyName) {
data = new ArrayList<Object>();
this.name = name;
this.userFriendlyName = userFriendlyName;
}
}
The two are (more or less) equivalent.
I hope that gives you some hints on how to initialise data in your objects. I won't talk about static initialisation blocks as that's probably a bit advanced at the moment.
EDIT: I've interpreted your question as "how do I initialise my instance variables", not "how do initialiser blocks work" as initialiser blocks are a relatively advanced concept, and from the tone of the question it seems you're asking about the simpler concept. I could be wrong.
public class StaticInitializationBlock {
static int staticVariable;
int instanceVariable;
// Static Initialization Block
static {
System.out.println("Static block");
staticVariable = 5;
}
// Instance Initialization Block
{
instanceVariable = 7;
System.out.println("Instance Block");
System.out.println(staticVariable);
System.out.println(instanceVariable);
staticVariable = 10;
}
public StaticInitializationBlock() {
System.out.println("Constructor");
}
public static void main(String[] args) {
new StaticInitializationBlock();
new StaticInitializationBlock();
}
}
Output:
Static block
Instance Block
5
7
Constructor
Instance Block
10
7
Constructor
Just to add to the excellent answers from #aioobe and #Biman Tripathy.
A static initializer is the equivalent of a constructor in the static context. which is needed to setup the static environment.
A instance initializer is best for anonymous inner classes.
It is also possible to have multiple initializer blocks in class
When we have multiple initializer blocks they are executed (actually copied to constructors by JVM) in the order they appear
Order of initializer blocks matters, but order of initializer blocks mixed with Constructors doesn't
Abstract classes can also have both static and instance initializer blocks.
Code Demo -
abstract class Aircraft {
protected Integer seatCapacity;
{ // Initial block 1, Before Constructor
System.out.println("Executing: Initial Block 1");
}
Aircraft() {
System.out.println("Executing: Aircraft constructor");
}
{ // Initial block 2, After Constructor
System.out.println("Executing: Initial Block 2");
}
}
class SupersonicAircraft extends Aircraft {
{ // Initial block 3, Internalizing a instance variable
seatCapacity = 300;
System.out.println("Executing: Initial Block 3");
}
{ // Initial block 4
System.out.println("Executing: Initial Block 4");
}
SupersonicAircraft() {
System.out.println("Executing: SupersonicAircraft constructor");
}
}
An instance creation of SupersonicAircraft will produce logs in below order
Executing: Initial Block 1
Executing: Initial Block 2
Executing: Aircraft constructor
Executing: Initial Block 3
Executing: Initial Block 4
Executing: SupersonicAircraft constructor
Seat Capacity - 300
Is there any difference between following two initializations of static variables:
class Class1 {
private static Var var;
static {
var = getSingletonVar();
}
}
class Class2 {
private static var = getSingletonVar;
}
Are these two different ways of initializing a static variable functionally the same?
Yes, its functionally the same.
From Java doc
There is an alternative to static blocks — you can write a private static method:
class Whatever {
public static varType myVar = initializeClassVariable();
private static varType initializeClassVariable() {
// initialization code goes here
}
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
The result will be same.
In both the cases static variable will get initialized with class loading.
static methods and static class blocks are two different things.
static methods need to be called where as static class block automatically gets executed with class loading.
First Thing you haven't declared static methods here.
probably if you want know order of execution
1) constructors
Invoked when you create an instance, totally independent of when #2 happens, or even if it ever happens at all
2)static methods
Invoked when you invoke them, totally independent of when #1 happens, or even if it ever happens at all
3)static blocks
Invoked when the class is initialized, which happens before #1 or #2 can happen.
Static initializers and static blocks both run when the class is initialized. Static blocks exist because sometimes you want to do something at initialization time that can't be characterized as a simple assignment:
static final Logger log = Logger.getLogger(ThisClass.class);
static final String PROPS_FILE = "/some/file.properties";
static final Properties gProps;
static {
gProps = new Properties();
try {
FileReader reader = new FileReader(PROPS_FILE);
try {
gProps.load(reader);
} finally {
reader.close();
}
} catch (IOException e) {
throw new SomeException("Failed to load properties from " + PROPS_FILE, e);
}
log.info(ThisClass.class.getName() + " Loaded");
}
I am trying to use static blocks like this:
I have a base class called Base.java
public class Base {
static public int myVar;
}
And a derived class Derived.java:
public class Derived extends Base {
static
{
Base.myVar = 10;
}
}
My main function is like this:
public static void main(String[] args) {
System.out.println(Derived.myVar);
System.out.println(Base.myVar);
}
This prints the out put as 0 0 where as I expected 10 0. Can somebody explain this behavior? Also, if I want my derived classes to set the values for a static variable how can I achieve that?
As I understand. You don't call any Derived properties (myVar belongs to Base, not to Derived). And java is not running static block from Derived. If you add some static field to Derived and access it, then java executes all static blocks.
class Base {
static public int myVar;
}
class Derived extends Base {
static public int myVar2;
static
{
Base.myVar = 10;
}
}
public class Main {
public static void main( String[] args ) throws Exception {
System.out.println(Derived.myVar2);
System.out.println(Base.myVar);
}
}
From java specification, when class is initialized (and static block got executed):
12.4.1 When Initialization Occurs A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
• T is a class and an instance of T is created.
• T is a class and a static method declared by T is invoked.
• A static field declared by T is assigned.
• A static field declared by T is used and the field is not a constant variable (§4.12.4).
• T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
Static initializer-blocks aren't run until the class is initialized. See Java Language Specification paragraphs 8.7 (Static initializers) and 12.4.1 (When initialization occurs):
A static initializer declared in a class is executed when the class is
initialized (§12.4.2). Together with any field initializers for class
variables (§8.3.2), static initializers may be used to initialize the
class variables of the class.
Here's a similar example straight out of JLS 12.4.1:
class Super {
static int taxi = 1729;
}
class Sub extends Super {
static { System.out.print("Sub "); }
}
class Test {
public static void main(String[] args) {
System.out.println(Sub.taxi);
}
}
This program prints only:
1729
because the class Sub is never initialized; the reference to Sub.taxi
is a reference to a field actually declared in class Super and does
not trigger initialization of the class Sub.
There is a single copy of myVar and both parent and child class will share the same.
Untill and unless child class get initilized.
When we do
class Base {
public static int myVar = 0;
static {
System.out.println("Base");
}
}
class Derived extends Base {
static {
System.out.println("Derived");
Base.myVar = 9;
}
}
public class StaticBlock {
public static void main(String[] args) {
System.out.println(Base.myVar);
System.out.println(Derived.myVar);
}
}
The Output will be
Base
0
0
That means derived class's static block not executing..!!
Here is the link to the Java Specification - section 8.7 talks about static initializers. It gives good details about how they should function and the order in which they get called. http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.7