In this tutorial of our Java learning, we will learn what a Java main method is, how to create it, pass arguments to it, operate on the parameters, and how to execute it to generate output from the provided parameters. We will learn the basic requirements to ensure the main method is executed with no errors by including packages where necessary and naming files and classes appropriately.
Table of Contents
1. Class Declaration
In Java, every application starts with a class, and the term that is mostly used for this development approach is called encapsulation, which is a way to hide the implementation from the outside. A class declaration comprises the keyword class
, followed by a class name and opening and closing curly braces, and the code goes between the curly braces.
A class can be used to achieve more advanced functionality of a system, but we cover that in another tutorial. Class names should be nouns having mixed cases with the first letter of each internal word capitalized and the most basic form is as shown below. The class names should be simple and descriptive, leveraging whole words without acronyms and abbreviations according to the Java naming convention.
When creating a class in Java, the file name must be the same as the class name else the application will not work.
class HelloWorldApp {
}
It is a good practice to include our classes in a Java package to help in separating concerns and allow faster development by making changes easily.A package is a namespace that organizes a set of related classes and interfaces.Think about the package is a directory that contains our classes and can have nested directories containing classes for other functionalities of a system.
We can create a package from anywhere on our computer using the right naming convention and then import it to our development environment to change the files. The prefix names of a package are always written in all-lowercase ASCII
letters and should use one of the top-level domain names such as com and edu or one of the two-letter English codes such as US or UK that identify countries.
Other sub-packages may depend on the different components in an organization, such as division, department, project, machine, and login names. When you create a class inside a package, the package name that the class belongs to must be declared at the top of the class, as shown below.
package com.javadevjournal;
class HelloWorldApp {
// class containing the main logic
}
2. Java main class
A Java application can have many classes that have dependencies to ensure sharing of data, conversion of data from one type to another, reading and writing files and all these cannot be achieved without the main class.
The main class is just a normal class but has a java main method which we will cover in this tutorial. We can have more than one class in a Java application but we have to show which class the java virtual machine should run as it executes a single main class at a time.The following is the syntax of the main class:
package com.javadevjournal;
class HelloWorldApp {
public static void main(String[] args) {}
}
3. Syntax of the Java main method
The Java main method contains a set of instructions that can be executed as if they were a single operation and this is achieved by calling the method. Every Java application should have a main method, which is the entry point for our program where execution starts.
This method is responsible for calling all the other methods required by the application and is like the main function in C
and C++
with the exception that it does not return any value.The main method in Java has the following signature and is invoked by the JVM
when we bootstrap our application.
public static void main(String[] args)
The convention is to use public static but we can use any order when working with both of the modifiers.
- The main method has only one parameter which is composed of an array of elements of type string.
- The array of a string is represented by the parenthesis enclosing the String keyword and the opening and closing brackets.
- The
args
name is a variable name we used to show an array of arguments, but we can change the name to whatever we like.
The main method body goes inside the opening and closing curly braces and we can instruct the main method to print a hello world message to the console as shown below.
package com.javadevjournal;
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
The statement we added inside the main method body uses the System class which comes from the core library to print the message to standard output. Let’s understand some important points of our first java program.
public
keyword – This is an access modifier, and it shows that the main method is accessible throughout the whole application (we will cover it in later articles).static
keyword – This keyword indicates that it does not require the class to be instantiated for it to be executed.void
keyword – The void keyword means the main method does not return any value.- main method name – The name of the method is always named main and cannot be changed to any other name because the JVM will not recognize it.
Below, I summarize for better visibility:
This is an introduction, and all these will be covered in more details in the other lessons.
4. Running Java main method
We will run the Java application using the command line but this can also be done using integrated development environment tools that make it much easier.Open the command line and change the directory to where the base package of our project is located and execute the following command.
D:\main-method>java ./src/com/javadevjournal/HelloWorldApp.java
The java command is used to initialize the Java virtual machine (JVM
) which starts an application by loading the specified class and calling that class’s main method. Before we use the java command, we should add Java to the system variables to avoid getting unrecognized command messages from our computer.
If the main class is located inside a package, we should ensure that we provide the fully qualified class name to avoid ClassNotFoundException
. The ClassNotFoundException
is an exception that is thrown when an application tries to load in a class through its string name, but no definition for the class with the specified name could be found. We can also provide the full path where the Java file is located, as we have done in the above example to run the application.
Though you should know these commands, I will suggest using some IDE (like IntelliJ/ Eclipse) to run your Java program.
5. Main method parameters
We use the array to pass information to the application when the system is running, and the string represents a command-line argument that we can pass to the application. Command-line arguments change the execution of a program without re-compiling it. For example, a library program might allow the user to specify that searching a book should return a specific number of books for each request using this command line argument.
D:\main-method>java ./src/com/javadevjournal/HelloWorldApp.java -limit
The command-line arguments are ignored if our application does not have any, but we should know the fact that such arguments exist. The following example uses a conditional statement to check the command-line argument passed to the main method and executes the block of code inside it if the condition is true.
package com.javadevjournal;
class HelloWorldApp {
public static void main(String[] cmdArguments) {
if (cmdArguments[0].equals("-limit")) {
System.out.println("10 ten books will be returned to the user");
}
}
}
Since the main method is expecting an array, we use the brackets to get a parameter at a specific position and compare it using the equals method, but all these will be discussed in another tutorial for better clarity.
Summary
In this tutorial, we have learned the purpose of the java main method, the meaning of the different components of the main method and how it is created, how to run the main method, and finally saw high to pass command-line arguments to the main method as an array of parameters.