When do instance init blocks get called? - java

Consider this code:
public class Main {
static String s = "-";
public static void main (String [] args){
go();
System.out.println(s);
Main m = new Main();
}
{go();}
static {go();}
static void go(){s+="s";}
}
Its output is:
-ss
the instance init block is never called, why?

It is called - AFTER you've printed s. Instance initializers are called when instances are created.

It is called. However it is called after the call to println because you create the first instance of Main of that. If you move the call to println to the end of main, you'll see three s.

Instance initialization block code runs right after the call to super() in a constructor, in other words, after all super constructors have run.
The order in which initialization blocks appear in a class matters. If a class has more than one they all run in the order they appear in the class file.
Some rules to remember:
List item Initialization blocks execute in the order they appear.
Static Initialization blocks run once when the class is first
loaded.
Instance Initialization blocks run every time a class
instance is created.
Instance Initialization blocks run after the
constructor’s call to super().

It is called, but after you print to the console. You aren't making an instance of it until after printing.

As the others have pointed out, the instance init block is called, but it doesnt affect the output of your System.out.println statement, because it is called in conjunction with the invocation of the instance of your class: Main m = new Main();
One thing you could do when trying to debug these cases is to dump a thread stack at the invocation point:
static void go() {
new Exception().printStackTrace(System.out);
s += "s";
}
This will allow you to see all the times that the go method is called, and by using the same print stream as your println in your main method, you can see the stacks in relation to the output of your s var.
In my version, the result looks like this:
java.lang.Exception
at Main.go(Main.java:29)
at Main.<clinit>(Main.java:25)
java.lang.Exception
at Main.go(Main.java:29)
at Main.main(Main.java:14)
-ss
java.lang.Exception
at Main.go(Main.java:29)
at Main.<init>(Main.java:21)
at Main.main(Main.java:17)

Related

How is this Java program executed?

class Welcome{
public static void main(String args[]){
System.out.println(Hello.a);
}
}
class Hello{
static int a=10;
static Hello h=new Hello();
{
System.out.println("IB");
}
static{
System.out.println("SB");
}
}
Output:
IB
SB
10
I really don't understand the logic behind this execution. According to me, the static variables are initialized and static block gets executed. Then, the instance variable is initialized and instance block is executed.
However, this seems to be a bit confusing. It would be a great help if a step-by-step order of actual execution is given.
What is the meaning of static Hello h=new Hello();?
How will this be treated?
I fixed the class keyword and ran it through. The execution is quite straight forward when you see it running.
Static variables are initialised. That means a and h are set.
Initialiser blocks are ran. So "IB" is printed. They run because the value of h is a new Hello object.
NOTE: This only happens because h is defined before the static initializer block in the class. If you change the order they appear in the code, then the order of execution will change.
Static initialiser blocks are ran. So "SB" is printed.
main method is invoked, which prints out Hello.a. So 10 is printed.
IDEOne Link: http://ideone.com/KfdS6n

Why Instance Initialization blocks are executed first than constructors?

I'm not able to get exactly why this code gives an output 0?
public class Poly
{
public static void main(String[] args)
{
Square sq=new Square(10);
}
}
class Square
{
int side;
Square(int a)
{
side=a;
}
{
System.out.print("The side of square is : "+side);
System.out.println();
}
}
What I want to ask-
Why it is showing output 0,and not 10?
Why Instance Initialization Block is initializing first and then
constructors?
It's not an instance initializer's job to completely initialize the whole object, you can have multiple initializers that each handle different things. When you have multiple initialization blocks they run in the order in which they appear in the file, top-to-bottom, and they cannot contain forward references. This article by Bill Venners has a lot of useful detail.
On the other hand, a constructor is responsible for initializing the entire object. Once the constructor has run the object is initialized, it should be in a valid state and be ready to be used.
So if an instance initializer ran after the constructor it wouldn't be initializing, it would be changing something that was already set. So the initializers have to run before the constructor.
Order is something like this, the static blocks go first and then the non static blocks. Then the Constructor.

Java static method vs main static method

I'm having trouble understanding the following code's execution. I want to follow the Java program so that I can understand how everything works together. I step up breakpoints in Eclipse but it doesn't explain why. Here's the code:
public class Sequence {
public Sequence() {
System.out.print("c ");
}
{
System.out.print("y ");
}
public static void main(String[] args) {
new Sequence().go();
}
void go() {
System.out.print("g ");
}
static {
System.out.print("x ");
}
}
The output to the code is x y c g. Can someone explain why this is? I thought the program entry point was public static void main but it appears static executes first?
The static block is executed before the main starts, so x get printed.
Then we enter the main, and we call
new Sequence().go();
Which calls the Sequence constructor. As per the static block, before The Sequence constructor gets called (so before a new Sequence object gets initialized), the instance block (the one written within the braces) gets executed, so y gets printed.
Then the constructor call prints c.
In the end, the go() method gets called on the newly created object, so g gets printed.
So the full output will be
x y c g
The JLS is of help here, chapter 12 to be precise.
First the static block will run. This will happen when the class is loaded by the ClassLoader.
Then main will run, this is executed by the JVM to start the application.
Then your constructor is executed when you call new Sequence(). The compiler will yank your instance initialiser (the bit in curly brackets) into the top of the constructor (after the implicit call to to the superclass constructor). So the bit in curly brackets runs first then the code in the constructor.
Finally the method go() is called.
So the output of the code is x y c g
Java execute static block after class loading and before any method. Main method is entry point for any program but it is however a method then static class initialization.
In your class you have used
//constructor
public Sequence() {
System.out.print("c ");
}
//instance init block
{
System.out.print("y ");
}
//method
void go() {
System.out.print("g ");
}
//static init block
static {
System.out.print("x ");
}
-> Init blocks execute in the order they appear.
->Static init blocks run once, when the class is first loaded.
-> Instance init blocks run every time a class instance is created.
-> Instance init blocks run after the constructor's call to super().
->Constructor run after when you create an instance.
According all of that rules you got,as expected x y c g output
First jvm loads static blocks when application starts. So static block executed first.
Then main method execution starts.
{
System.out.print("y ");
}
is the constructor block it will be copied to each constructor so when u instantiate class it will be called every time.
Click here
Steps:
i. When class is loaded then static block is executed first.
ii. Every time object of that class is instantiated then initialization block
i.e.
{
System.out.print("y ");
}
is executed(every time) and after that the time of constructor comes to be executed.
iii. When object creation is finished then go() method is executed.
And hence the output.

