Module: Introduction to Java

Hello World Program

Hello World Program in Java

This is the most basic program in any programming language, used to verify that your environment is set up correctly and you can compile and run code. Here's how to write a "Hello, World!" program in Java:

1. Create a Java File:

Create a new text file named HelloWorld.java. Important: The filename must match the class name (case-sensitive) and have the .java extension.

2. Write the Code:

Open HelloWorld.java in a text editor and paste the following code:

public class HelloWorld {

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

3. Explanation of the Code:

  • public class HelloWorld { ... }: This declares a class named HelloWorld. In Java, all code resides within classes. public means this class is accessible from anywhere.
  • public static void main(String[] args) { ... }: This is the main method. It's the entry point of your program – where execution begins.
    • public: Makes the method accessible from outside the class.
    • static: Allows the method to be called without creating an instance of the HelloWorld class.
    • void: Indicates that the method doesn't return any value.
    • String[] args: This is an array of strings that can be used to pass command-line arguments to your program. We don't use them in this simple example.
  • System.out.println("Hello, World!");: This line prints the text "Hello, World!" to the console (standard output).
    • System.out: Represents the standard output stream.
    • println(): A method of the System.out object that prints a line of text to the console and adds a newline character at the end.

4. Compile the Code:

Open a terminal or command prompt and navigate to the directory where you saved HelloWorld.java. Then, compile the code using the Java compiler (javac):

javac HelloWorld.java

If the compilation is successful, a new file named HelloWorld.class will be created in the same directory. This file contains the bytecode, which is the compiled version of your Java code.

5. Run the Code:

Now, run the compiled code using the Java Virtual Machine (java):

java HelloWorld

This will execute the main method in the HelloWorld class, and you should see the following output on your console:

Hello, World!

Summary:

  1. Create HelloWorld.java with the code above.
  2. Compile: javac HelloWorld.java
  3. Run: java HelloWorld
  4. Output: Hello, World!

Congratulations! You've successfully written and run your first Java program. This is the foundation for learning more complex Java concepts.