How is this Java program executed? - java

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

Related

Printing static variable without class name leads to an error

public class ClearingDoubtsAboutStatic {
static
{
System.out.println("Static Block1 Output: "+ClearingDoubtsAboutStatic.statVar); //------Line 5
statVar=20; //-----Line 6
System.out.println("Static Block1 Output: "+ClearingDoubtsAboutStatic.statVar); //------Line 7
System.out.println("Static Block1 Output: "+statVar); //---Line 8
}
static int statVar=30;
public static void main(String[] args) {
}
}
What in my mind was that the line 7 and 8 will give the same output, but it is not the case.
My Question
what I don't understand is when we are able to initialize the static variable without the class name at line 6 but why we are not able to print it without the class name at line 8?
The 2 rules you copy/paste are wrong, you should only consider:
Static declaration and static block initialization are considered in
the order they appear in the source file
Thus, you can fix your issue, changing the order of the declaration, and your static initialization block:
static int statVar=30;
static
{
System.out.println("Static Block1 Output: "+ statVar); //------Line 5
statVar=20; //-----Line 6
System.out.println("Static Block1 Output: "+ statVar); //------Line 7
System.out.println("Static Block1 Output: "+statVar); //---Line 8
}
I not quite sure about your case but in my IntelliJ when I try your code, I got this:
Error:(9, 55) java: illegal forward reference
Hmmm i'm not sure about that but i will share with you my guess. Initialization starts first for everything that is static in Class (in defined order). So your static{...} is will be initialized at first, then statVar will receive its value. First printing should show 0 as this is default int value. It works because your are referencing it by Class name and that is how static variables should be referenced. There is one static variable for Class, not for object. When you are trying to reference it without class name, your are treating it like just some field in your class and you shouldn't try to reference those before they are defined. So compiler is not allowing to do so.

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.

Why is this Java code in curly braces ({}) outside of a method?

I am getting ready for a java certification exam and I have seen code LIKE this in one of the practice tests:
class Foo {
int x = 1;
public static void main(String [] args) {
int x = 2;
Foo f = new Foo();
f.whatever();
}
{ x += x; } // <-- what's up with this?
void whatever() {
++x;
System.out.println(x);
}
}
My question is ... Is it valid to write code in curly braces outside a method? What are the effects of these (if any)?
Borrowed from here -
Normally, you would put code to initialize an instance variable in a
constructor. There are two alternatives to using a constructor to
initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static
initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
You may also wanna look at the discussions here.
This is an initializer block that is executed while the instance of the class is being loaded/created and that is used to initialize member properties of a class (See Java http://download.oracle.com/javase/tutorial/java/javaOO/initial.html). You can have as many blocks as you want and they will be instantiated from top to bottom.
In addition to the instance block, you can have as many static blocks as you want as well to initialize static members. They would be declared as follows:
public class Initialization {
static int b = 10;
int a = 5;
static {
b = -9;
}
{
a += 2;
}
public static void main(String[] args) throws Exception {
System.out.println(ClientVoting.b);
System.out.println(new ClientVoting().a);
System.out.println(ClientVoting.b);
System.out.println(new ClientVoting().a);
}
static {
b = 1;
}
{
a++;
}
}
While the class is being initialized, the static member "b" is initialized as 10, then the first static scope changes its value to -9, and later to 1. This is only executed once while the class is loaded. This executes before the initialization of the first line of the main method.
On the other hand, the similar example to your class is the instance reference "a". A is initialized as 5, then the instance block updates it to 7, and the last block to 8. As expected, the static members are only initialized once in this code, while the instance blocks are executed EVERY time you create a new instance.
The output to this example is 1 8 1 8
It's an initializer block. It's used to set instance variables. The motivation to use initializer blocks over constructors is to prevent writing redundant code. The Java compiler copies the contents of the block into each constructor.

When do instance init blocks get called?

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)

Categories