Recent in Sports

Breaking News

Writing Your First Java Program Java


If you’ve successfully set up your Java development environment with JDK and an IDE, you’re now ready to write your first Java program! In this tutorial, we’ll go step by step to create, compile, and run a simple Java program.

1. Understanding the Basic Structure of a Java Program

Every Java program follows a basic structure. Let’s take a look at a simple Java program:

java

// This is a simple Java program public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }

Breaking it Down:

  • public class HelloWorld – Every Java program starts with a class. Here, our class name is HelloWorld. The class name must match the filename (HelloWorld.java).
  • public static void main(String[] args) – This is the main method where the execution starts. Java always looks for this method to run the program.
  • System.out.println("Hello, World!"); – This prints "Hello, World!" to the console.

2. Writing and Running Your First Java Program

Step 1: Create a Java File

  1. Open your preferred IDE (such as IntelliJ IDEA or Eclipse).
  2. Create a new Java project.
  3. Inside the project, create a new Java file and name it HelloWorld.java.

Step 2: Write the Code

Copy and paste the above code into your HelloWorld.java file.

Step 3: Compile and Run the Program

Using an IDE:

  1. Click the Run button (usually a green triangle).
  2. You should see the output:
Hello, World!

Using the Command Line (Terminal):

  1. Open the terminal or command prompt.

  2. Navigate to the folder where your HelloWorld.java file is saved.

  3. Compile the program using:

    nginx

    javac HelloWorld.java
  4. Run the compiled file:

    nginx

    java HelloWorld
  5. You should see the output:


    Hello, World!

3. Common Errors and How to Fix Them

Error 1: "javac is not recognized"

Solution: Ensure that Java is installed correctly and added to the system PATH.

Error 2: "Main method not found"

Solution: Double-check that you’ve written public static void main(String[] args) correctly.

Error 3: "Class name mismatch"

Solution: Make sure your file name and class name are exactly the same (HelloWorld.java and HelloWorld).

No comments