Thursday, June 10, 2010

method execution before main method

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

5 comments:

  1. Nice code with good example.
    keep it up and post more blogs like this...............

    ReplyDelete
  2. Dear Kantham,
    It would be good if you discuss some real time examples also on these concepts

    ReplyDelete
  3. Its a good idea for sharing these types of concepts.keep more concepts

    ReplyDelete
  4. Aunties don't need all these I think... :-)

    ReplyDelete