Installing Java and your first program

Time to set up your own machine. You'll install a JDK, make your computer find it, write your first program in a real editor and run it from the terminal. You'll also meet the five errors almost every beginner hits on day one, so they won't scare you when they appear.

Module 1 · Introduction to Java⏱ 17 minBeginnerHands-on setup8 practice problems
1 The story

Kabir's first “Hello”

Kabir has the JDK installed now. Excited, he writes his first program, saves it, compiles it… and gets three different errors in ten minutes. He's about to give up when Riya sits down next to him.

> javac main.java error: class Hello is public, should be declared in a file named Hello.java Fix: rename to Hello.java > java Hello.class Error: Could not find or load main class Hello.class Fix: java Hello > java Hello Namaste, MyPhatshala! Error 1 Error 2 Success! myphatshala.in
Riya

Don't panic, Kabir. I got the exact same errors in my first week. Read the message slowly: it says the class is called Hello, but your file is main.java.

Riya

And the second one: you typed java Hello.class. The java command wants the class name, not the file name.

Arjun Sir

Riya's right. Java error messages look scary, but they are very precise. Today let's set up the machine properly, from the installer to the first output, and learn the five classic first-day errors on purpose.

2 Definition

What does “setting up Java” mean?

Formal definition (write this in exams)

Setting up a Java development environment means installing a JDK, making its tools reachable through the PATH environment variable (and usually setting JAVA_HOME to the JDK's install directory), and choosing a source editor or IDE. A first Java program is a public class saved in a file of the same name with a public static void main(String[] args) method, compiled with javac and executed with java.

In simple words

Install the JDK, tell your computer where its tools are, pick an editor, and you're ready. Your first program is a class with a main method. Save it with the same name as the class, compile it with javac, and run it with java plus the class name.

Words you'll meet in this lesson

PATHA list of folders your operating system searches when you type a command like java.
JAVA_HOMEA variable holding the JDK's top folder. Build tools and IDEs read it.
IDEIntegrated Development Environment: an editor with compile, run and debug built in (IntelliJ IDEA, Eclipse, VS Code).
TerminalA text window for typing commands: Command Prompt or PowerShell on Windows, Terminal on macOS and Linux.
Command-line argumentsExtra words after java Hello, which arrive in args.
Escape sequenceSpecial characters inside a string, like \n (new line) and \t (tab).

Setup checklist

Which JDKAn LTS version: Java 21 or 25. Eclipse Temurin is a free, popular build.
WindowsInstaller from adoptium.net, or winget install EclipseAdoptium.Temurin.21.JDK
macOSInstaller from adoptium.net, or brew install --cask temurin@21
Ubuntu / Debiansudo apt install openjdk-21-jdk
Checkjava -version and javac -version both print 21 (or your version)
EditorIntelliJ IDEA Community (free), VS Code with the Java extension pack, or Eclipse
Golden rulesFile name = public class name · javac File.java · java ClassName (no .class)

Exam tip: a file can contain only one public class, and the file must be named after it (Hello.java for public class Hello). Java is case-sensitive: Hello, hello and HELLO are three different names.

3 Types and ways to use it

Ways to write and run Java

Choose your editor

Plain editor + terminal

Notepad++, VS Code or any text editor, then javac and java by hand. Best for your first week, because you see every step.

Learn the basics

IntelliJ IDEA

The most popular Java IDE in industry. The free Community Edition is enough for this whole course. Smart suggestions, refactoring and a great debugger.

Industry favourite

VS Code

A light editor. Install the “Extension Pack for Java” to get compile, run and debug buttons. Good if you also write Python or web code.

Lightweight

Eclipse IDE

A long-established free IDE, still common in many companies and colleges, especially for older enterprise projects.

Enterprise classic

Four ways to run your program

WayCommandWhen to use
Compile, then runjavac Hello.java
java Hello
The standard way; you see the .class file
Source-file modejava Hello.javaJava 11+: quick single-file practice
IDE Run buttonClick ▶ next to mainEveryday work; the IDE runs javac and java for you
Online editorThe live editor in Part 7No install, any device

New in Java 25: beginners can write a much shorter first program, without a class declaration: void main() { IO.println("Namaste!"); }. This course uses the classic form with public class and public static void main(String[] args), because it works on every Java version, it's what you'll see in company code, and it's what exams ask for.

4 Step by step

Install, check, write, compile, run

  1. Install the JDK

    Download Eclipse Temurin 21 (LTS) for your operating system from adoptium.net and run the installer. On Windows, tick the options “Set JAVA_HOME variable” and “Add to PATH” if the installer offers them.

    The installer copies the JDK folder (bin, lib, conf…) to a location like C:\Program Files\Eclipse Adoptium\jdk-21… on Windows or /Library/Java/JavaVirtualMachines/ on macOS.
  2. Set JAVA_HOME and PATH (if not done)

    Windows: search “Environment Variables” → New system variable JAVA_HOME = the JDK folder → edit Path → add %JAVA_HOME%\bin and move it to the top. macOS/Linux: add these lines to ~/.zshrc or ~/.bashrc:

    export JAVA_HOME=$(/usr/libexec/java_home -v 21)   # macOS
    export PATH="$JAVA_HOME/bin:$PATH"
    PATH is searched from first folder to last. Putting the JDK's bin first makes sure your terminal uses this JDK even if an older Java exists elsewhere.
  3. Open a NEW terminal and check

    java -version
    javac -version
    Terminals read environment variables only when they start, so an old window won't see your changes. Both commands should show the same version.
  4. Write your first program

    Make a folder such as C:\java-practice, open it in your editor, and create Hello.java:

    public class Hello {
        public static void main(String[] args) {
            System.out.println("Namaste, MyPhatshala!");
        }
    }
    Namaste, MyPhatshala!
    The editor saves plain text. Use “Save as” and check the name really is Hello.java, not Hello.java.txt (Windows can hide extensions).
  5. Compile and run

    cd C:\java-practice
    javac Hello.java
    java Hello
    Namaste, MyPhatshala!
    cd moves into your folder, because javac and java look for files in the current folder. javac writes Hello.class; java Hello asks the JVM to load the class named Hello and run its main.
5 See it happen

From installer to first output: both views

Six moments in Kabir's setup. Left: his screen. Right: what the operating system and Java are doing.

Kabir's first program 6 steps
What you see Eclipse Temurin JDK 21 Setup ☑ Add to PATH ☑ Set JAVA_HOME variable Installing… 76% Environment Variables JAVA_HOME C:\Program Files\Eclipse Adoptium\jdk-21… Path %JAVA_HOME%\bin ← moved to top C:\Windows\system32 C:\Program Files\Oracle\Java\javapath C:\> java -version openjdk version "21.0.…" C:\> javac -version javac 21.0.… Both show 21 in a new terminal window. Hello.java public class Hello { public static void main(String[] args) { System.out.println("Namaste, MyPhatshala!"); }} Class name Hello = file name Hello.java C:\java-practice> javac Hello.java C:\java-practice> java Hello Namaste, MyPhatshala! C:\java-practice> java Hello.class Error: Could not find or load main class Hello.class Caused by: java.lang.ClassNotFoundException: Hello.class The classic day-one mistake javac takes a file name: javac Hello.java java takes a class name: java Hello myphatshala.in
Behind the screen Files copied to disk C:\Program Files\Eclipse Adoptium\ jdk-21…\ bin\ java.exe javac.exe jar.exe… lib\ modules (class libraries) conf\ jmods\ legal\ release Two settings, two jobs PATH Used by the operating system: “where do I find a program called java or javac?” Searched top to bottom. JAVA_HOME Used by tools (Maven, Gradle, IDEs, Kafka): “which JDK folder should I use?” Windows searches PATH for “java” 1 …\jdk-21…\bin found ✓ 2 C:\Windows\system32 3 …\Oracle\Java\javapath (old) The first match wins. If the old Java folder were above, the old version would run instead. The naming rule javac enforces file Hello.java public class Hello = If they differ, javac stops with: class Hello is public, should be declared in a file named Hello.java Hello.java javac Hello.class java JVM java Hello means: “load the class named Hello”. The class loader looks for Hello.class in the current folder (the default classpath), loads and verifies it, then calls public static void main(String[] args). args is an empty array, because no extra words were typed. “Hello.class” is read as a class name: package Hello + class “class” So the loader searches for the file Hello/class.class → not found and throws ClassNotFoundException. The dot means “package”, not “extension”. That's why java takes the bare class name. myphatshala.in
6 Real-world use

How developers set up Java at work

At home you install one JDK. At work, setups are a little more organised. Here's what you'll meet in your first job.

Watch it with an example: two commands in the terminal

Riya's folder and terminal, side by side. See which file each command needs and what it creates.

javac Hello.java, then java Hello 6 steps
Animated example 📁 D:\java Hello.java Hello.class > javac Hello.java (no message = success) > java Hello Hello, Riya! > java hello Error: Could not find or load main class hello JVM starts → loads Hello.class finds public static void main(String[] args) runs main → println myphatshala.in
17 · 21 · 25

1. Several JDKs on one laptop

Developers often maintain an older project on Java 17 and a new one on Java 21. Tools such as SDKMAN! (macOS/Linux) or the IDE's own JDK settings let you switch per project without breaking anything.

Project A → JDK 17·SDKMAN / IDE settings·Project B → JDK 21

2. IDE projects instead of single files

In a company, you rarely compile files by hand. IntelliJ IDEA or Eclipse opens a Maven or Gradle project, downloads libraries and compiles everything when you press Run. Knowing javac and java still helps you understand what the Run button does.

Open project→IDE runs javac + java for you→Output pane
.sdkmanrcjava=21…

3. The Java version written into the project

Teams record the Java version in the build file (for example <maven.compiler.release>21</maven.compiler.release>) and sometimes a version file in the repository, so every developer and the build server use the same version.

pom.xml / build.gradle→release 21→Same everywhere
Dev container

4. Ready-made dev containers and cloud IDEs

Some teams give new joiners a dev container or cloud workspace with the right JDK, tools and settings already installed. You open it and start coding on day one.

Open repo→Container with JDK 21→Code immediately
$ java -versionopenjdk 21…

5. Interview coding rounds

Online assessments and coding interviews often use a browser editor where only the class name Main or Solution works, exactly like the live editor below. Knowing the class-name rule saves panic in the middle of a test.

Online test→public class Main / Solution→Submit

Examples are simplified. Every company has its own setup guide; read it on your first day.

7 Run the code

Your first real programs

Here's a slightly bigger first program with notes. The live editor uses the class name Main, so the challenges do too.

public class Hello {
    public static void main(String[] args) {
        System.out.println("Namaste, MyPhatshala!");
        System.out.println("Arguments received: " + args.length);
        System.out.println("Java\tis\tfun");
    }
}
Namaste, MyPhatshala! Arguments received: 0 Java is fun
  • public class HelloThe class name. Save the file as Hello.java, with a capital H.
  • String[] argsHolds any words typed after the class name. java Hello Riya Kharghar would make args.length 2.
  • args.lengthHow many arguments arrived. With plain java Hello it's 0.
  • "Java\tis\tfun"\t is an escape sequence for a tab. Others: \n new line, \" a double quote, \\ a backslash.
8 Line by line

What the JVM does with your first program

Step through Hello.java. Watch where args comes from and how each line reaches the console.

Worked examples: real problems, solved and traced in memory

Your first programs mostly print. These three show the printing tools you'll use for years: println vs print, escape sequences like \t and \n, and the args array that receives command-line input.

Example 1Railways · tickets

Print a train ticket with tabs and new lines

Problem statement

Print a small train ticket with labels lined up in columns. Use \t (tab) to align and \n to start new lines inside one string.

Input
PNR 4521789630, train 12123 Deccan Queen, coach C2 seat 34
Expected output
==== E-TICKET ====
PNR:	4521789630
Train:	12123 "Deccan Queen"
Coach:	C2
Seat:	34
==================

Approach

  1. \t moves to the next tab stop; \n starts a new line.
  2. Build the ticket with a few println calls.
  3. Use \" to print double quotes inside a string.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 2Shop · receipts

print vs println on one receipt line

Problem statement

A shop prints each item, its quantity and price on one line, building it piece by piece. Use print (stays on the same line) and finish each line with println.

Input
Pen × 3 Rs 30, Notebook × 2 Rs 90
Expected output
Pen x3 Rs 30
Notebook x2 Rs 90
Total Rs 120

Approach

  1. System.out.print prints without a line break.
  2. System.out.println() ends the line.
  3. Print a total at the end.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 3Command line · args

How many arguments did the program get?

Problem statement

When you run java Main from a terminal, extra words after it arrive in the args array. This run has none. Print how many arguments arrived and what args is.

Input
run as: java Main (no extra words)
Expected output
Arguments received: 0
Is args null? false
Try: java Main Asha 3

Approach

  1. args is a String[] created by the JVM before main starts.
  2. args.length is the number of words passed.
  3. With no words, it's an empty array (length 0), not null.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

9 Quiz and revision

Check yourself

Quick revision

Lesson 1.5 in one screen

  • Install an LTS JDK (21 or 25), e.g. Eclipse Temurin. Check with java -version and javac -version.
  • PATH: the OS finds commands (first match wins). JAVA_HOME: tools find the JDK folder.
  • Open a new terminal after changing variables.
  • Public class name = file name, case-sensitive. One public class per file.
  • javac Hello.java (file name) → java Hello (class name). Or java Hello.java for quick runs.
  • Entry point: public static void main(String[] args); args holds command-line words.
  • Escape sequences: \n \t \" \\.

Interview and viva questions

Can a Java file have more than one class?

Yes, but at most one public class, and the file must be named after it. javac creates a separate .class file for every class in the file.

Can the file name differ from the class name?

Only if the class is not public. For example, a non-public class Test can be saved in Practice.java, and javac will produce Test.class. For public classes, the names must match.

What's the difference between PATH and JAVA_HOME?

PATH is an operating-system list of folders searched for commands, so it lets you type java anywhere. JAVA_HOME is a convention used by other tools (Maven, Gradle, Tomcat, Kafka, IDEs) to find which JDK to use. You usually set both, with PATH including JAVA_HOME/bin.

What is the difference between print and println?

print writes the text and stays on the same line. println writes the text and then a line break. printf writes formatted text, for example System.out.printf("Total: %d%n", 60).

What happens if you write main without static?

On classic Java versions the program compiles, but java Main reports that the main method was not found, because the JVM calls main without creating an object first, which requires it to be static. (Java 25 relaxed these rules for simple programs, but the classic form works everywhere.)

Practice problems

Practise printing exactly what you want: lines, tabs, quotes and numbers. Every output is fixed. The last three are business tasks.

P1Easy

Hello on three lines

Print Hello, Namaste and Vanakkam on three lines with one println.

Input
(none)
Expected output
Hello
Namaste
Vanakkam
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello\nNamaste\nVanakkam");
    }
}
Hello Namaste Vanakkam

