- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to execute a static block without main method in Java?
VM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method.
Example
public class Sample { static { System.out.println("Hello how are you"); } }
Since the above program doesn’t have a main method, If you compile and execute it you will get an error message.
C:\Sample>javac StaticBlockExample.java C:\Sample>java StaticBlockExample Error: Main method not found in class StaticBlockExample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
If you want to execute static block you need to have Main method and, static blocks of the class gets executed before main method.
Example
public class StaticBlockExample { static { System.out.println("This is static block"); } public static void main(String args[]){ System.out.println("This is main method"); } }
Output
This is static block This is main method
- Related Articles
- Can we execute a java program without a main method?
- Why main() method must be static in java?
- Java static block
- Why the main () method in Java is always static?
- A static initialization block in Java
- Will a finally block execute after a return statement in a method in Java?
- Can We declare main() method as Non-Static in java?
- Can we create a program without a main method in Java?
- How to throw an exception from a static block in Java?
- A non-static initialization block in Java
- What are the restrictions imposed on a static method or a static block of code in java?
- Sequence of execution of, instance method, static block and constructor in java?
- Can we change the order of public static void main() to static public void main() in Java?
- Can we have a try block without a catch block in Java?
- How to call a non-static method of an abstract class from a static method in java?

Advertisements