Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
What will happen if i declare main() in java as non-static?
Next article icon

What will happen if i declare main() in java as non-static?

Last Updated : 27 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

main() method in Java acts as an application's entry point. So declaration must read "public static void main(String[] args)" to work properly .

What happens if you declare main to be non-static is as follows?

Java
import java.util.Scanner; public class Sample{    public void main(String[] args){       System.out.println("This is a sample code");    } } 

Compilation Error:

If we declare main as non-static (public void main(String[] args)), our code will not compile. This is because the Java Virtual Machine (JVM) needs to call the main method without creating an instance of the class. If main is non-static, it would require an instance of the class to be created, which contradicts the purpose of the entry point method.

Reasons Why main() Method Should be Static:

  • No Need to Create an Instance of the Class Containing the Main Method: Making the main method static removes the need to create an instance of the class. Java applications don't need to create a class object in order to begin running from the main function. This is essential because it simplifies the program startup process because the Java runtime environment allows you to invoke a static method directly without generating an object.
  • Entry Point: The main method is the program's entrance point, and it is used by Java applications. Being static indicates that it belongs to the class as a whole, not to any particular instance. In order to begin executing a Java program, the JVM searches for the public static void main(String[] args) function. Main must be static since non-static methods cannot be invoked straight from the JVM without an instance.
  • Memory Efficiency: Static methods are kept in a different location of memory because they belong to the class rather than any specific object. Memory efficiency is improved by separating static procedures from object-specific data (instance variables). In contrast, static methods do not need to allocate memory for each instance of an object, but non-static methods do.
  • Consistency Across Java Applications: By mandating that the main method be static, Java applications are guaranteed to be consistent. The signature of the main method is constant regardless of the class or application. This uniformity makes it easy for developers to comprehend how Java applications begin their execution and streamlines the process of starting Java programs.
  • Activating Command-Line Invocation: Java programs are frequently launched from the command line with a class name specified. If the main method wasn't static, the command to run the program would have to specify extra information about how to make a class instance, which would make the command-line execution process more difficult. The main method can be called directly because it is static, which makes command-line calling easier.
  • Static methods are simple and thread-safe: Because they don't need instance-specific data when they operate so these are simple and thread-safe. Making the main method static promotes thread safety because it is frequently where multithreaded Java applications begin. Additionally, a static main method makes it easier to comprehend how a program works because there is just one entry point, which improves predictability and manageability.

Example of using static:

Java
// Java Program to implement  // Direct Addition to Add two Numbers  import java.io.*;   // Driver Class  class GFG {      public static int sum(int num1, int num2)      {          return num1+num2;      }           // main function      public static void main(String[] args)      {          GFG ob = new GFG();          int res = ob.sum(28, 49);          System.out.println(res);      }  } 

Output
77

Conclusion:

Declaring the main method in Java as non-static is not possible. The Java compiler will generate an error message if you try to do so.

This is because the JVM expects the main method to be static. If main() is non-static, it would require an instance of the class to be created before execution, which contradicts the fundamental purpose of the main() method as the starting point of the program.


Next Article
What will happen if i declare main() in java as non-static?

M

manukumar_gfg
Improve
Article Tags :
  • DSA
  • GFacts
  • Java-Collections
  • java-basics
Practice Tags :
  • Java-Collections

Similar Reads

    What is Class Loading and Static Blocks in Java?
    Class Loading is the process of storing the class-specific information in the memory. Class-specific information means, information about the class members, i.e., variables and methods. It is just like that before firing a bullet, first, we need to load the bullet into the pistol. Similarly, to use
    3 min read
    Are Static Local Variables Allowed in Java?
    In Java, there are different types of variables, each with its own behavior and scope. Understanding these variables plays a very important role. In this article, we will discuss the concept of static with local variables, and we will also discuss in Java static local variables are allowed or not.Wh
    3 min read
    Why non-static variable cannot be referenced from a static method in Java
    Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static.
    4 min read
    Print Hello World Without using a Semicolon in Java
    Every statement in Java must end with a semicolon as per the basics. However, unlike other languages, almost all statements in Java can be treated as expressions. However, there are a few scenarios when we can write a running program without semicolons. If we place the statement inside an if/for sta
    2 min read
    Assigning values to static final variables in Java
    Assigning values to static final variables in Java: In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.For example, follow
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences