Results 1 to 3 of 3

Thread: Static method

  1. #1
    Rubel Rana is offline Member
    Join Date
    Jul 2013
    Posts
    14
    Rep Power
    0

    Thumbs up Static method

    <
    public class TestBlock {

    static{ //1

    System.out.println("I am in static1 block");
    }
    //2
    {
    System.out.println("I am in non static block");
    }

    static{ //3

    System.out.println("I am in static2 block");
    }
    public static void main(String a[]){
    TestBlock block=new TestBlock();
    }
    }

    />

    Ans:
    I am in static1 block
    I am in static2 block
    I am in non static block

    My question is why static methods print serially skipping the nonstatic method??
    Last edited by Rubel Rana; 10-01-2013 at 02:56 PM.

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    926
    Rep Power
    2

    Default Re: Static method

    Because the non-static block only gets hit for instances that you create using "new TestBlock()". In the next example I never create a new instance, only fire a static method. Now the non-static line is gone:
    Java Code:
    public class TestBlock {
    
        static{
            System.out.println("I am in static1 block");
        }
    
        {
            System.out.println("I am in non static block");
        }
    
        static{
            System.out.println("I am in static2 block");
        }
    
        public static void main(String a[]){
            TestBlock.blah();
        }
    
        public static void blah() {
    
        }
    }

  3. #3
    Rubel Rana is offline Member
    Join Date
    Jul 2013
    Posts
    14
    Rep Power
    0

Similar Threads

  1. Replies: 3
    Last Post: 05-31-2012, 07:56 PM
  2. Replies: 7
    Last Post: 09-24-2010, 05:09 AM
  3. Replies: 3
    Last Post: 02-09-2010, 05:22 AM
  4. Replies: 1
    Last Post: 02-10-2009, 10:03 AM
  5. Replies: 1
    Last Post: 08-07-2007, 05:05 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •