First Java Program - Hello World
Here's an example of a simple Java program that prints "Hello, World!" to the console:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Let's break down the program:
- The program starts with the declaration of a class named HelloWorld using the public access modifier. In Java, the code is organized into classes, and the public keyword indicates that the class is accessible from other classes.
- Inside the class, there is a main method, which serves as the entry point for the program. It has the public access modifier, indicating that it can be accessed from outside the class. The main method is where the program execution begins.
- The main method takes an array of strings (args) as a parameter. This parameter allows you to pass command-line arguments to the program, although we're not using it in this example.
- Within the main method, there is a single statement: System.out.println("Hello, World!");. This statement uses the System.out.println method to print the message "Hello, World!" to the console. The println method is part of the out object of the System class, and it adds a newline character after printing the message.
To run this program, follow these steps:
- Install Java Development Kit (JDK) on your computer if you haven't already.
- Save the above code in a file named HelloWorld.java, ensuring that the file has the .java extension.
- Open a command prompt or terminal and navigate to the directory where the HelloWorld.java file is saved.
- Compile the Java source file into bytecode by running the command: javac HelloWorld.java. This command invokes the Java compiler (javac) and generates the compiled bytecode file HelloWorld.class.
- Run the compiled program by executing the command: java HelloWorld. This command starts the Java Virtual Machine (JVM) and executes the compiled bytecode.
You should see the output Hello, World! displayed in the console.
Congratulations! You have successfully run your first Java program.