Chapter 02 of 21
Chapter 02 — Phase 1: Fundamentals
Setting Up Java
Install the JDK, configure your environment, set up a professional IDE, and run your first Java program three different ways. No prior setup experience needed — every step is covered.
~30 min read
Practical Setup
All OS Covered
12 Practice Problems
📦
2.1 — InstallInstalling the JDK

The JDK (Java Development Kit) is the foundation. Without it, you cannot compile or run Java programs. It includes the compiler (javac), the runtime (JVM), and all core Java libraries.

Which JDK to Install?

Always choose an LTS (Long-Term Support) version — it is stable and supported for years. Recommended: JDK 17 or JDK 21. Avoid odd-numbered versions like 19 or 23 — they are short-term releases.

Step 1 — Download

Two reliable, free sources:

SourceURLNotes
Eclipse Temurin (Recommended)adoptium.netFree, open-source, community-backed. Best for students.
Oracle JDKoracle.com/javaOfficial Oracle release. Free for personal/dev use.
Amazon Correttoaws.amazon.com/correttoFree, enterprise-grade, maintained by Amazon.

On the download page: select your operating system (Windows/Mac/Linux), your architecture (x64 for most PCs, aarch64 for Apple M1/M2), and download the installer (.msi for Windows, .pkg for Mac, .deb or .rpm for Linux).

Step 2 — Set Environment Variables

After installing, the system needs to know where Java is installed so that java and javac commands work from any folder in the terminal.

Windows — Setting JAVA_HOME and PATH:

  1. Right-click This PCPropertiesAdvanced system settings
  2. Click Environment Variables button at the bottom
  3. Under System variables, click New:
    Variable name: JAVA_HOME
    Variable value: C:\Program Files\Java\jdk-17 (your actual install path)
  4. Find the Path variable → click Edit → click New → type: %JAVA_HOME%\bin
  5. Click OK on all dialogs. Open a new Command Prompt (important — old ones won't see the change).
Windows CMD — Verify
C:\> java --version
openjdk 17.0.9 2023-10-17

C:\> javac --version
javac 17.0.9

C:\> echo %JAVA_HOME%
C:\Program Files\Java\jdk-17

macOS — Using .pkg installer (easiest):

  1. Run the downloaded .pkg file — it installs automatically to /Library/Java/JavaVirtualMachines/
  2. Open Terminal and add to your shell profile. For Zsh (default on modern Mac), edit ~/.zshrc:
macOS Terminal — Setup
# Add to ~/.zshrc (open with: nano ~/.zshrc)
export JAVA_HOME=$(/usr/libexec/java_home -v 17)
export PATH=$JAVA_HOME/bin:$PATH

# Apply changes:
source ~/.zshrc

# Verify:
java --version
javac --version

Linux (Ubuntu/Debian) — Using apt:

Linux Terminal — Install & Verify
# Update packages and install JDK 17:
sudo apt update
sudo apt install openjdk-17-jdk

# Verify installation:
java --version
javac --version

# If multiple Java versions exist, choose default:
sudo update-alternatives --config java

# Set JAVA_HOME (add to ~/.bashrc):
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
export PATH=$JAVA_HOME/bin:$PATH
source ~/.bashrc

Step 3 — Verify Installation

Open a brand new terminal window and run both commands. Both must show version numbers:

Terminal — Both Commands Must Work
$ java --version
openjdk 17.0.9 2023-10-17
OpenJDK Runtime Environment Temurin-17.0.9+9

$ javac --version
javac 17.0.9
If You See Version Numbers — You're Done!

Both java and javac working means JDK is installed and your PATH is correct. You are ready to compile and run Java programs.

If Commands Are Not Recognized
  • Windows: Did you open a NEW Command Prompt after setting PATH? Old ones don't see new variables.
  • All OS: Check that JAVA_HOME points to the correct folder where JDK was installed.
  • All OS: Make sure you added %JAVA_HOME%\bin (Windows) or $JAVA_HOME/bin (Mac/Linux) — the \bin part is essential.
  • Mac: Did you run source ~/.zshrc after editing the file?
🖥️
2.2 — ToolsChoosing Your IDE

An IDE (Integrated Development Environment) is a smart code editor with features like autocomplete, error highlighting, and one-click running. You can write Java in Notepad — but a good IDE makes you 10x more productive.

IDEBest ForProsConsCost
IntelliJ IDEA CommunityProfessional & studentsBest Java intelligence, smart autocomplete, refactoring, built-in debuggerHigher RAM usage (~500MB+)Free
VS CodeLightweight daily useFast, free, great extensions ecosystem, low RAMNeeds extensions, not Java-nativeFree
EclipseUniversity & enterpriseWidely used in academia, powerful featuresOlder UI, can feel slowFree
BlueJComplete beginnersDesigned for learning OOP, shows object diagramsNot used in real-world workFree
Replit / JDoodleQuick experimentsNo installation, runs in browserLimited features, needs internetFree
Recommendation for CSE Students

Use IntelliJ IDEA Community Edition for daily work and assignments — it has the best Java support and will be familiar when you enter the industry. Use VS Code when on a low-RAM machine. Know how to run from the terminal too — university lab exams may not have IDEs.

IntelliJ IDEA — Complete Setup

1
Download
Go to jetbrains.com/idea → Download Community Edition (free). Run the installer, accept defaults.
2
Create New Project
Open IntelliJ → New Project → Select Java on the left → Choose your JDK from the dropdown → Name your project (e.g., JavaCourse) → Click Create.
3
Create a Java Class
In the Project panel (left), right-click the src folder → New → Java Class → Type HelloWorld → Press Enter.
4
Write Your Code
The editor opens. Type psvm and press Tab — IntelliJ auto-expands it to the full main method! Type sout + Tab for System.out.println().
5
Run
Click the green ▶ Play button next to the main method, or press Shift+F10. Output appears in the Run panel at the bottom.
IntelliJ Live Templates — Speed Up Typing
Type ThisPressExpands To
psvmTabpublic static void main(String[] args) { }
soutTabSystem.out.println();
soutvTabSystem.out.println("varName = " + varName);
foriTabFull for(int i=0; i<n; i++) loop
iterTabEnhanced for-each loop

VS Code — Java Setup

1
Install VS Code
Download from code.visualstudio.com. Free, fast, works on all OS.
2
Install Java Extension Pack
Open VS Code → click the Extensions icon (Ctrl+Shift+X) → search "Extension Pack for Java" by Microsoft → Install. This adds: language support, debugger, test runner, and Maven support.
3
Open a Folder & Create File
File → Open Folder → create a new folder for your project. Create a new file named HelloWorld.java. VS Code will detect it as Java automatically.
4
Run
A "Run Java" link appears above the main method. Click it. Output appears in the Terminal panel below.
▶️
2.3 — ExecutionRunning Java — Three Ways

You should know all three methods. University lab exams may only have a terminal. Job interviews may ask you to compile from command line.

Way 1 — Terminal / Command Prompt (Master This First)

Terminal — Full Workflow
# Step 1: Navigate to the folder containing your .java file
cd Desktop/JavaProjects

# Step 2: List files to confirm your .java file is there
ls          # Mac/Linux
dir         # Windows

# Step 3: Compile — creates HelloWorld.class in the same folder
javac HelloWorld.java

# Step 4: Run — use class name, NOT filename
java HelloWorld

# Output:
Hello, World!
Essential Terminal Commands
CommandWindowsMac / Linux
Go into foldercd FolderNamecd FolderName
Go up one levelcd ..cd ..
List filesdirls
Clear screenclsclear
Show current pathcdpwd

Way 2 — IntelliJ IDEA (Fastest for Development)

Once set up (see Section 2.2), simply press Shift+F10 or click the green play button. IntelliJ handles compilation and running automatically. You can see output, errors, and debug all in one window.

Key IntelliJ Shortcuts
ShortcutAction
Shift+F10Run current program
Shift+F9Debug current program
Ctrl+ZUndo
Ctrl+/Toggle comment on line
Ctrl+DDuplicate current line
Alt+EnterQuick fix (fix errors automatically)
Ctrl+Shift+F10Run the file in the editor

Way 3 — Online Compiler (No Installation Needed)

Useful when you're on a different computer or want to test quickly. Just paste code and run.

SiteURLBest Feature
JDoodlejdoodle.comSimple, fast, supports multiple Java versions
Replitreplit.comFull project support, shareable links
OnlineGDBonlinegdb.comHas debugger, good for tracing code
Programizprogramiz.com/java-programming/online-compilerClean UI, good for beginners
📁
2.4 — OrganisationRecommended Project Structure

Keeping your files organised from day one is a professional habit. Here's a structure that works for university coursework:

JavaCourse/ ← Root project folder ├── Chapter01/ │ ├── HelloWorld.java │ └── HelloWorld.class ← created by javac ├── Chapter02/ │ └── SetupTest.java ├── Chapter04/ │ ├── Variables.java │ └── DataTypes.java ├── OOP/ │ ├── Student.java │ └── BankAccount.java └── Practice/ ├── Easy/ └── Medium/ Rule: ONE public class per .java file. File name must match public class name exactly.
IntelliJ Project vs Simple Folder

In IntelliJ, code goes inside the src/ folder of your project. The compiled .class files go to out/production/ automatically. You never need to run javac manually in IntelliJ — it compiles in the background as you type.

🚨
2.5 — TroubleshootComplete Error Guide

Every beginner hits these errors. Here they are with exact causes and fixes:

🚨 Error Reference Table
Error MessageCauseFix
'java' is not recognizedPATH not set / terminal not restartedSet JAVA_HOME + PATH, open NEW terminal
'javac' is not recognizedJRE installed instead of JDK, or PATH missingInstall JDK (not JRE), add bin to PATH
error: class X is public, should be in file X.javaFilename doesn't match class nameRename file to exactly match class name (case-sensitive)
error: ';' expectedMissing semicolon at end of statementAdd ; at the line shown in error
error: reached end of file while parsingMissing closing brace }Count opening vs closing braces — add the missing one
Could not find or load main class XWrong class name in run command, or in wrong folderUse java ClassName (no .class). Run from folder containing .class file
Main method not found in class Xmain method missing or wrong signatureEnsure exact signature: public static void main(String[] args)
error: cannot find symbolVariable/method not declared, or typoCheck spelling, ensure variable is declared before use
How to Read Java Error Messages

