Java program structure
A basic Java program consists of several key components that follow a specific structure. Let’s break down the parts of a simple “Hello, World!” program to understand how they work together.
Here is the basic structure of a Java program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Class Definition
public class HelloWorld {
// code inside the class
}
public
: This is an access modifier that defines the visibility of the class.public
means the class can be accessed from any other class.class
: This keyword is used to define a class in Java. A class is a blueprint for creating objects and contains methods and fields.HelloWorld
: This is the name of the class. By convention, class names should start with an uppercase letter and follow camelCase for multi-word names.
In Java, everything must be written inside a class. The name of the class must match the name of the file (e.g., HelloWorld.java
).
The main
Method
public static void main(String[] args) {
// code to be executed
}
public
: Themain
method is public so it can be accessed by the JVM to run the program.static
: This keyword means the method belongs to the class rather than an instance of the class. It can be called without creating an object of the class.void
: This means that the method does not return any value.main
: This is the name of the method where the program execution begins. Themain
method is the entry point of any Java application.String[] args
: This is an array ofString
arguments that can be passed to the program from the command line. Even if no arguments are passed, this parameter must be included.
The System.out.println
Statement
System.out.println("Hello, World!");
System
: This is a built-in class in Java that provides access to system-related functionalities.out
: This is a static member of theSystem
class, representing the standard output stream (usually the console).println
: This is a method of theout
object that prints the given message to the console followed by a new line.This line prints the message
"Hello, World!"
to the console when the program is executed.