AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



corejava-basics: Can we execute a program without main() method?

Is there any way to execute a java program without main() method? Please explain me with a proper example and scenario.

corejava x 340
basics x 169
Posted On : 2013-11-21 22:00:11.0
profile Saksham Kumar - anyforum.in Saksham Kumar
72933914279
up-rate
5
down-rate

Answers


Yes, one of the way is static block but in previous version of JDK not in JDK 1.7 .  static block is used to initialize the static data member and It is executed before main method at the time of class-loading.
Let´s see the simple example of static block:

class StaticBlockExample{  
static{
  System.out.println("static block is invoked");
 }  
 
public static void main(String args[]){  
  System.out.println("Hello main()");  
 }  
}  

===========================      Output      ============================
static block is invoked      
Hello main()

Similarly following is example of a program having no main() :

class StaticBlock{  
 static{  
 System.out.println("static block is invoked");  
 System.exit(0);  
 }  
}

===========================      Output      ============================
static block is invoked (if not JDK7)

Posted On : 2013-11-21 22:21:13
Satisfied : 1 Yes  0 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523185319392
Reply This Thread
up-rate
4
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in