Java errors show: FileName.java:LineNumber: error: description

Sample Error
HelloWorld.java:5: error: ';' expected
        System.out.println("Hello")
                                   ^
1 error
  • HelloWorld.java — which file has the error
  • 5 — which line number to look at
  • error: ';' expected — what Java expected but didn't find
  • ^ — caret points to the exact position of the problem

Always fix errors from top to bottom — one error can cascade into many. Fix the first one and recompile before worrying about the others.

2.6 — VerifyComplete Setup Checklist

Tick every item to confirm your environment is fully working:

📝
2.7 — ExamExam Preparation
2 Marks — Short Answer

Q: What is JAVA_HOME and why must it be set?

Answer: JAVA_HOME is an environment variable that stores the installation path of the JDK on the system. It must be set so that the operating system and other tools (like build tools Maven and Gradle) can locate the JDK directory. The PATH variable is then set to include %JAVA_HOME%\bin (Windows) so that java and javac commands can be executed from any directory in the terminal.

3 Marks — Explain

Q: What is the difference between compiling and running a Java program? Write the exact commands used.

Answer: Compiling is the process of translating Java source code (.java file) into bytecode (.class file) using the Java compiler. Command: javac HelloWorld.java — this creates HelloWorld.class. Running is the process of launching the JVM to execute the compiled bytecode. Command: java HelloWorld — note there is no file extension; Java takes the class name, not the filename. The JVM then loads the .class file, finds the main method, and executes it.

MCQs

Q1.Which command compiles a Java source file named Test.java?
Ajava Test.java
Bjavac Test.java
Cjava Test
Dcompile Test.java
javac is the Java compiler command. javac Test.java compiles the source file and produces Test.class. The java command is for running, not compiling.
Q2.After compiling HelloWorld.java, which file is created?
AHelloWorld.exe
BHelloWorld.class
CHelloWorld.jar
DHelloWorld.bin
✓ Compilation with javac produces a .class file containing bytecode. This is NOT machine code — it's an intermediate format the JVM can run on any platform.
Q3.What does the IDE shortcut psvm expand to in IntelliJ?
ASystem.out.println();
Bpublic static void main(String[] args) { }
CA for loop template
DA class template
psvm is a Live Template in IntelliJ that expands to the full main method signature. Type it and press Tab. Similarly, sout + Tab expands to System.out.println();.
Q4.You see: 'javac' is not recognized as an internal or external command. Most likely cause?
AJava code has a syntax error
BThe .java file doesn't exist
CJDK bin directory is not in the PATH environment variable
DThe program has a runtime error
✓ This error means the OS cannot find the javac executable. Either the JDK is not installed, the bin folder was not added to PATH, or the terminal wasn't restarted after setting PATH.
Q5.Which of the following is the CORRECT command to run a compiled Java class named MyApp?
Ajava MyApp.java
Bjavac MyApp
Cjava MyApp
Djava MyApp.class
java MyApp is correct — no extension. The java launcher takes the class name. java MyApp.java would try to find a class literally named "MyApp.java". java MyApp.class would try to find a class named "MyApp.class".
Memory Tips — Chapter 2
  • javac vs java: "javac = compile (C for Compile). java = run."
  • No extension when running: java HelloWorld not java HelloWorld.class — you give the class NAME, not the filename.
  • Fix errors top to bottom: One error often causes 10 more. Fix the first, recompile, repeat.
  • New terminal after PATH change: Environment variables are loaded when the terminal starts — old terminals don't see new values.
  • psvm + Tab: The fastest way to type the main method in IntelliJ. sout + Tab for println.
Quick Revision — Chapter 2
Download JDK from adoptium.net or oracle.com. Choose LTS version (17 or 21).
Set JAVA_HOME to JDK install path. Add $JAVA_HOME/bin to PATH. Open NEW terminal to apply.
Verify: java --version and javac --version must both show version numbers.
Compile: javac FileName.java → creates FileName.class. Run: java ClassName (no extension).
IntelliJ: best IDE for Java. psvm+Tab → main method. sout+Tab → println. Shift+F10 → run.
VS Code: install "Extension Pack for Java" by Microsoft for Java support.
Error "not recognized" → PATH not set. Error "class X should be in file X.java" → filename mismatch.
Fix errors top to bottom. Read: filename:lineNumber:description. ^ points to the exact problem location.
💪
2.8 — PracticePractice Problems

Easy

P2.1
Verify Setup
Run both java --version and javac --version in your terminal. Take note of the version numbers. If either fails, fix it before continuing.
EasyPractical
P2.2
Terminal Workflow
Create HelloWorld.java using only a plain text editor (Notepad or gedit — no IDE). Compile and run it entirely from the terminal. Confirm output.
EasyPractical
P2.3
IntelliJ First Program
Create a new IntelliJ project. Use psvm and sout shortcuts to write a program that prints your name. Run with Shift+F10.
Easy
P2.4
Error Reproduction
Deliberately rename your .java file so it doesn't match the class name. What exact error do you get? Fix it. Document what you learned.
EasyDebug
P2.5
Three Ways Challenge
Run the same HelloWorld program all three ways: terminal, IDE, and an online compiler (jdoodle.com). Screenshot or note the output from each.
EasyPractical

Medium

P2.6
Project Folder Structure
Create the folder structure shown in Section 2.4 on your computer. Place a working Java file in Chapter01, Chapter02, and Practice/Easy folders. Compile and run each from the correct directory.
Medium
P2.7
Error Message Collection
Intentionally create each of these errors: missing semicolon, missing brace, wrong capitalization, wrong run command. Document the exact error message, line number, and fix for each.
MediumDebug
P2.8
Multiple Files
Create three separate Java files in the same folder: First.java, Second.java, Third.java — each printing a different message. Compile all three with one command: javac *.java. Then run each.
Medium
P2.9
IDE vs Terminal Compare
Write a program with a deliberate error (e.g., missing semicolon). Compare how IntelliJ highlights it vs how the terminal shows it. Which gives more helpful feedback?
Medium

Hard

P2.10
JAVA_HOME Deep Dive
In a terminal, print the full contents of your JAVA_HOME directory (ls $JAVA_HOME/bin on Mac/Linux, dir %JAVA_HOME%\bin on Windows). Identify at least 8 tools listed and look up what each one does.
Hard
P2.11
Javadoc Generation
Write a class with a /** */ Javadoc comment above the class declaration. Then run javadoc ClassName.java in the terminal. Open the generated HTML file. This is how Java API documentation is made.
Hard
P2.12
Setup Documentation
Write a complete Java program that, when run, prints step-by-step Java installation instructions for a friend using your operating system. Include all commands they'd need to type.
Hard
Chapter 2 Challenge

True setup mastery means you can recover from anything.

  • Unset your PATH temporarily (or open a fresh shell without Java in PATH) and try running Java. Reproduce the "not recognized" error, then fix it from scratch.
  • Without any IDE: write, compile, and run a program that prints a 5-line formatted table using only a plain text editor and terminal commands.
  • Find out: what Java version is installed on your university lab computers? Is it JDK or JRE? How can you tell the difference from the command line?