LearnContact
Lesson 545 min read

First Java Program

Write, compile, and run your first Java program. Learn how source files, classes, the main method, statements, comments, compilation, bytecode, the JVM, and program execution work together.

Introduction

Now that Java is installed and configured, it is time to write your first complete Java program. This lesson will take you through every part of the program, from creating the source file to seeing the final output.

A first program may contain only a few lines of code, but those lines introduce several fundamental Java concepts: classes, methods, statements, strings, compilation, bytecode, the JVM, and program execution.

Instead of only copying a Hello World program, you will understand what every important part means and how Java transforms your source code into a running application.

First Program Journey
WRITE SOURCE CODE

        │
        ▼

SAVE AS .java FILE

        │
        ▼

COMPILE WITH javac

        │
        ▼

GENERATE .class FILE

        │
        ▼

RUN WITH java

        │
        ▼

JVM EXECUTES BYTECODE

        │
        ▼

OUTPUT APPEARS
What You Will Learn
  • How to create your first Java source file.
  • How to write a complete Java program.
  • What a class declaration means.
  • Why the class name matters.
  • What curly braces represent.
  • What the main method is.
  • Why main is the program entry point.
  • What public means in the main method.
  • What static means in the main method.
  • What void means in the main method.
  • Why the method is named main.
  • What String[] args represents.
  • How System.out.println() works.
  • What System represents.
  • What out represents.
  • What println() does.
  • What a string literal is.
  • Why statements use semicolons.
  • How to compile a Java program.
  • What compilation produces.
  • What a .class file contains.
  • How to run a Java program.
  • How source code becomes output.
  • Why Java is case-sensitive.
  • How Java filenames and class names are related.
  • Why indentation improves readability.
  • How whitespace affects Java code.
  • How to write multiple statements.
  • The difference between print() and println().
  • How to print text, numbers, and calculations.
  • How escape sequences work.
  • How Java comments work.
  • How command-line arguments work.
  • The difference between compile-time, runtime, and logical errors.
  • How to solve common first-program errors.

Your First Java Program

The traditional first program in almost every programming language displays a simple message. In Java, we will begin by printing Hello, World! to the console.

HelloWorld.java
public class HelloWorld {

    public static void main(String[] args) {

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

    }

}
Output
Hello, World!
Your First Goal
  • Create the source file.
  • Write the program.
  • Compile the source code.
  • Run the compiled program.
  • See Hello, World! in the terminal.

Create a Project Folder

Create a separate folder for your first Java program. Keeping source files organized makes compilation and execution easier.

Example Folder Structure
JavaCourse

└── FirstProgram

        └── HelloWorld.java

Open your terminal inside the folder where the Java source file will be stored.

Working Directory
CURRENT DIRECTORY

FirstProgram

        │
        ▼

CONTAINS

HelloWorld.java
Why the Current Directory Matters
  • The compiler must be able to find the source file.
  • The Java launcher must be able to find the compiled class.
  • Many beginner errors happen because commands are executed from the wrong directory.

Create the Source File

Create a new file named HelloWorld.java. Java source files use the .java extension.

Correct Filename
HelloWorld.java
Incorrect Filenames
HelloWorld.txt

HelloWorld.java.txt

helloworld.java

Hello.java
Check File Extensions
  • Some operating systems hide known file extensions.
  • A file that appears as HelloWorld.java may actually be HelloWorld.java.txt.
  • Make sure the real filename ends with .java.

Write the Complete Program

HelloWorld.java
public class HelloWorld {

    public static void main(String[] args) {

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

    }

}

Save the file before compiling it. The compiler reads the saved contents of the source file.

Program Parts
public class HelloWorld

        │
        ▼

CLASS DECLARATION


public static void main(String[] args)

        │
        ▼

MAIN METHOD


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

        │
        ▼

OUTPUT STATEMENT

Understanding the Program

The first program contains several pieces of Java syntax. Each part has a specific role.

Program Breakdown
public class HelloWorld {
    //      └──────── Class Name

    public static void main(String[] args) {
    //                  └── Main Method

        System.out.println("Hello, World!");
        //                 └── Output Statement

    }

}
High-Level Structure
CLASS

└── METHOD

        └── STATEMENT

At this stage, focus on recognizing the structure. Later lessons will explain classes, methods, objects, access modifiers, arrays, and strings in greater depth.

The Class Declaration

Class Declaration
public class HelloWorld {

}

Java programs are organized using classes. The class keyword declares a class, and HelloWorld is the name of this class.

Class Declaration Parts
public class HelloWorld
  │      │       │
  │      │       └── Class Name
  │      │
  │      └────────── Class Keyword
  │
  └───────────────── Access Modifier
For Now
  • Think of a class as a container for program code.
  • The main method is written inside the class.
  • Later lessons will explain classes in detail.

The Class Name

Class Name
HelloWorld

HelloWorld is an identifier chosen as the class name. Java naming conventions usually begin class names with an uppercase letter and use PascalCase for multiple words.

Class Naming Examples
GOOD CONVENTION

HelloWorld

Student

BankAccount

EmployeeManagementSystem


POOR CONVENTION

helloworld

student_data

BANKACCOUNT
Class Naming Convention
  • Begin each word with an uppercase letter.
  • Do not normally use spaces.
  • Use meaningful names.
  • Use PascalCase for multiple words.

Curly Braces

Curly Braces
{

}

Curly braces define blocks of code. An opening brace begins a block, and a closing brace ends it.

Nested Blocks
public class HelloWorld {          // Class block starts

    public static void main(String[] args) {  // Method block starts

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

    }                                        // Method block ends

}                                            // Class block ends
Block Structure
CLASS BLOCK

{

    METHOD BLOCK

    {

        STATEMENTS

    }

}
Braces Must Match
  • Every opening brace should have a matching closing brace.
  • Missing braces can cause compilation errors.
  • Indentation helps you see which braces belong together.

The main Method

main Method
public static void main(String[] args) {

}

The main method is the traditional entry point of a standalone Java application. When you run the class, the Java launcher looks for an appropriate main method to begin program execution.

main Method Structure
public static void main(String[] args)
  │      │      │     │        │
  │      │      │     │        └── Parameter Name
  │      │      │     │
  │      │      │     └─────────── String Array Parameter
  │      │      │
  │      │      └───────────────── Method Name
  │      │
  │      └──────────────────────── Return Type
  │
  └─────────────────────────────── Modifiers

The public Keyword

public
public static void main(String[] args)

The public keyword is an access modifier. In the traditional main method declaration, it allows the Java launcher to access the method when starting the application.

Do Not Memorize Access Control Yet
  • You will learn access modifiers in later lessons.
  • For now, recognize public as part of the standard main method declaration.

The static Keyword

static
public static void main(String[] args)

The static keyword allows the main method to belong to the class itself rather than requiring an object of the class to be created before the method can be called.

Why static Matters
PROGRAM STARTS

        │
        ▼

NO HelloWorld OBJECT EXISTS YET

        │
        ▼

main IS static

        │
        ▼

JVM CAN START EXECUTION
Later Topic
  • Static members will be explained in detail later.
  • For now, remember that the traditional main method is static.

The void Keyword

void
public static void main(String[] args)

The void keyword is the return type of the main method. It means the method does not return a value.

Return Concept
METHOD EXECUTES

        │
        ▼

PERFORMS STATEMENTS

        │
        ▼

RETURNS NO VALUE

        │
        ▼

void

The main Method Name

Method Name
main

The method name is main. The Java launcher recognizes this method name as part of the traditional application entry-point signature.

Java is Case-Sensitive
  • main is correct.
  • Main is different.
  • MAIN is different.
  • Changing capitalization changes the identifier.

Understanding String[] args

Parameter
String[] args

String[] args is the parameter of the main method. It allows the program to receive command-line arguments as an array of strings.

Parameter Breakdown
String[] args
   │       │
   │       └── Variable Name
   │
   └────────── Array of Strings

The name args is conventional but not mandatory. The parameter can use another valid variable name.

Also Valid
public static void main(String[] values) {

}
Convention
  • Most Java programs use the name args.
  • Following common conventions makes code easier for other developers to understand.

The Program Entry Point

An entry point is the location where program execution begins. In the traditional Java application structure, execution begins from the main method.

Execution Start
RUN

java HelloWorld

        │
        ▼

JAVA LAUNCHER LOADS CLASS

        │
        ▼

LOCATES main METHOD

        │
        ▼

STARTS EXECUTING STATEMENTS

        │
        ▼

PROGRAM ENDS
Execution Begins Here
public class HelloWorld {

    public static void main(String[] args) {

        // Execution starts inside this method

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

    }

}

Understanding System.out.println()

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

This statement displays text in the console and then moves the cursor to a new line.

Statement Breakdown
System.out.println("Hello, World!");
  │     │      │          │
  │     │      │          └── Semicolon
  │     │      │
  │     │      └───────────── Method Call
  │     │
  │     └──────────────────── Output Stream
  │
  └────────────────────────── System Class

The System Class

System
System

System is a class provided by Java. It provides access to system-related resources and utilities.

For This Lesson
  • You do not need to understand the complete System class yet.
  • Recognize that System is the class used at the beginning of the output statement.

The out Object

out
System.out

out represents the standard output stream. It is commonly connected to the terminal or console where program output is displayed.

Standard Output
JAVA PROGRAM

        │
        ▼

System.out

        │
        ▼

STANDARD OUTPUT

        │
        ▼

TERMINAL / CONSOLE

The println Method

println()
println("Hello, World!")

println is a method used to print a value and then move to the next line.

Multiple println Statements
System.out.println("Java");
System.out.println("Programming");
System.out.println("Course");
Output
Java
Programming
Course

String Literal

String Literal
"Hello, World!"

Text written directly inside double quotation marks is called a string literal.

String Literal Examples
"Java"

"Hello, World!"

"My name is Alex"

"12345"
Double Quotes Matter
  • Text literals use double quotation marks.
  • Removing the quotation marks changes how Java interprets the content.
  • Opening and closing quotation marks must match.

The Semicolon

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

Many Java statements end with a semicolon. The semicolon marks the end of the statement.

Statements
System.out.println("First");
System.out.println("Second");
System.out.println("Third");
Missing Semicolon
  • A missing required semicolon causes a compilation error.
  • The compiler usually reports the location near the problem.
  • The reported location may not always be the exact character where the mistake began.

Compile the Program

Open a terminal in the folder containing HelloWorld.java and run the Java compiler.

Compile
javac HelloWorld.java
Before Compilation
FirstProgram

└── HelloWorld.java
After Successful Compilation
FirstProgram

├── HelloWorld.java
└── HelloWorld.class
Successful Compilation
  • The command may display no message.
  • A HelloWorld.class file should be created.
  • No compiler error should appear.

What Compilation Does

The Java compiler reads the source code, checks it for compilation errors, and translates valid code into bytecode.

Compilation Process
HelloWorld.java

        │
        ▼

javac COMPILER

        │
        ├── Reads Source Code
        │
        ├── Checks Syntax
        │
        ├── Checks Language Rules
        │
        └── Generates Bytecode
        │
        ▼

HelloWorld.class

If the source code contains compilation errors, the compiler reports them and the expected class file may not be generated.

The .class File

The .class file contains Java bytecode generated by the compiler. It is not ordinary Java source code.

Source and Bytecode
HelloWorld.java

CREATED BY:
Developer

CONTAINS:
Java Source Code


HelloWorld.class

CREATED BY:
javac Compiler

CONTAINS:
Java Bytecode
Do Not Edit .class Files as Source Code
  • Write and edit the .java source file.
  • Compile the source file again after changes.
  • The compiler regenerates the .class file.

Run the Program

After successful compilation, run the program using the java command followed by the class name.

Run
java HelloWorld
Output
Hello, World!
Correct Execution Command
  • Use: java HelloWorld
  • Do not use: java HelloWorld.class
  • The traditional launcher command uses the class name.

Complete Execution Flow

Execution Flow
STEP 1

WRITE

HelloWorld.java

        │
        ▼

STEP 2

COMPILE

javac HelloWorld.java

        │
        ▼

STEP 3

GENERATE

HelloWorld.class

        │
        ▼

STEP 4

RUN

java HelloWorld

        │
        ▼

STEP 5

JVM EXECUTES BYTECODE

        │
        ▼

STEP 6

OUTPUT

Hello, World!

From Source Code to Output

Complete Java Program Lifecycle
DEVELOPER

        │
        ▼

WRITES SOURCE CODE

        │
        ▼

HelloWorld.java

        │
        ▼

javac

        │
        ▼

BYTECODE

        │
        ▼

HelloWorld.class

        │
        ▼

java COMMAND

        │
        ▼

JVM STARTS

        │
        ▼

CLASS LOADED

        │
        ▼

main METHOD FOUND

        │
        ▼

STATEMENTS EXECUTED

        │
        ▼

System.out.println()

        │
        ▼

OUTPUT DISPLAYED

Java is Case-Sensitive

Java treats uppercase and lowercase letters as different characters.

Different Identifiers
HelloWorld

helloworld

HELLOWORLD

helloWorld


ALL ARE DIFFERENT
Correct
System.out.println("Hello");
Incorrect
system.out.println("Hello");
Check Capitalization Carefully
  • System is not system.
  • String is not string.
  • HelloWorld is not helloworld.
  • main is not Main.

Filename Rules

When a source file contains a public top-level class, the filename must match the public class name.

Correct Match
PUBLIC CLASS

HelloWorld

        │
        ▼

FILENAME

HelloWorld.java
Incorrect Match
PUBLIC CLASS

HelloWorld

        │
        ▼

FILENAME

Hello.java

        │
        ▼

COMPILATION ERROR

Class Name Rules

  • A class name is an identifier.
  • It cannot contain spaces.
  • It cannot begin with a digit.
  • It cannot be a reserved Java keyword.
  • It can contain letters, digits, underscores, and dollar signs, subject to identifier rules.
  • Class names conventionally use PascalCase.
  • Meaningful names are preferred.
Examples
VALID

HelloWorld

Student

BankAccount

Employee2


INVALID

2Employee

Bank Account

public

Indentation

Indentation means adding spaces before nested code to visually show the program structure.

Readable Code
public class HelloWorld {

    public static void main(String[] args) {

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

    }

}
Poorly Formatted Code
public class HelloWorld{
public static void main(String[] args){
System.out.println("Hello, World!");
}
}
Indentation Improves Readability
  • Indent code inside classes.
  • Indent code inside methods.
  • Use consistent spacing.
  • Let your editor or IDE format code when appropriate.

Whitespace

Whitespace includes spaces, tabs, and line breaks. Java often allows flexible whitespace between tokens, but whitespace cannot be inserted everywhere.

Both Can Compile
System.out.println("Hello");

System
    .
    out
    .
    println
    (
        "Hello"
    )
    ;
Readable Code Matters
  • Legal formatting is not always good formatting.
  • Use conventional formatting.
  • Do not make code unnecessarily difficult to read.

Writing Multiple Statements

Multiple Statements
public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello!");
        System.out.println("Welcome to Java.");
        System.out.println("This is my first program.");

    }

}
Output
Hello!
Welcome to Java.
This is my first program.

Statements inside the main method normally execute sequentially from top to bottom unless control-flow logic changes the order.

Sequential Execution
STATEMENT 1

        │
        ▼

STATEMENT 2

        │
        ▼

STATEMENT 3

        │
        ▼

PROGRAM CONTINUES

The print() method displays output without automatically moving to a new line afterward.

Using print()
System.out.print("Hello ");
System.out.print("Java");
System.out.print("!");
Output
Hello Java!

The println() Method

The println() method displays output and then moves to the next line.

Using println()
System.out.println("Hello");
System.out.println("Java");
System.out.println("!");
Output
Hello
Java
!
Comparison
print()

PRINTS VALUE
+
STAYS ON SAME LINE


println()

PRINTS VALUE
+
MOVES TO NEXT LINE

print()

Displays output without automatically adding a line break.

println()

Displays output and then adds a line break.

Printing Numbers

Numbers can be printed without quotation marks.

Printing Numbers
System.out.println(10);
System.out.println(25);
System.out.println(1000);
Output
10
25
1000
Text vs Number
  • "10" is a string literal.
  • 10 is a numeric literal.
  • They may look similar in output but represent different kinds of values.

Printing Calculations

Java can evaluate an expression before printing the result.

Calculations
System.out.println(10 + 5);
System.out.println(20 - 8);
System.out.println(6 * 4);
System.out.println(20 / 5);
Output
15
12
24
4
Execution
EXPRESSION

10 + 5

        │
        ▼

EVALUATION

15

        │
        ▼

PRINT

15

Printing Text and Numbers

Text with Number
System.out.println("Age: " + 25);
Output
Age: 25
Important Difference
System.out.println(10 + 20);
System.out.println("10" + "20");
System.out.println("Result: " + 10 + 20);
System.out.println("Result: " + (10 + 20));
Output
30
1020
Result: 1020
Result: 30
Order Matters
  • Numeric addition can produce a mathematical result.
  • String concatenation joins values as text.
  • Parentheses can control which expression is evaluated first.
  • Operators will be explained in detail in a later lesson.

Escape Sequences

Escape sequences are special character combinations beginning with a backslash. They allow certain special characters and formatting to be represented inside string literals.

Common Escape Sequences
\n    New Line

\t    Horizontal Tab

\"    Double Quote

\'    Single Quote

\\    Backslash

\b    Backspace

\r    Carriage Return

New Line Escape Sequence

New Line
System.out.println("Java\nProgramming\nCourse");
Output
Java
Programming
Course

Tab Escape Sequence

Tab
System.out.println("Name\tAge");
System.out.println("Alex\t25");
Output
Name    Age
Alex    25

Printing Quotes and Backslashes

Double Quotes
System.out.println("He said, \"Hello!\"");
Output
He said, "Hello!"
Backslash
System.out.println("C:\\Java\\Projects");
Output
C:\Java\Projects

Comments

Comments are notes written inside source code for developers. The compiler ignores comment content as executable program instructions.

// Single-Line

Used for a comment that continues to the end of the current line.

/* Multi-Line */

Used for comments that can span multiple lines.

/** Documentation */

Used for documentation comments that can be processed by documentation tools.

Single-Line Comments

Single-Line Comments
public class HelloWorld {

    public static void main(String[] args) {

        // Print a welcome message
        System.out.println("Welcome to Java!");

    }

}
End-of-Line Comment
System.out.println("Hello"); // Display Hello

Multi-Line Comments

Multi-Line Comment
/*
    This is a multi-line comment.

    It can contain multiple lines.
*/

System.out.println("Hello");
Use Comments Carefully
  • Comments should explain useful information.
  • Do not comment every obvious statement.
  • Keep comments accurate when code changes.

Documentation Comments

Documentation Comment
/**
 * Displays a welcome message.
 */
public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Welcome!");

    }

}

