foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Java
  • Understand the structure of a basic Java program
  • Write and run the classic 'Hello, World!' program
  • Learn about the main method and its components

Writing Your First Program

Time to write your first Java program. This is where theory meets practice. Don't worry if everything doesn't click immediately—that's completely normal.

The Classic "Hello, World!" Program

Let's start with the tradition that's welcomed millions into programming. The "Hello, World!" program is simple but teaches you the essential structure of every Java application.

Your First Java Program

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

This tiny program contains all the fundamental building blocks you need to understand. Let's break it down piece by piece.

Understanding the Program Structure

The Class Declaration

public class HelloWorld {

Every Java program starts with a class. Think of a class as a blueprint or a container that holds your program's code.

  • public means this class can be accessed from anywhere
  • class is the keyword that declares we're creating a class
  • HelloWorld is the name of our class (you could name it anything, but it should describe what the program does)
  • The opening curly brace { marks the beginning of the class

Important Rule: If your class is declared as public, the filename must exactly match the class name. So this code must be saved in a file called HelloWorld.java.

The Main Method - The Program's Entry Point

public static void main(String[] args) {

This is the main method—the starting point of every Java application. When you run a Java program, the Java Virtual Machine looks for this exact method and starts executing code from here.

Let's understand each part:

  • public: Accessible from anywhere
  • static: Can be called without creating an object
  • void: Doesn't return any value
  • main: The required name for the program's entry point
  • String[] args: Can accept command-line arguments (we'll cover this later)
  • {: Opening brace for the method body

The Action - Printing to Console

System.out.println("Hello, World!");

This line does the actual work—it prints text to the console.

  • System: A built-in Java class that provides system-related functionality
  • out: A static field that represents the standard output stream (usually your console)
  • println: A method that prints text and moves to the next line
  • "Hello, World!": The text we want to display (note the quotation marks)
  • ;: Every Java statement must end with a semicolon

Closing Braces

    }
}

Each opening brace { must have a matching closing brace }. The first } closes the main method, and the second } closes the class.

Let's Create This Program Step by Step

Step 1: Create the File

  1. Open your IDE (IntelliJ or VS Code)
  2. Create a new Java class file
  3. Name it HelloWorld.java
  4. Make sure the filename matches your class name exactly

Step 2: Write the Code

Type the complete program exactly as shown above. Pay attention to:

  • Capitalization (Java is case-sensitive!)
  • Spelling
  • Curly braces and parentheses
  • Semicolon at the end of the println statement

Step 3: Save and Compile

In most modern IDEs, compilation happens automatically when you save. But let's understand what's happening behind the scenes:

  1. Compilation: Your HelloWorld.java file gets compiled into HelloWorld.class (bytecode)
  2. Execution: The JVM runs the bytecode

If you're using the command line, you would use:

javac HelloWorld.java   # Compiles the program
java HelloWorld         # Runs the program

Step 4: Run Your Program

In your IDE:

  • Look for a "Run" button (usually a green triangle)
  • Or right-click in the code editor and select "Run"
  • Or use the keyboard shortcut (Ctrl+F5 in VS Code, Shift+F10 in IntelliJ)

You should see output like:

Hello, World!

Congratulations! You've just written and executed your first Java program!

Understanding System.out.println() vs System.out.print()

Java gives you two main ways to output text:

println() - Print with New Line

System.out.println("Hello");
System.out.println("World");

Output:

Hello
World

print() - Print Without New Line

System.out.print("Hello ");
System.out.print("World");

Output:

Hello World

The println method adds a newline character after printing, while print does not.

Common Mistakes and How to Fix Them

Mistake 1: Missing Semicolon

System.out.println("Hello, World!")  // ERROR: missing semicolon

Fix: Add the semicolon at the end of the statement.

Mistake 2: Wrong Filename

// File is named helloWorld.java but class is:
public class HelloWorld {  // ERROR: filename doesn't match class name

Fix: Rename the file to HelloWorld.java (match case exactly).

Mistake 3: Misspelled Method Name

public static void main(String[] args) {
    System.out.println("Hello, World!");  // ERROR: wrong method name
}

Fix: Change println to println.

Mistake 4: Missing or Extra Braces

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    // ERROR: missing closing brace for class

Fix: Ensure every opening brace { has a matching closing brace }.

Mistake 5: Wrong Main Method Signature

public static void main(String args) {  // ERROR: missing brackets
    System.out.println("Hello, World!");
}

Fix: Use String[] args not String args.

Let's Experiment: Customizing Your Program

Now that you have the basic program working, try making these changes:

Change the Message

System.out.println("Welcome to Java programming!");

Print Multiple Lines

System.out.println("Line 1");
System.out.println("Line 2");
System.out.println("Line 3");

Combine print() and println()

System.out.print("This ");
System.out.print("will ");
System.out.print("all ");
System.out.println("be on one line.");
System.out.println("This is on a new line.");

Understanding Java's Case Sensitivity

Java pays attention to uppercase and lowercase letters. These are all different:

  • HelloWorld ≠ helloworld ≠ HELLOWORLD
  • System ≠ system
  • println ≠ Println

Always use the exact capitalization shown in the examples.

Adding Comments to Your Code

Comments help explain what your code does. They're ignored by the compiler but are invaluable for humans.

Single-line Comments

// This is a single-line comment
System.out.println("Hello, World!");  // Comment after code

Multi-line Comments

/*
 This is a multi-line comment.
 It can span multiple lines.
 Useful for longer explanations.
*/
System.out.println("Hello, World!");

The Complete Process: From Code to Execution

Let's review what happens when you write and run a Java program:

  1. Write: You create a .java file with your code
  2. Compile: The javac compiler converts your code to bytecode (.class file)
  3. Execute: The JVM reads the bytecode and runs your program
  4. Output: Your program produces results (like text on the screen)
HelloWorld.java → javac → HelloWorld.class → java → "Hello, World!"
     ^               ^           ^               ^          ^
   Your code     Compiler    Bytecode       JVM        Output

Best Practices for Beginners

1. Consistent Indentation

Use consistent spacing (usually 4 spaces or a tab) to make your code readable:

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

2. Descriptive Names

Use names that describe what your code does:

// Good:
public class GreetingProgram

// Less clear:
public class Program1

3. Save Often

Get in the habit of saving your files frequently (Ctrl+S).

4. Test Small Changes

Make one small change at a time and test it. This makes finding errors easier.

Troubleshooting Common Issues

"Error: Could not find or load main class"

  • Check that your class has the exact same name as your filename
  • Make sure you're in the right directory when running the program

"Error: Main method not found"

  • Verify your main method signature is exactly: public static void main(String[] args)

Program runs but nothing happens

  • Check that you have a System.out.println() statement
  • Make sure you're looking at the correct output console

Beyond "Hello, World!"

Now that you've mastered the basics, you can start experimenting:

Try Different Messages

System.out.println("My name is [Your Name]");
System.out.println("I'm learning Java!");

Create Multiple Classes

Try creating a second program in a new file:

public class Greeting {
    public static void main(String[] args) {
        System.out.println("Nice to meet you!");
    }
}

Key Takeaways

  • Every Java program needs a class and a main method
  • The filename must match the public class name
  • System.out.println() prints text to the console
  • Every statement ends with a semicolon
  • Java is case-sensitive
  • Use comments to explain your code
  • Compile-time errors prevent your program from running
  • Runtime errors happen while your program is executing

What's Next?

You've taken a huge step—you're now a Java programmer! In the next subTopicLesson, we'll dive deeper into Java's basic syntax, including variables, data types, and how to make your programs more interactive.

Remember: Every expert was once a beginner who wrote their first "Hello, World!" program. You're on your way!

Practice Exercise

Before moving on, try these subTopicExercises:

  1. Modify the program to display your name
  2. Create a program that prints a short poem on multiple lines
  3. Write a program that uses both print() and println() to create a specific output pattern
  4. Create a new class called Introduction that prints a brief self-introduction

The more you practice, the more comfortable you'll become with the basic structure of Java programs. Happy coding!

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service