How the output of program came?

The output of following program is:
superstatic block
static blockn0
inmain
super constructor
constructor
Here is the code:
class StaticSuper{
static {
System.out.println("superstatic block");
}
StaticSuper(){
System.out.println("super constructor");
}
}
public class StaticClassExample extends StaticSuper{
static int rand;
static {
rand =(int) (Math.random() * 6);
System.out.println("static blockn" + rand);
}
StaticClassExample(){
System.out.println("constructor");
}
public static void main(String[] args) {
System.out.println("inmain");
StaticClassExample st= new StaticClassExample();
}
}
Why "inmain" is printed third though it is first in the main()? Please explain me the meaning of:
static {
// some lines
}
in the class.
The static block you're seeing is what we call a static initializer and its job is usually to initialize something in the class (perhaps a class-wide state or some kind of resource).
It is invoked when the class is loaded by the runtime and that's why it may be run before main is run.
1 : when you create an instance by using new == > it calls the constructor
2 : just when you constructor is called , the parent constructor is called
3 : and also whenever a class is loaded , even for a constructor , the static blocks are executed first ,
thus you get the order you are getting
since you are executing you class , the complete files is checked first for any static block , and static blocks are executed even before the main method gets called
Static blocks are called at the time classes are loaded. Thats why print outs of static are printed first.
Static variable means that there won't be separate copies of that variable for different instances of that class.
Static block of code is simply if you want to execute something at the time of class loading.
Please explain me the meaning of static { // some lines } in the
class.
It's called a static initializer. It's executed when the class is loaded (or initialized, to be exact). The static blocks will be executed before your main()method.
Why "inmain" is printed third though it is first in the main()?
Since static blocks are executed before your main(), it appears third in the print list and when you create the instance of StaticClassExample class, first its parent constructor is called and then its own constructor is called.
Hence, the output.

Need an explanation for the output

Why are "Hi1" and "Hi3" displayed twice by the following code?
static int a=1;
public static void main(String[] args) {
if (a==2) { System.out.println(args[0]); a = 3;}
if (a==1) { main(); }
System.out.println("Hi1");
System.out.println(new PlayingWithMain().main("Hi3"));
}
public static void main() {
a = 2;
String[] a = new String[10];
a[0] = "Hi2";
main(a);
}
String main(String s) {
return s;
}
I have just started preparing for the OCPJP exam.
The first lesson — or trick, depending on how you look at it — of this question is that only one main method is special, no matter how many main methods are present. The special one is the one that takes the form
public static void main( /* multiple arguments */ ) { ... }
In the past, the argument had to be String[] args, but for recent versions, var-args are also acceptable (e.g. String... args). JLS 12.1.4
Now that we know which method to start with, we see that the first line checks the value of a. We see that it's initialized to 1, so we can ignore the a==2 line. Then, on the next line, we jump to the no-argument main.
In the no-arg main, a gets set to 2. The next lesson is that method-local variables can hide class variables. A new a gets declared, and it takes precedence inside the method but only lives as long as the method does. It's an array of strings of size ten, but only the first one is set (to "Hi2"). There's one more lesson in this method: this code is written to make you think the string-arg main gets called next, but it doesn't, because we haven't created an object and it's not static. Instead, we go back to main(String[] args).
This time, a is 2 — remember, we set it in the no-arg main, and a is static so the change sticks around — so we print the first argument, "Hi2." Next, we set a to 3, so the upcoming a==1 test fails. In the following line, we print "Hi1" for the first time and create a new instance of PlayingWithMain, which I assume is the class that the whole code snippet lives in.
Since a is static, its value remains 3 even for the new object. However, since the object is calling main("Hi3"), we don't go to a static version of main; instead, we go to the string-arg main. That method just kicks the input right back to the caller, where it gets immediately printed out.
That does it for the string-array-arg main, so we go back to the method that called it, the no-arg main. It's also finished, so we go back again, to the version of main(String[] args) that the JVM called. Remember, we just completed the line
if (a==1) { main(); }
so we move on to printing "Hi1" again. Finally, we repeat the last line, which creates another new PlayingWithMain object and prints "Hi3" one last time.
main(String[]) calls main() which again calls main(String[]) if a==1, which is true at the beginning.
The a variable is used to make this recursion only happen once and not endlessly.
This is why the main(String[]) method is executed twice, and this is why the output written from that method appears twice.

Categories