The above question means that we need to execute some line of code which perform something before the main() method execution. As we know that when we execute our program JVM will call main() at very first , so it seems that its not possible to perform something before the main() method execution but is possible with the static initialization block and calling method while initializing static variable 

Important Points :

1. Static initialized will always be executed before main() method calling by JVM.
2. Final static variable can be initialized using static initialization block.

1st Approach by static initialization block: 

Program :

public class Lab1 {

    static {                       // static initialization block
 int sum=10+20;
 System.out.println("SUM:"+sum);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}

In the above program sum=10+20 will be executed before main() method and hence output will look like ,
SUM:30
main() method

NOTE : We can also call a static method from static initialization block which too can perform some task which will always counted before main() method execution.


public class Lab1 {

    static {                 // static initialization block
 int s=Lab1.sum(10,20);
        System.out.println("SUM:"+s);
    }

    public static int sum(int a,int b ){
        return (a+b);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}


Now in the above program static sum() method will be called first before main() method. And the output will look like ,

SUM:30
main() method

2nd Approach by Calling static method while initializing static variable :

public class Lab1 {

    static int x=Lab1.sum(10,20); 

    public static int sum(int a,int b ){
        System.out.println("SUM:"+(a+b));
        return (a+b);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}



In the above program at the time of call loading JVM will try to initialize the static variable 'x' here and while initializing it will call static method sum(). So this method will be executed before the main() method execution. The output will look like,

SUM:30
main() method







1 comment:

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic