First Java Program

First Java Program | Hello World Example

The "Hello, World!" program is the simplest program you can write in any programming language, and it serves as a great introduction to Java. This program will print "Hello, World!" on the screen. Let's walk through the steps to create, compile, and run this basic Java program.


Step 1: Writing the Code

Open your text editor or Integrated Development Environment (IDE) and type the following code:

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

Explanation of the Code:

  • public class HelloWorld: This defines a class named HelloWorld. In Java, every program must have at least one class.

  • public static void main(String[] args): This is the main method, the entry point of any Java program. When you run the program, the code inside this method is executed.

  • System.out.println("Hello, World!");: This line prints "Hello, World!" to the console. System.out is used to print text, and println adds a new line after printing the text.

Step 2: Saving the Code

Save the file with the name HelloWorld.java. The filename must match the class name (in this case, HelloWorld) and have a .java extension.

Step 3: Compiling the Code

To compile your Java program, follow these steps:

  1. Open a command prompt or terminal.

  2. Navigate to the directory where you saved your HelloWorld.java file.

  3. Run the following command to compile the program:

    javac HelloWorld.java

If the code is correct, this command will create a file named HelloWorld.class. This file contains the bytecode, which can be executed by the Java Virtual Machine (JVM).

Step 4: Running the Code

After compiling the code, you can run the program using the following command:

java HelloWorld

This will execute the compiled bytecode, and you should see the following output on your screen:

Hello, World!

Conclusion

Congratulations! You've just written, compiled, and executed your first Java program. The "Hello, World!" example demonstrates the basic structure of a Java program, including classes, the main method, and printing output to the console. From here, you can start exploring more advanced concepts and building more complex programs.

For more examples and tutorials, visit codeswithpankaj.com.

Last updated