• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Without writing a main(),Can you execute a program?

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check out this.....& Execute ................

public class QTest{
static{
print(10);
}
static void print(int x){
System.out.println(x);
System.exit(0);
}
}
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hai Manoj,
Yes you can get the output as 10 because while runtime first static block will run before main method.In that code you terminating that program after static block you will get the output of 10.
If that wont have

------------------------
System.exit(0);
------------------------
in your program you will get NosuchMethodError after printing 10 like this
10
Exception in thread "main" java.lang.NoSuchMethodError: main


For more detail modify your program by
-------------------------------------
public class QTest{
static{
print(10);
}
static void print(int x){
System.out.println(x);
}
public static void main(String arg[])
{
System.out.println("i am in main");

}
}
-------------------------------------------
You will get the output as:
10
i am in main.
From this you come to know that after static block only main will run.

Regards,
Premavenkat.
 
Manoj Mani
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes......You are right....This will run, print a message and terminate gracefully. The runtime system needs to load the class before it can look for the main method. So the static initializer will run first and print "10". Immediately after that System.exit(0) will be called terminating the program before an error can be thrown.
 
"To do good, you actually have to do something." -- Yvon Chouinard
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic