Can We Call Non-Static Methods from main() in Java? Complete Guide
Yes. Methods called from public static void main(String[] args) do not have to be static. They only need to be static if you are calling them directly without…
Yes. Methods called from public static void main(String[] args) do not have to be static. They only need to be static if you are calling them directly without creating an object.
Let’s understand why.
Why is main() static?
public static void main(String[] args) {
// Entry point of the application
}
The JVM calls main() before creating any object of your class. Since no object exists yet, main() must be static.
Case 1: Calling another static method ✅
Since both methods belong to the class itself, you can call them directly.
public class Demo {
public static void main(String[] args) {
printMessage();
}
static void printMessage() {
System.out.println("Hello");
}
}
Output
Hello
Case 2: Calling a non-static method ❌ (Compilation Error)
public class Demo {
public static void main(String[] args) {
printMessage(); // Error
}
void printMessage() {
System.out.println("Hello");
}
}
Compilation Error
non-static method printMessage() cannot be referenced from a static context
Why?
printMessage() belongs to an object, but no object has been created yet.
Case 3: Calling a non-static method using an object ✅
public class Demo {
public static void main(String[] args) {
Demo demo = new Demo();
demo.printMessage();
}
void printMessage() {
System.out.println("Hello");
}
}
Output
Hello
Here:
- JVM calls
main(). main()creates aDemoobject.- The object calls the instance method.
Real-world Spring Boot example
In a normal Java application:
public static void main(String[] args) {
EmployeeService service = new EmployeeService();
service.saveEmployee();
}
saveEmployee() is not static.
In Spring Boot:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
After the Spring container starts, you typically get beans from the container, and those beans expose instance methods:
@Service
public class EmployeeService {
public void saveEmployee() {
System.out.println("Employee Saved");
}
}
The method is still non-static. Spring creates the object (bean) and calls it for you.
Rule to remember
Inside a static method (main()):
| What you want to call | Allowed? | How? |
|---|---|---|
| Static method | ✅ Yes | Call directly: method() |
| Static variable | ✅ Yes | Access directly |
| Non-static method | ❌ No | Need an object |
| Non-static variable | ❌ No | Need an object |
Easy way to remember
- Static members belong to the class.
- No object required.
- Non-static members belong to an object.
- You must create (or obtain) an object before using them.
So the answer is:
No, methods called from
main()do not all need to be static. Only methods you call directly from the static context must be static. If a method is non-static, create (or obtain) an object first and then call it.