The sequence of call will be:
1. static block
2. main
3. constructor
World of tricky Core Java Q&A(Java SE),Java EE and Open source technologies like Struts,Hibernate,Spring,Velocity etc
Disclaimer
Interview Questions On Java,Java EE Copyright © 2012
7 comments:
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";
}
}
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.
Great Job.
good example for understanding
good example for understanding
Good explanation Dharm
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
Post a Comment