In this article, you will learn all about the main method in Java – the starting point of every Java program. The article also describes the new features of Java 21 to 23, which are still in the preview stage.
You will learn in detail:
- What is a
main()
method, and what do we need it for? - How do you run the
main()
method? - What are the components of Java’s
main()
method, and what do they mean? - How can the
main()
method be written much more easily in new Java versions?
What Is the main() Method in Java?
To start a Java program, it requires a main method. This method is the entry point to the program. The JVM (Java Virtual Machine) calls this main method when a program is started and executes the Java code it contains.
Example of a main() method in Java
A simple Hello World Java program with a main method looks like this, for example:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Code language: Java (java)
To start this program, first, save the program code in a file named HelloWorld.java.
Then enter the following command on the command line / in a terminal:
java HelloWorld.java
Code language: plaintext (plaintext)
You should now see the following output:
Hello world!
Code language: plaintext (plaintext)
Congratulations! You have written and started your first Java program.
But why was it so complicated?
What do all the terms like public
, class
, static
, void
, etc. mean in the program code?
The good news is that, as a beginner, you don’t need to know this at first. In modern Java versions, it is much easier!
How? You will see this in the following section.
(If you are still interested, you will find a detailed description of all components of the main method below in the section Java main() method syntax).
The Java 21 main() Method
The main method has been greatly simplified in Java 21. However, this change is still in the preview stage until at least Java 23. This means that details may still change and that you should not use the new main method in production code yet.
In this section, I will show you what will change for you. You can find the technical details behind these changes in the Implicitly Declared Classes and Instance Main Methods section.
Let’s go back to the Hello World example from the first section:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Code language: Java (java)
You had to write a lot of boilerplate code here – code that would be the same in every Java program. The only thing you want to say is: “Please print the text ‘Hello World!’.”
In Java 21 and the current Java version 22 (with activated preview features), you can already write this much shorter:
void main() {
System.out.println("Hello world!");
}
Code language: Java (java)
And in the next Java version 23, it will be even shorter (without System.out
):
void main() {
println("Hello world!");
}
Code language: Java (java)
The main method and the output command are still there – but everything else, including the class around the main method, has been deleted without replacement.
This means that as a Java beginner, you will no longer have to worry about public
, class
, static
, etc., in the future. These terms can be introduced when they are needed.
Please note that you must explicitly activate preview features. For example, if you save the Java 22 variant (the middle example) in a file HelloWorld22.java, then you must start the program as follows:
java --enable-preview --source 22 HelloWorld22.java
Code language: plaintext (plaintext)
The following section explains the technical details behind the changes.
Implicitly Declared Classes and Instance Main Methods
In the previous section, you learned that in the future, a Java main method can be written without a class, without public static
, and without String[] args
, and that a simple println(...)
is sufficient for the output instead of System.out.println(
....
)
This makes the following code a valid and complete Java program in the future:
void main() {
println("Hello world!");
}
Code language: Java (java)
This section describes in detail the changes that have made this simplification possible.
First of all, the history of the changes:
- It all started in Java 21 with a preview feature with the complicated-sounding name “Unnamed Classes and Instance Main Methods” (defined in JDK Enhancement Proposal 445).
- In Java 22, the feature was renamed to the even more complicated name “Implicitly Declared Classes and Instance Main Methods” (defined in JDK Enhancement Proposal 463).
- In Java 23, the feature was improved once again (JDK Enhancement Proposal 477).
In the following, I describe the three components of the new feature: implicitly declared classes, instance-main methods, and the automatically imported java.io.IO
class.
Implicitly Declared Classes
For a Java file without an explicit class declaration, for example, without public class HelloWorld
, the Java compiler will, in the future, generate an “implicit class” with a name defined by the compiler. As a rule, this is the file’s name without the .java extension.
For example, if you compile the file HelloWorld.java, the compiler creates the file HelloWorld.class – and if you then decompile it, you will see that the class name is also HelloWorld
.
The following characteristics apply to implicit classes:
- An implicit class is always in the unnamed package (just like any regular class without
package
definition). - An implicit class is generally
final
, so it cannot be inherited. - An implicit class cannot implement interfaces or extend other classes.
- An implicit class cannot be accessed via the name specified by the compiler, i.e., other classes cannot instantiate an implicit class, and they cannot call any methods on it, not even static ones.
However, an implicit class can call methods on itself, i.e., methods that are defined in the same .java file, as in the following example:
void main() {
println(greeting());
}
String greeting() {
return "Hello, World!";
}
Code language: Java (java)
Since an implicit class cannot be accessed from outside, it must always contain a main method.
Instance Main Methods
Instance main methods are non-static main methods, i.e., main methods without the static
keyword. The following main methods will be permitted in the future:
- non-static instance methods,
- Methods with the visibility level public, protected, or package-private (without a modifier),
- Methods with or without
String[]
parameters.
Here are a few examples:
void main()
void main(String[] args)
public void main()
protected static void main(String[] args)
Static and non-static methods with the same signature, as well as methods with different visibility modifiers with the same signature, are mutually exclusive and lead to a “method is already defined” compiler error.
However, it is possible for a main method with a String[]
parameter and a main method without parameters to exist simultaneously in the same .java file:
void main(String[] args) {
. . .
}
protected static void main() {
. . .
}
Code language: Java (java)
In this case, the JDK developers specified that the method with the String[]
parameter has priority. In the example, the JVM would start void main(String[] args)
.
Console Interaction With java.io.IO
It was not until the third preview phase of the changes, in Java 23, that the new class java.io.IO
was introduced – with the following static methods:
void print(Object obj)
– prints the passed text or the text representation of the passed object to the console – without a line break at the end.void println(Object obj)
– prints the passed text or the text representation of the passed object to the console – with a line break at the end.String readln(String prompt)
– displays the passed prompt, accepts a user input, and returns it.
An implicitly declared class automatically imports all java.io.IO
methods as if the class contained the following import statement:
import static java.io.IO.*;
Code language: Java (java)
This is what makes it possible for the methods to be called without a qualifying class name prefix.
Java main() Method Syntax
This section describes the syntax of the main method before the simplifications introduced in Java 21. Previously, a main method had to be embedded in a class, and its syntax was rigid:
public class MyMainMethodDemo
public static void main(String[] args) {
// code to execute
}
// possibly more code
}
Code language: Java (java)
Only the name of the class, in the example MyMainMethodDemo
, and the name of the parameter, in the example args
, may be freely chosen.
If a program consists of several classes, any number of these classes may contain a main()
method. To start a program, you need to specify the name of the class whose main()
method you want to run, as shown at the beginning of the article.
What do the individual elements mean?
public class MyMainMethodDemo
This first line of code introduces a class in the sense of object-oriented programming. MyMainMethodDemo
is the name of the class. Java code is always arranged within classes.
public static void main(String[] args)
The second line, the so-called method signature, introduces a method. Methods contain the program code to be executed.
public
public
is a so-called visibility modifier. A class and the main()
method it contains must be public
so that the JVM can call the main()
method and thus execute the program code it contains.
static
Object orientation differentiates between static methods and instance methods. Static methods can be called without having to create an instance of the class surrounding them – i.e., an object. Instance methods, on the other hand, can only be called on an object.
The main()
method in Java must be static so that it can be called without instantiating the class – i.e. without creating an object of this class.
void
Methods can return values, e.g., Math.random()
returns a random number. However, a main()
method has no return value. And this is precisely what is indicated by the identifier void
.
String[] args
This is a parameter of the method. String[]
ist der Typ des Parameters: ein String-Array. And args
is the name of the parameter. This name may be changed. When starting a program, so-called command line parameters can be passed, e.g., like this:
java HelloWorld.java happy coders out there
Code language: plaintext (plaintext)
These parameters are passed to the main()
method as a string array and can be read and printed there, for example:
public class HelloWorld {
public static void main(String[] args) {
System.out.print("Hello");
for (String arg : args) {
System.out.print(" " + arg);
}
System.out.println("!");
}
}
Code language: Java (java)
If you call this program as above, you will get the following output:
Hello happy coders out there!
Code language: plaintext (plaintext)
Conclusion
The main()
method is the starting point of every Java program. Without this, no Java program can start. Until now, the syntax of main()
methods was rigidly predefined:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Code language: Java (java)
In the current Java version 22 – with activated preview features – the same main()
method can be written as follows:
void main() {
System.out.println("Hello world!");
}
Code language: Java (java)
And in the next version, Java 23, it will be even shorter:
void main() {
println("Hello world!");
}
Code language: Java (java)
This makes it easier, particularly for Java beginners, to learn the language. Concepts that only become relevant for larger programs, such as classes, the distinction between static and instance methods, visibility modifiers such as public
, protected
, and private
, as well as coarse-grained structures such as packages and modules, can be introduced when needed.
If you liked the article, please share it using one of the share buttons at the end or leave me a comment.
Would you like to be informed when new articles are published on HappyCoders.eu? Then click here to sign up for the HappyCoders.eu newsletter.