Java is a widely used programming language, known for its simplicity, portability, and robustness. Writing your first Java program is an exciting step in learning to code. Here’s a step-by-step guide:
Create a Java Program File
1. Open your text editor or IDE.
2. Create a new file named HelloWorld.java. The file name must match the class name (case-sensitive) to avoid compilation errors.
// This is a simple Java program
public class HelloWorld {
public static void main(String[] args) {
// Print a message to the console
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld: Defines a public class named HelloWorld.
public static void main(String[] args): The entry point of the program.
System.out.println(“Hello, World!”);: Prints “Hello, World!” to the console.
Compile the Program
1. Open a terminal or command prompt.
2. Navigate to the directory where you saved HelloWorld.java
3. Run the following command to compile the program:
javac HelloWorld.java
4. If there are no errors, this will generate a file named HelloWorld.class.
Run the Program
1. In the same directory, execute the following command:
java HelloWorld
2. You should see the output
Hello, World!