• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

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

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic