Your First Java Program: A Step-by-Step Guide


Writing your first Java program is an exciting milestone in your journey to becoming a proficient developer. In this section, we will walk you through the process of creating a simple Java program — the famous "Hello, World!" program. This program will introduce you to the structure of a Java program, basic syntax, and how to run it.

Step 1: Set Up Your Development Environment

Before you can start coding, you need to have the Java Development Kit (JDK) installed on your computer. Here’s how to set it up:

  1. Download the JDK:
    • Visit the official Java downloads page and download the latest JDK version.
    • Follow the installation instructions for your operating system (Windows, macOS, or Linux).
  2. Set Up an IDE:
    • Although you can use any text editor, we recommend using an IDE (Integrated Development Environment) for easier coding. IntelliJ IDEA, Eclipse, and NetBeans are popular IDEs for Java development.
    • For this guide, we’ll use IntelliJ IDEA, but the steps are similar in other IDEs.

Step 2: Create Your Java Project

  1. Open IntelliJ IDEA and click on "Create New Project."
  2. Select Java from the project type options and click Next.
  3. Choose a project name and set the location where your project will be saved.
  4. Click Finish to create your project.

Step 3: Write Your First Program

Now, it’s time to write your first Java program! Follow these steps:

  1. In the src folder, right-click and select New > Java Class.
  2. Name the class HelloWorld.

Now, type the following code into your HelloWorld.java file:

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

Explanation of the Code

  • public class HelloWorld: This is the declaration of a class named HelloWorld. In Java, all code must be written inside a class.
  • public static void main(String[] args): This is the main method. It’s the entry point of your Java application — when you run the program, the code inside this method is executed first.
  • System.out.println("Hello, World!");: This line of code prints the string "Hello, World!" to the console.

Step 4: Run Your Program

To run your Java program, follow these steps:

  1. In IntelliJ IDEA, click on the Run button (the green triangle) at the top of the screen.
  2. You can also run the program from the terminal by typing:
java HelloWorld

After running the program, you should see the following output:

Hello, World!

 

Congratulations!

You have successfully written and run your first Java program. This program may be simple, but it’s an important first step in learning Java. In the next steps, you can build on this knowledge by exploring Java’s syntax, data types, and control structures.

Keep coding and have fun exploring the world of Java!