Documentation comments begin with /** and can be used by documentation tools such as Javadoc.

Later Use
  • Documentation comments are especially useful for classes, methods, and APIs.
  • You will understand their value more clearly after learning methods and classes.

Command-Line Arguments

Command-line arguments are values supplied after the class name when starting a Java application.

Run with Argument
java HelloWorld Alex
Argument Flow
COMMAND

java HelloWorld Alex

        │
        ▼

ARGUMENT

Alex

        │
        ▼

String[] args

        │
        ▼

args[0]

Using args

HelloWorld.java
public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello, " + args[0] + "!");

    }

}
Compile
javac HelloWorld.java
Run
java HelloWorld Alex
Output
Hello, Alex!
Argument Required
  • This example expects at least one command-line argument.
  • Running it without an argument causes a runtime error.
  • Arrays and error handling will be covered later.

Multiple Command-Line Arguments

ArgumentsExample.java
public class ArgumentsExample {

    public static void main(String[] args) {

        System.out.println("First: " + args[0]);
        System.out.println("Second: " + args[1]);
        System.out.println("Third: " + args[2]);

    }

}
Run
java ArgumentsExample Java Is Powerful
Output
First: Java
Second: Is
Third: Powerful
Argument Indexes
Java        Is        Powerful
 │           │           │
 ▼           ▼           ▼
args[0]     args[1]     args[2]

Command-Line Arguments are Strings

Values received through String[] args are strings, even when they look like numbers.

Command
java Example 10 20
Inside args
args[0] = "10"

args[1] = "20"
Important
  • The arguments are initially strings.
  • Numeric text must be converted before normal numeric calculations.
  • Type conversion will be covered in later lessons.

Can You Run a Java Source File Without Traditional Compilation?

Modern Java versions support launching a single source file directly. In this mode, the source file can be provided to the java command.

Source-File Mode
java HelloWorld.java

The Java launcher handles the required compilation steps for the source-file launch process.

Learn the Traditional Process First
  • Understand javac HelloWorld.java.
  • Understand the generated HelloWorld.class file.
  • Understand java HelloWorld.
  • The traditional process clearly teaches compilation and execution.

Traditional Compilation vs Source-File Mode

Traditional Process
SOURCE FILE

HelloWorld.java

        │
        ▼

javac HelloWorld.java

        │
        ▼

HelloWorld.class

        │
        ▼

java HelloWorld

        │
        ▼

OUTPUT
Source-File Mode
SOURCE FILE

HelloWorld.java

        │
        ▼

java HelloWorld.java

        │
        ▼

LAUNCHER HANDLES SOURCE EXECUTION

        │
        ▼

OUTPUT
Course Approach
  • This course will emphasize the traditional compile-and-run model first.
  • It gives you a clearer understanding of source code, bytecode, class files, and JVM execution.

Compile-Time Errors

Compile-time errors are detected while the compiler is processing source code.

Example
public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello")

    }

}

The output statement is missing a semicolon, so the compiler reports an error.

Compile-Time Error Flow
SOURCE CODE

        │
        ▼

javac

        │
        ▼

ERROR FOUND

        │
        ▼

ERROR MESSAGE

        │
        ▼

FIX SOURCE CODE

        │
        ▼

COMPILE AGAIN

Runtime Errors

Runtime errors occur while a program is executing. The source code may compile successfully, but a problem happens during execution.

Example
public class HelloWorld {

    public static void main(String[] args) {

        System.out.println(args[0]);

    }

}

The program can compile successfully, but running it without an argument causes an error because args[0] does not exist.

Runtime Error Flow
SOURCE CODE

        │
        ▼

COMPILES SUCCESSFULLY

        │
        ▼

PROGRAM STARTS

        │
        ▼

PROBLEM OCCURS DURING EXECUTION

        │
        ▼

RUNTIME ERROR

Logical Errors

A logical error occurs when the program runs but produces an incorrect result because the program logic is wrong.

Logical Error Example
public class Calculation {

    public static void main(String[] args) {

        System.out.println("10 + 20 = " + 10 + 20);

    }

}
Unexpected Output
10 + 20 = 1020
Corrected
System.out.println("10 + 20 = " + (10 + 20));
Correct Output
10 + 20 = 30

Common First Program Errors

Common Error Categories
FIRST PROGRAM ERRORS

├── Wrong Filename
├── Wrong Class Name
├── Missing Semicolon
├── Incorrect Capitalization
├── Missing Quote
├── Missing Brace
├── Wrong Directory
├── Wrong Compile Command
├── Wrong Run Command
└── Old .class File

Error: Wrong Filename

Source Code
public class HelloWorld {

}
Wrong Filename
Hello.java
Correct Filename
HelloWorld.java
Solution
  • Check the public class name.
  • Rename the source file to match it exactly.
  • Remember that capitalization matters.

Error: Missing Semicolon

Incorrect
System.out.println("Hello")
Correct
System.out.println("Hello");
Solution
  • Check the statement reported by the compiler.
  • Check the previous line as well.
  • Add the missing semicolon where required.

Error: Incorrect Capitalization

Incorrect
system.out.println("Hello");
Correct
System.out.println("Hello");
Remember
  • Java is case-sensitive.
  • System begins with uppercase S.
  • String begins with uppercase S.
  • main uses lowercase letters.

Error: Unclosed String Literal

Incorrect
System.out.println("Hello);
Correct
System.out.println("Hello");
Solution
  • Check the opening double quote.
  • Check the closing double quote.
  • Escape quotes that should appear inside the string.

Error: Missing Brace

Incorrect
public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello");

}

The method block is closed, but the class block is not closed.

Brace Check
OPENING BRACES

{

{


CLOSING BRACES

}


MISSING

}

Error: Could Not Find or Load Main Class

This error can occur when the Java launcher cannot locate the requested class in the expected class path and directory context.

Possible Causes
POSSIBLE CAUSES

├── Class Was Not Compiled
├── Wrong Class Name Used
├── Wrong Current Directory
├── Package Structure Mismatch
└── Classpath Problem
Basic Checks
  • Confirm that HelloWorld.class exists.
  • Confirm that you are in the correct directory.
  • Run java HelloWorld with the exact class name.
  • Do not add .class to the class name.

Error: Running Commands from the Wrong Directory

Correct Situation
CURRENT DIRECTORY

FirstProgram

        │
        ▼

FILES

HelloWorld.java
HelloWorld.class
Commands
javac HelloWorld.java

java HelloWorld
Check Your Location
  • List the files in the current directory.
  • Confirm the source file is present before compiling.
  • Confirm the class file is present before traditional execution.

First Program Variations

Personal Introduction
public class Introduction {

    public static void main(String[] args) {

        System.out.println("Hello!");
        System.out.println("My name is Alex.");
        System.out.println("I am learning Java.");

    }

}
Simple Calculation
public class Calculation {

    public static void main(String[] args) {

        System.out.println("10 + 20 = " + (10 + 20));
        System.out.println("10 * 20 = " + (10 * 20));

    }

}
Simple Pattern
public class Pattern {

    public static void main(String[] args) {

        System.out.println("*");
        System.out.println("**");
        System.out.println("***");
        System.out.println("****");
        System.out.println("*****");

    }

}

Best Practices for Your First Programs

  • Use meaningful class names.
  • Follow Java naming conventions.
  • Match the public class name and filename.
  • Use consistent indentation.
  • Keep opening and closing braces easy to identify.
  • Save the source file before compiling.
  • Read compiler errors carefully.
  • Fix one error at a time.
  • Compile again after changing the source code.
  • Run the newly compiled class.
  • Use comments only when they add useful information.
  • Practice writing programs manually instead of only copying code.
  • Use the command line enough to understand compilation and execution.
  • Do not depend entirely on an IDE Run button.
  • Experiment with print(), println(), strings, numbers, and calculations.

First Program Execution Checklist

Checklist
FIRST JAVA PROGRAM CHECKLIST

[ ] Java is installed

[ ] java -version works

[ ] javac -version works

[ ] Project folder created

[ ] HelloWorld.java created

[ ] File extension is correct

[ ] Public class is HelloWorld

[ ] Filename is HelloWorld.java

[ ] main method is present

[ ] Output statement is present

[ ] Quotes are closed

[ ] Semicolon is present

[ ] Braces are balanced

[ ] Source file is saved

[ ] Terminal is in correct directory

[ ] javac HelloWorld.java succeeds

[ ] HelloWorld.class is created

[ ] java HelloWorld runs

[ ] Expected output appears

Common Misconceptions

Avoid These Misconceptions
  • A Java source file is not the same as a class file.
  • .java files contain source code.
  • .class files contain compiled bytecode.
  • The developer normally edits the .java file.
  • The compiler generates the .class file.
  • javac compiles Java source code.
  • java launches Java applications.
  • The traditional compile command includes the .java extension.
  • The traditional run command uses the class name.
  • java HelloWorld.class is not the normal traditional run command.
  • Java is case-sensitive.
  • System and system are different.
  • String and string are different.
  • main and Main are different.
  • The public class name and filename must match.
  • A file named HelloWorld.java.txt is not a Java source file with the expected extension.
  • The main method is traditionally the program entry point.
  • public, static, void, and main each have different meanings.
  • String[] args is not random syntax.
  • Command-line arguments are received through the main method parameter.
  • Command-line arguments are strings initially.
  • System.out.println() is made of multiple parts.
  • println() prints a value and adds a line break.
  • print() does not automatically add a line break.
  • A semicolon commonly ends a Java statement.
  • Curly braces define code blocks.
  • Indentation improves readability even when some whitespace does not change program meaning.
  • Comments are not executed as normal program statements.
  • Compilation errors happen before successful execution.
  • Runtime errors happen while the program is running.
  • Logical errors can produce incorrect output without stopping the program.
  • Successful compilation may produce no terminal message.
  • Changing source code does not automatically update an old .class file in the traditional process.
  • You must compile again after changing source code.
  • Running from the wrong directory can prevent Java from finding the class.
  • An IDE Run button does not remove the underlying compilation and execution concepts.
  • Modern Java can support source-file launch mode, but understanding traditional compilation remains important.
  • String concatenation and numeric addition can produce different results.
  • Parentheses can change expression evaluation.
  • Escape sequences are used to represent special characters inside strings.

Practice Exercises

Exercise 1: Hello Java
  • Create a class named HelloJava.
  • Print: Hello, Java!
  • Compile the program.
  • Run the program.
Exercise 2: Personal Introduction
  • Create a class named AboutMe.
  • Print your name.
  • Print your city.
  • Print the technology you are learning.
  • Use separate println() statements.
Exercise 3: Same-Line Output
  • Use three print() statements.
  • Display three words on the same line.
  • Add spaces manually where required.
Exercise 4: Calculations
  • Print the result of 50 + 25.
  • Print the result of 50 - 25.
  • Print the result of 50 * 25.
  • Print the result of 50 / 25.
Exercise 5: Escape Sequences
  • Print three lines using one println() statement and \n.
  • Print tab-separated values using \t.
  • Print a sentence containing double quotation marks.
  • Print a Windows-style path containing backslashes.
Exercise 6: Command-Line Argument
  • Create a program that reads args[0].
  • Display a welcome message containing that value.
  • Run the program with your name as an argument.
Exercise 7: Debug the Program
  • Remove a semicolon and observe the compiler error.
  • Change System to system and observe the error.
  • Remove a closing brace and observe the error.
  • Restore the correct code after each experiment.

Common Interview Questions

What is the traditional entry point of a Java application?

The traditional entry point is the main method with the appropriate signature.

What does javac do?

javac compiles Java source code into Java bytecode.

What does the java command do?

The java command launches a Java application and starts the runtime process required to execute it.

What is a .java file?

A .java file is a source file containing Java source code.

What is a .class file?

A .class file contains Java bytecode generated by the compiler.

Why is the main method public?

In the traditional main method declaration, public allows the Java launcher to access the method.

Why is the main method static?

It allows the method to be invoked without first creating an object of the class.

What does void mean in the main method?

It means the method does not return a value.

What is String[] args?

It is an array of strings used to receive command-line arguments.

What is System.out.println()?

It is commonly used to print a value to standard output and then add a line break.

What is the difference between print() and println()?

print() does not automatically add a line break, while println() does.

Is Java case-sensitive?

Yes. Uppercase and lowercase letters are treated as different.

Why must the filename match the public class name?

A public top-level class must be declared in a source file with the corresponding class name.

What happens after javac successfully compiles a source file?

One or more .class files containing bytecode are generated.

What is a compile-time error?

It is an error detected during compilation.

What is a runtime error?

It is an error that occurs while the program is executing.

What is a logical error?

It is a mistake in program logic that causes incorrect results even though the program may compile and run.

What is a string literal?

It is text written directly inside double quotation marks.

Why are semicolons used?

Semicolons commonly mark the end of Java statements.

What do curly braces represent?

They define blocks of code such as class and method bodies.

Frequently Asked Questions

Why is Hello World usually the first program?

It provides a simple way to verify that the development environment works while introducing basic program structure and output.

Can I change HelloWorld to another class name?

Yes. Use a valid class name and make sure the filename matches the public class name.

Can I write Java without an IDE?

Yes. A text editor, JDK, and terminal are enough to write, compile, and run Java programs.

Why does javac show no output?

Successful compilation often produces no terminal message. Check whether the expected .class file was generated.

Why does my old output still appear after changing the code?

In the traditional process, you may be running an old .class file. Save the source file and compile it again.

Why should I not type java HelloWorld.class?

The traditional java launcher command uses the class name rather than the class filename.

Can I use another name instead of args?

Yes. args is a conventional parameter name, but another valid identifier can be used.

Can I remove String[] args?

For the traditional main method signature taught here, keep the command-line argument parameter.

Can main use String args[] instead?

Yes. Java permits array brackets after the type or variable name, though String[] args is the common convention.

Can I write everything on one line?

Some simple programs can be written on one line, but conventional formatting is much easier to read and maintain.

Does indentation affect Java execution?

Indentation generally does not define blocks in Java because braces do, but proper indentation is essential for readability.

Why does text use double quotes?

Double quotation marks define string literals in Java.

Can println() print numbers?

Yes. It can print numbers, strings, expressions, and many other values.

Why does "10" + "20" produce 1020?

Both values are strings, so the plus operator joins them as text.

Why does "Result: " + 10 + 20 produce Result: 1020?

Evaluation proceeds from left to right in this expression, and after string concatenation begins, the later numbers are joined as text.

How do I print 30 instead?

Use parentheses around the numeric calculation: "Result: " + (10 + 20).

Can Java run a source file directly?

Modern Java versions support source-file launch mode for suitable single-file programs, but the traditional compile-and-run process remains important to understand.

Why should I learn javac if an IDE compiles automatically?

Understanding javac teaches you what compilation does and helps you troubleshoot build and execution problems.

What happens if I run a program from the wrong folder?

The compiler or launcher may be unable to find the source file or compiled class.

Do comments appear in program output?

No. Comments are ignored as executable instructions and do not appear unless the program explicitly prints similar text.

What is the difference between \n and println()?

\n creates a newline inside string content, while println() prints its value and then adds a line break.

Can command-line arguments contain spaces?

A value containing spaces can generally be passed as one argument by quoting it appropriately in the shell.

Why does args[0] cause an error when no argument is provided?

The arguments array is empty, so there is no element at index 0.

Key Takeaways

  • Java source files use the .java extension.
  • A first Java program can be written in a simple text editor.
  • Java programs are organized using classes.
  • The class keyword declares a class.
  • Class names conventionally use PascalCase.
  • The public class name should match the source filename.
  • HelloWorld should be stored in HelloWorld.java.
  • Java is case-sensitive.
  • HelloWorld and helloworld are different identifiers.
  • Curly braces define code blocks.
  • Opening and closing braces should match.
  • The traditional Java application entry point is the main method.
  • The traditional main method commonly uses public static void main(String[] args).
  • public is an access modifier.
  • static allows main to be used without creating an object first.
  • void means the method returns no value.
  • main is the method name recognized for traditional application startup.
  • String[] args receives command-line arguments.
  • args is a conventional parameter name.
  • Command-line arguments are initially strings.
  • System.out.println() prints output and adds a line break.
  • System is a Java class.
  • out represents the standard output stream.
  • println() is a method.
  • Text literals use double quotation marks.
  • Many Java statements end with semicolons.
  • javac compiles Java source code.
  • The traditional compile command is javac HelloWorld.java.
  • Successful compilation generates HelloWorld.class.
  • .class files contain Java bytecode.
  • The traditional run command is java HelloWorld.
  • The JVM executes Java bytecode.
  • The traditional execution command uses the class name, not the .class filename.
  • Source code is written by the developer.
  • Bytecode is generated by the compiler.
  • Statements normally execute sequentially from top to bottom.
  • print() does not automatically add a new line.
  • println() adds a new line after output.
  • Numbers can be printed without quotation marks.
  • Expressions can be evaluated before printing.
  • The plus operator can perform numeric addition or string concatenation.
  • Parentheses can control expression evaluation.
  • Escape sequences represent special characters inside strings.
  • \n creates a new line.
  • \t creates a horizontal tab.
  • \" represents a double quote inside a string.
  • \\ represents a backslash.
  • Java supports single-line comments.
  • Java supports multi-line comments.
  • Java supports documentation comments.
  • Comments are ignored as executable instructions.
  • Command-line arguments are available through the main method parameter.
  • Array indexing begins at 0.
  • Modern Java supports source-file launch mode.
  • The traditional compilation process is still important to understand.
  • Compile-time errors are detected during compilation.
  • Runtime errors occur during execution.
  • Logical errors produce incorrect behavior or results.
  • A missing semicolon can cause a compilation error.
  • Incorrect capitalization can cause errors.
  • Unclosed string literals cause compilation errors.
  • Missing braces can cause compilation errors.
  • Running from the wrong directory can prevent files or classes from being found.
  • Source changes should be saved before compilation.
  • In the traditional process, source changes must be recompiled.
  • Successful compilation may display no message.
  • Good indentation improves readability.
  • Meaningful names improve code quality.
  • The best way to learn the first program is to write, compile, modify, break, fix, and run it repeatedly.

Summary

Your first Java program introduces the complete development cycle: writing source code, saving it in a .java file, compiling it with javac, generating bytecode, and running the compiled class with the java command.

A Java program is organized inside a class. In the traditional application structure, execution begins from the main method. The declaration public static void main(String[] args) contains several important parts that will become clearer as you learn methods, arrays, classes, objects, and access modifiers.

The statement System.out.println() is commonly used to display output. System identifies a Java class, out provides access to standard output, and println() prints a value followed by a line break.

Java source code is stored in .java files. The javac compiler translates valid source code into bytecode stored in .class files. The Java launcher then starts the runtime environment and executes the application.

Java is case-sensitive, so capitalization matters. The public class name and source filename must match, required semicolons must be present, string quotation marks must be closed, and code blocks must use matching braces.

You also learned how print() and println() differ, how to display text and numbers, how expressions can be evaluated, how escape sequences work, and how comments can document source code.

The main method can receive command-line arguments through String[] args. These arguments are initially strings and can be accessed using array indexes.

Finally, you learned the difference between compile-time errors, runtime errors, and logical errors. Understanding these categories will make debugging easier throughout the rest of the course.

Lesson 5 Completed
  • You created your first Java source file.
  • You wrote a complete Java program.
  • You understand the basic class declaration.
  • You understand why the class name matters.
  • You understand curly braces and code blocks.
  • You recognize the traditional main method.
  • You understand the role of public in the main method.
  • You understand the basic role of static.
  • You understand what void means.
  • You understand why the method is named main.
  • You understand the purpose of String[] args.
  • You understand the program entry point.
  • You understand System.out.println().
  • You understand the basic role of System.
  • You understand the basic role of out.
  • You understand what println() does.
  • You understand string literals.
  • You understand why semicolons are used.
  • You know how to compile a Java source file.
  • You understand what compilation does.
  • You understand the purpose of the .class file.
  • You know how to run a compiled Java program.
  • You understand the complete source-to-output flow.
  • You understand Java case sensitivity.
  • You understand filename and public class name matching.
  • You understand basic class naming rules.
  • You understand why indentation matters.
  • You understand basic whitespace behavior.
  • You can write multiple statements.
  • You understand print().
  • You understand println().
  • You know the difference between print() and println().
  • You can print numbers.
  • You can print calculations.
  • You can combine text and values.
  • You understand basic string concatenation.
  • You understand basic escape sequences.
  • You can create new lines and tabs inside strings.
  • You can print quotes and backslashes.
  • You understand Java comments.
  • You can write single-line comments.
  • You can write multi-line comments.
  • You recognize documentation comments.
  • You understand command-line arguments.
  • You can access values from args.
  • You understand that arguments are strings.
  • You understand source-file launch mode.
  • You know the difference between traditional compilation and source-file mode.
  • You understand compile-time errors.
  • You understand runtime errors.
  • You understand logical errors.
  • You can identify common first-program mistakes.
  • You know how to solve filename problems.
  • You know how to solve missing semicolon problems.
  • You know how to identify capitalization mistakes.
  • You know how to identify unclosed strings.
  • You know how to identify missing braces.
  • You understand basic main-class loading errors.
  • You know why the current directory matters.
  • You can create variations of your first program.
  • You are ready to understand the detailed structure of a Java program.
Next Lesson →

Java Program Structure