Friday, October 16, 2015

Understanding mysterious static - 2

Oh! that was interesting, if you tried executing the program in the previous post. For a second may be it gave a food for thought to your mind. Why main is not executing first? Why am i getting output as:

In static block...InterestingStatic1
In main...InterestingStatic1

May be something is happening before main is executing. I must know it. Everything is mystery until understood. So let me take you to another interesting and mysterious scenario :

Here is what you do. Nothing much. Add InterestingStatic1Test class to the project you created yesterday. Let the class InterestingStatic1 be there in the project without any changes.

package teststatic;
public class InterestingStatic1Test {
        System.out.println("In static block...InterestingStatic1Test");
    public void printSomething(){
        System.out.println("Just printing ... Welcome to Mysteries of Java");
    public static void main(String[] args) {
        System.out.println("In main...InterestingStatic1Test");
        InterestingStatic1Test justObject = new InterestingStatic1Test();
        InterestingStatic1 newObject = new InterestingStatic1();

Yes, you are right. I am going to ask you to guess the output first and then run the program. Does it match your guess? Why the output is what it is.  wait... there is more to come ... See you...

©K.A.N. Nancy

1 comment:

  1. This comment has been removed by a blog administrator.