This question already has answers here:
Java independent block of code [duplicate]
(2 answers)
Calling a Java method with no name
(8 answers)
Closed 9 years ago.
Hello Friends what is the use of having just a block in Java class
public class StaticExample {
{
System.out.println("I m here...");
}
}
That's an initialization block. It gets executed when a new instance is created. If you think that that's a job for the constructor, it is a place where you can put code that is executed no matter which constructor is used. They are executed in the order they appear, before the constructor. If you put static in front of an initialization block, it becomes a static initialization block, which is executed as soon as the class is loaded.
It's called an initializer block and is invoked every time an instance of the class is created.
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
The code is invoked before the code in the constructor and doesnt depend on the latter.
public class InitializerExample {
public InitializerExample() {
System.out.println("InitializerExample");
}
{
System.out.println("I'm here...");
}
public static void main(String[] args) {
new InitializerExample();
}
}
will produce
I'm here...
InitializerExample
It is documented in the official tutorial here
Related
This question already has answers here:
Why does a Java method reference with return type match the Consumer interface?
(2 answers)
Why does the following casting with method reference not produce a compilation error? [duplicate]
(2 answers)
Closed 4 years ago.
I encountered code like this(I simplidied it a bit) in the article:
public class Main {
static class A {
}
public static void main(String[] args) {
new Thread(A::new).start();
}
}
I surprised about that code because from my point if view it must produce compile time error because Thread constructor accepts Runnable but A doesn't have methid run but it compiles and even starts without any errors/exceptions. I checked it on my PC in several variations and it works anyway.
So I have following questions:
Why there no compilation errors?
Which method executes instead of run method?
A Runnable is a FunctionalInterface which can also be represented in lambda expression as in your case:
new Thread(() -> new A())
which is nothing but a similar representation of method-reference
A::new
that in your code is equivalent to
new Runnable() {
#Override
public void run() {
new A(); // just creating an instance of 'A' for every call to 'run'
}
}
This question already has answers here:
What is the difference between a static and a non-static initialization code block
(9 answers)
Closed 4 years ago.
The result is:
1
3
1
3
1
3
2
The constructor runs for A,B and for C (3 times). But if you use static keyword it runs only once. What is the reason of this? And why does this line executes last?
enum Enums {
A, B, C;
{
System.out.println(1);
}
static {
System.out.println(2);
}
private Enums() {
System.out.println(3);
}
}
public class MainClass{
public static void main(String[] args) {
Enum en = Enums.C;
}
}
There are three different things at play here:
private Enums()
{
System.out.println(3);
}
This is the constructor. It (or some other potential constructor) runs when an instance is created.
{
System.out.println(1);
}
This is an instance initializer. It runs when an object is being constructed, regardless of which constructor is used.
static
{
System.out.println(2);
}
This is a static initializer. It gets run once this class has been loaded into the JVM, whether or not an instance is being created. However, since we're dealing with an enum, all its instances have to be created as part of loading the class. That's why it runs after the three constructors and initializers.
To complement #smallhacker answer you should read the answers in Static initializer in Java
Uff! what is static initializer?
The static initializer is a static {} block of code inside java class,
and run only one time before the constructor or main method is called.
This question already has answers here:
Static block in Java not executed
(5 answers)
Closed 8 years ago.
class a
{
static final int a =5;
static {
System.out.println("hi");
}
}
class b
{
public static void main(String[] args) {
System.out.println(a.a);
}
}
Why doesn't the static block run,and the output is only
5
whereas if I remove final keyword from the class variable, the static block gets executed and the output becomes
hi
5
Basically what happened is that the static final combination on primitives and Strings cause them to be inlined by the compiler, and this might have prevented the static initialization block from execution, since a class is never loaded by the classloader, as a.a was resolved during compilation
Because your variables with the keywords static final are compiled-time constants which do not trigger the loading of the class containing the field.
Try putting running this code with static final on the variable a
System.out.println(a.a)
a var = new a();
as you can see the output will be
5
hi
The static block isnt triggered when a is called but the moment an instance of the class is created it gets triggered. It can be triggered by any of these:
an instance of the class is created,
a static method of the class is invoked,
a static field of the class is assigned,
a non-constant static field is used, or
for a top-level class, an assert statement lexically nested within the class is executed.
A question very similar to yours which might be helpful:
Static block in Java not executed
This question already has answers here:
In what order do static/instance initializer blocks in Java run?
(8 answers)
Closed 9 years ago.
class prog
{
static
{
System.out.println("s1");
}
prog()
{
System.out.println("s2");
}
public static void main(String...args)
{
prog p = new prog();
}
}
Output is
s1
s2
As per the output, it seems that static initialization block gets executed before the default constructor itself is executed.
What is the rationale behind this?
Static block executed once at the time of class-loading & initialisation by JVM and constructor is called at the every time of creating instance of that class.
If you change your code -
public static void main(String...args){
prog p = new prog();
prog p = new prog();
}
you'll get output -
s1 // static block execution on class loading time
s2 // 1st Object constructor
s2 // 2nd object constructor
Which clarifies more.
Strictly speaking, static initializers are executed, when the class is initialized.
Class loading is a separate step, that happens slightly earlier. Usually a class is loaded and then immediately initialized, so the timing doesn't really matter most of the time. But it is possible to load a class without initializing it (for example by using the three-argument Class.forName() variant).
No matter which way you approach it: a class will always be fully initialized at the time you create an instance of it, so the static block will already have been run at that time.
That is right static initialization is being done when class is loaded by class loader and constructor when new instance is created
Static block one time execution block..
it executes while class loading..
when object is created for a class constructor executes..
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static Initialization Blocks
Unusual “static” method declaration
I'm trying to prepare for a OCJPC in the near future, and I came across a construct I had never seen before. As it is tough to google for programming constructs, I am asking the question here. The code fragment:
class Geryon {
static { System.out.print("a"); }
{ System.out.print("b"); }
Geryon(String s) { System.out.print(s); }
public static void main(String[] args) {
new Geryon("c");
}
}
I am referring to the 2 print statements inside theGeryon() method header in the place where I would expect a return type. As far as I was able to google, a static method header consists of:
access-modifier keyword-"static" return-type|void method-name
Judging from the answer to the quiz question, the code does not only compile, but will also be run. Can anyone direct me to a source where this is explained?
A is a static initializer that gets called when the class is initialized by classloader, this :
static { System.out.print("a"); }
And the other (B) is an anonymous block that gets called every time the class is instantiated :
{ System.out.print("b"); }
Oh and the third print statement, C, is just a normal constructor call.
You will get all three lines if you instantiated one Geryon, like the code you posted. But then the next time you instantiated a Geryon you will only get two - B and C; as it has already been initialized by classloader, so the static block does not get called.