-
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 namedMain
with amain
method. Themain
method is the entry point for Java applications and serves as the starting point for execution. - Within the
main
method, you use theSystem.out.println()
method to print the "Hello World" message to the console.
- You begin by creating a Java file named
-
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 runjavac Main.java
. If there are no errors in the code, the compiler will generate a bytecode file namedMain.class
.
- After saving
-
Running the Java Program:
- Once the code is successfully compiled, you use the
java
command to execute the program. You typejava Main
in the Command Prompt. - The Java Virtual Machine (JVM) loads the bytecode from
Main.class
and starts executing themain
method. - As a result, the "Hello World" message is printed to the console, indicating that the program has run successfully.
- Once the code is successfully compiled, you use the
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":
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:
The output should read:
Congratulations! You have written and executed your first Java program.
Practice Excercise Practice now