Wednesday, April 18, 2007

If you have static block, constructor and main method in Java file then what will be the sequence of method calls?

The sequence of call will be:
1. static block
2. main
3. constructor

8 comments :

Anonymous said...

that is wrong , try this, first is the main executed and then static block

public class Tester {

static String s = "int";

public static void main(String[] args){
System.out.println(s);
}

static{
System.out.println(s);
s="my";
}

}

Dharm on July 8, 2007 at 12:50 AM said...

My Anonymous friend..
Thanks for your comments...

Pl revalidate what you have said, answer to this question is still valid.I have made few changes to your code which will help you analyze the scenario more...

public class Tester {

static String s = "int";

public Tester() {

System.out.println("Inside constructor");
}

public static void main(String[] args) {
System.out.println("Inside main method");
Tester tester = new Tester();
System.out.println(s);
}

static {
System.out.println("Inside static block");
System.out.println(s);
s = "my";
}

}


And here is the output which you get at console:
----------------------
Inside static block
int
Inside main method
Inside constructor
my
------------------------

Let me know if it is still not clear to you.

Anonymous said...

Great Job.

jagan on June 16, 2011 at 2:25 AM said...

good example for understanding

jagan on June 16, 2011 at 2:25 AM said...

good example for understanding

Aviral Sharad Srivastava said...

Good explanation Dharm

maanas said...

statis is 1st always but main method or constructor can come next based on the call. For example the below code.

public class Tester {

public static String s="initialised";

static {
s="inside static";
System.out.println(s);
}
public Tester() {
// TODO Auto-generated constructor stub

s="inside constructor";
System.out.println(s);
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Tester t=new Tester();
s="inside main";
System.out.println(s);
}

}



-------------------
output will be
inside static
inside constructor
inside main

Amit said...

maanas please write ur print statement in main at first line . then u'll get main is executing before constructor.

 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2016. Reads: best tracker