1. Writing the Java Code:

    • You begin by creating a Java file named Main.java. In Java, every application starts with a class definition, and the class name must match the filename.
    • Inside Main.java, you define a class named Main with a main method. The main method is the entry point for Java applications and serves as the starting point for execution.
    • Within the main method, you use the System.out.println() method to print the "Hello World" message to the console.
  2. Compiling the Java Code:

    • After saving Main.java, you open the Command Prompt and navigate to the directory where the file is saved.
    • You use the javac command to compile the Java source code. In this case, you run javac Main.java. If there are no errors in the code, the compiler will generate a bytecode file named Main.class.
  3. Running the Java Program:

    • Once the code is successfully compiled, you use the java command to execute the program. You type java Main in the Command Prompt.
    • The Java Virtual Machine (JVM) loads the bytecode from Main.class and starts executing the main method.
    • As a result, the "Hello World" message is printed to the console, indicating that the program has run successfully.

Main.java


 

public class Main { public static void main(String[] args) { System.out.println("Hello World"); } }


 

Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on how to run the code above.

Save the code in Notepad as "Main.java". Open Command Prompt (cmd.exe), navigate to the directory where you saved your file, and type "javac Main.java":

C:\Users\Your Name>javac Main.java


 

This will compile your code. If there are no errors in the code, the command prompt will take you to the next line. Now, type "java Main" to run the file:
 

C:\Users\Your Name>java Main
 

The output should read:

Hello World
 

Congratulations! You have written and executed your first Java program.


 



Practice Excercise Practice now