How it works: each \n starts a new line.

P2Easy

Print quotes

Print: She said "Java is easy".

Input
(none)
Expected output
She said "Java is easy".
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        System.out.println("She said \"Java is easy\".");
    }
}
She said "Java is easy".

How it works: \" is the escape for a double quote.

P3Easy

print on one line

Print 1 2 3 on one line using three print calls, then end the line.

Input
(none)
Expected output
1 2 3
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        System.out.print("1 ");
        System.out.print("2 ");
        System.out.print("3");
        System.out.println();
    }
}
1 2 3

How it works: println() with no argument just ends the line.

P4Medium

A tabbed table

Print a 2-row table with columns Item and Price, separated by tabs.

Input
Tea 15, Coffee 25
Expected output
Item	Price
Tea	15
Coffee	25
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        System.out.println("Item\tPrice");
        System.out.println("Tea\t15");
        System.out.println("Coffee\t25");
    }
}
Item Price Tea 15 Coffee 25

How it works: tabs line up short columns; for perfect alignment you'll later use printf.

P5Medium

Print a backslash

Print the Windows path C:\Java\bin.

Input
(none)
Expected output
C:\Java\bin
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        System.out.println("C:\\Java\\bin");
    }
}
C:\Java\bin

How it works: a single backslash starts an escape, so a real backslash is written \\.

P6Business problem

Shop banner

Print a 3-line banner for "Sharma General Store" with a line of = signs above and below.

Input
(none)
Expected output
========================
  Sharma General Store
========================
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        System.out.println("========================");
        System.out.println("  Sharma General Store");
        System.out.println("========================");
    }
}
======================== Sharma General Store ========================

How it works: small banners like this are common in receipts and console tools.

P7Business problem

Bill with print and println

Print "Total: Rs 450" by printing the label, then the amount, then ending the line.

Input
450
Expected output
Total: Rs 450
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int total = 450;
        System.out.print("Total: Rs ");
        System.out.println(total);
    }
}
Total: Rs 450

How it works: print and println accept numbers as well as text.

P8Business problem

Argument count check

A billing tool expects 2 arguments (customer and amount). Print how many it got and how many are missing.

Input
run with no arguments
Expected output
Got 0 of 2 arguments
Missing: 2
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        System.out.println("Got " + args.length + " of 2 arguments");
        System.out.println("Missing: " + (2 - args.length));
    }
}
Got 0 of 2 arguments Missing: 2

How it works: real command-line tools check args.length first and print usage help if something is missing.

Real-world scenario questions (asked in company interviews)

Setup problems are some of the first things you'll solve in a new job. Decide your answer first, then open the model answer.

Online assessment · campus hiringFresher

Your code won't compile in the online test

In a timed online coding test, your solution works on your laptop, where the class is called BankAccountSolver. When you paste it into the test's editor and press Run, you get a compile error about the class being public and the file name. The timer is running.

The interviewer is checking: can you read an error quickly and calmly, and do you know the file-name rule?

Show a strong answer

The online editor saves the code in a fixed file, usually Main.java or Solution.java. A public class must match that file name, so public class BankAccountSolver fails.

  • Rename the public class to the name the platform expects (read the starter code or instructions; usually Main or Solution).
  • Helper classes can stay, but without the public keyword.
  • Also check that the platform's expected main method or function signature hasn't been changed.

Avoid: rewriting your logic in a panic. The logic is fine; only the class name is wrong.

IT services · first weekFresher

Two projects, two Java versions

You're assigned to two projects: a maintenance project on Java 17 and a new microservice on Java 21. If you change PATH for one, the other's build breaks. Your lead asks how you'll set up your laptop.

The interviewer is checking: do you know how professionals manage several JDKs without fighting with PATH every day?

Show a strong answer
  • Install both JDKs side by side; they don't conflict on disk.
  • In the IDE, set the Project SDK separately for each project (IntelliJ: Project Structure → SDK).
  • For the command line, use a version manager such as SDKMAN! on macOS/Linux, or a small script per project that sets JAVA_HOME and PATH before building.
  • Rely on each project's build file (maven.compiler.release or Gradle toolchains) to declare its Java version, so builds are predictable.

Avoid: uninstalling and reinstalling JDKs every time you switch projects.

Any company · support ticketFresher

“Could not find or load main class” on a colleague's machine

A tester runs java com.shop.App inside the project's target/classes folder and it works. A colleague runs java App from inside target/classes/com/shop and gets Could not find or load main class App. They ask you why the same class works for one and not the other.

The interviewer is checking: do you understand that the class loader finds classes using the full class name and the classpath, not just the file?

Show a strong answer

The class is in the package com.shop, so its real name is com.shop.App. The class loader turns that into the path com/shop/App.class and searches for it starting from each classpath folder.

  • The tester ran from target/classes, so com/shop/App.class was found.
  • The colleague asked for a class called just App from inside the package folder, so the name and the location don't match.
  • Fix: run from the classpath root with the full name, or use java -cp target/classes com.shop.App from anywhere. Packages are covered in Lesson 6.6.

Avoid saying: “The class file must be corrupted.”

Any company · laptop setupFresher

IntelliJ runs it, the terminal doesn't

Your program runs perfectly with IntelliJ's Run button. In the terminal, javac isn't recognised at all. A senior asks: “If IntelliJ can compile it, Java must be installed. What's going on?”

The interviewer is checking: do you understand that an IDE can use its own JDK, separate from the system PATH?

Show a strong answer

IntelliJ can download and use a JDK of its own and remembers its location in the project settings. The terminal doesn't know about that: it only searches the folders in PATH.

  1. Find the JDK IntelliJ uses (Project Structure → SDK shows its path).
  2. Set JAVA_HOME to that folder and add its bin to PATH (or install a JDK system-wide).
  3. Open a new terminal and confirm with javac -version.

Avoid: concluding that Java is “half installed”. Two programs are simply looking in different places.