Header Ads

  • Breaking Now

    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:

    1. 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";
      }

      }

      ReplyDelete
    2. 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.

      ReplyDelete
    3. good example for understanding

      ReplyDelete
    4. good example for understanding

      ReplyDelete
    5. Aviral Sharad SrivastavaOctober 14, 2011 at 6:41 AM

      Good explanation Dharm

      ReplyDelete
    6. 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

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

      ReplyDelete

    Post Top Ad

    Post Bottom Ad