• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

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.
 
A day job? In an office? My worst nightmare! Comfort me tiny ad!
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic