We can execute some special kind of methods and blocks before main method execution. When program execution started, at that time JVM will initialize static variables, static blocks first, then only it will start static main method execution. So, if we write a static block, JVM will execute that static block first, then after it will execute main method. In that static block you can call only static methods. In this way we can execute some special kind (only static methods) of methods before main method execution.
Here, i am giving one exmple as follows,
public class Test {
private static int random = 123;
public static void main(String args[]) {
System.out.println("Hi, i am main() method.");
System.out.println("random value from main() method : " + random);
}/*main()*/
static {
System.out.println("Hi, i am static block.");
System.out.println("random value from static method : " + random);
random = 345;
getValue();
}/*static*/
private static void getValue() {
System.out.println("Hi, i am getValue() method.");
System.out.println("random value from getValue() method : " + random);
random = 456;
}/*getValue()*/
}/*class*/
OUT PUT:
Hi, i am static block.
random value from static block : 123
Hi, i am getValue() method.
random value from getValue() method : 345
Hello, I am main() method.
random value from main() method : 456
nice blog man............
ReplyDeleteNice code with good example.
ReplyDeletekeep it up and post more blogs like this...............
Dear Kantham,
ReplyDeleteIt would be good if you discuss some real time examples also on these concepts
Its a good idea for sharing these types of concepts.keep more concepts
ReplyDeleteAunties don't need all these I think... :-)
ReplyDelete