In Java static block is used to initialize the static data members. Important point to note is that static block is executed before the main method at the time of class loading.
This is illustrated well in the following example:
class staticExample {
static
{
System.out.println( "Inside Static Block." );
}
public static void main(String args[])
{
System.out.println( "Inside main method." );
}
}
|
One question arises from the above example:
Question: Can we execute a Java class without declaring main() method?
Answer: No since JDK 1.7 it is not possible to execute any java class without main() method. But it was one of the ways till JDK 1.6.
Example:
class staticExample {
static
{
System.out.println( "Inside Static Block." );
System.exit( 0 );
}
}
|
Output:(In JDK 1.6)
Inside Static Block.
But from JDK 1.7 onwards the above code gives an error in output.
Output:
Error: Main method not found in class staticExample, please define the main method as:
public static void main(String args[])
or a JavaFX application class must extend javafx.application.Application
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
20 Dec, 2018
Like Article
Save Article