Project Based Learning in Java

Introduction to Java

Java overview, JVM flow, JDK/JRE/JVM, WORA, and first program.

Lecture 1.1.1 CO1 aligned Unit 1

Learning outcome: Explain what Java is, why it is used, how a Java program runs, and how to write, compile, and execute a first program.

Java is a high-level, class-based programming language with strong object-oriented support, designed for building portable and reliable software. It is used in Android applications, enterprise systems, banking platforms, e-commerce systems, desktop tools, and server-side services.

Java was created at Sun Microsystems by a team led by James Gosling and released publicly in 1995. Its central design promise is still its most important idea: write a program once, compile it once, and run it on any system that has a compatible Java Virtual Machine.

Why Java Matters

Java remains important because it balances readability, strong tooling, object-oriented design, and platform independence. Students coming from C or C++ will recognize braces, semicolons, data types, expressions, and control structures, but Java changes the execution model and removes several low-level responsibilities.

Key reasons Java is widely used:

Feature What it means in practice
Simple Cleaner than C++ in many common situations; no direct pointer arithmetic and no manual delete.
Object-oriented Programs are organized around classes and objects, which helps model real systems.
Platform independent Java source compiles to bytecode that can run on any platform with a JVM.
Architecture-neutral Bytecode is not tied to one processor or operating system.
Portable The same compiled bytecode can be carried across platforms.
Robust Strong type checking, exceptions, and automatic memory management reduce many common errors.
Secure The JVM prevents direct memory access and provides a controlled runtime environment.
High performance Modern JVMs use JIT compilation to speed up frequently used bytecode.
Multithreaded Built-in support for running multiple tasks at the same time.
Distributed/network ready Standard libraries support networking, web systems, and enterprise applications.
Dynamic Classes can be loaded when needed at runtime.

How a Java Program Runs

Java does not compile source code directly into machine code for one operating system. Instead, Java source code is compiled into bytecode. Bytecode is stored in .class files and is executed by the Java Virtual Machine.

In simple terms: Bytecode is a recipe written in a shared kitchen language. The recipe itself belongs to no particular kitchen; every kitchen keeps a cook — the JVM — who reads that language and works the local stove.

Java source code is compiled to bytecode and executed by the JVM Source HelloWorld.java human readable javac Bytecode HelloWorld.class portable format java JVM executes Output console
Figure 1. Java source becomes bytecode, and bytecode runs on the JVM.

The execution flow is:

  1. Write source code in a .java file.
  2. Compile the source with javac.
  3. The compiler produces .class bytecode.
  4. The JVM loads and executes the bytecode.
  5. The program produces output.

JDK, JRE, and JVM

These terms are related but distinct. Older teaching diagrams often show the JDK containing a separately installed JRE, which contains the JVM. For modern JDKs, it is more accurate to treat the JRE as the runtime concept—a JVM plus the libraries and supporting files required by an application—while the JDK supplies both development tools and a runtime image.

In simple terms: The JVM is the engine, the JRE is the whole car you can drive, and the JDK is that car plus the workshop and tools for building new ones. Writing programs needs the workshop; only running a finished program needs just the car.

The JDK supplies development tools and Java runtime components, including a JVM JDK Development tools plus a Java runtime image Runtime components JVM plus libraries and supporting files JVM
Figure 2. The modern JDK includes development tools and runtime components; the JVM executes bytecode.
Term Full form Main purpose
JVM Java Virtual Machine Executes bytecode and makes Java portable.
JRE Java Runtime Environment The JVM plus libraries and supporting files needed to run an application; historically also distributed as a separate installation.
JDK Java Development Kit Provides development tools such as javac together with a Java runtime image.

For this course, install a JDK. The conceptual distinction still matters: the JVM is the execution engine, a runtime environment supplies what a Java application needs to run, and the JDK adds compilation and development tools.

Inside the JVM Execution Pipeline

After compilation produces a .class file, several components inside the JVM cooperate to load, verify, and execute the bytecode.

In simple terms: Loading, verifying, and executing is airport security for code. The class loader brings the luggage in, the verifier checks that nothing dangerous is inside, and only then is the bytecode allowed through to run.

JVM execution pipeline from class loading to execution .class file bytecode Class Loader loads classes Verifier checks bytecode Interpreter JIT Compiler
Figure 3. The JVM loads bytecode, verifies it, and then executes it through interpretation and JIT compilation.
JVM component Role
Class loader Loads .class files into the JVM.
Bytecode verifier Checks bytecode for illegal or unsafe operations before execution.
Interpreter Executes bytecode instructions directly.
JIT compiler Converts frequently used bytecode into native machine code at runtime for speed.

Platform Independence and WORA

Java's platform independence comes from bytecode. The .class file does not belong to Windows, Linux, or macOS. Each operating system has its own JVM, and that JVM translates the same bytecode for the local machine.

In simple terms: The .class file is one document, and each operating system supplies its own translator. Write it once, and Windows, Linux, and macOS each read it aloud in their own language.

One bytecode file runs on different systems through platform-specific JVMs Bytecode same .class file Windows JVM runs on Windows Linux JVM runs on Linux macOS JVM runs on macOS
Figure 4. Write once, run anywhere depends on platform-specific JVMs.

The bytecode is platform-neutral; the JVM implementation is platform-specific. Complete applications must also avoid incompatible native libraries, operating-system assumptions, and unavailable dependencies if they are to remain portable.

Setting Up the Environment

JDK 17 is the baseline for the core examples and laboratory work. JDK 21 may also be used; features that require a later release are marked Enrichment and are not required for the core exercises.

Check the installation from a terminal:

java -version
javac -version

If both commands print version numbers, Java is installed and available from the system path. If the terminal reports that the command is not found, the JDK bin folder is probably not configured in the PATH.

Recommended editors for beginners:

Tool Best use
Eclipse IDE Full Java IDE with project management, compiler integration, debugging, and classroom-friendly tooling.
Text editor plus terminal Keeps the compile-and-run steps visible while learning.
VS Code Lightweight editor with Java extensions.
IntelliJ IDEA Community Full Java IDE for larger projects.

How to Read the Code Samples

Java blocks appear in two clearly different forms:

  • A block containing a top-level public class is a complete source-file example. Save it in a file whose name matches that class, then compile and run it as shown.
  • A short block containing only declarations, statements, or a method demonstrates one local idea. It is a fragment intended to be placed inside the surrounding class or method described by the text; it is not presented as a standalone program.

Invalid code is commented out or explicitly labelled as invalid. Traditional switch examples show every required break;, except where the text intentionally demonstrates fall-through.

First Java Program

Create a file named exactly HelloWorld.java.

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

Compile and run:

javac HelloWorld.java
java HelloWorld

Output:

Hello, World!

Line-by-line meaning:

Code Meaning
public class HelloWorld Declares a class named HelloWorld. The public class name must match the file name.
public static void main(String[] args) The entry point where the JVM starts execution.
System.out.println(...) Prints a line of output to the console.
{ } Groups code into blocks.
; Ends a statement.

Command-Line Arguments

The String[] args part of main stores command-line arguments. Each argument arrives as a String, even if it looks like a number. Numeric arguments must be converted before arithmetic.

In simple terms: Command-line arguments arrive the way a form arrives filled in by hand: everything is text. Typing 25 at the terminal gives the characters '2' and '5', not the number 25, until the program converts them.

public class AddArgs {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: java AddArgs <first> <second>");
            return;
        }

        try {
            int first = Integer.parseInt(args[0]);
            int second = Integer.parseInt(args[1]);
            System.out.println(first + second);
        } catch (NumberFormatException exception) {
            System.out.println("Both arguments must be valid integers.");
        }
    }
}

Compile and run:

javac AddArgs.java
java AddArgs 10 20

Output:

30

Common Mistakes

Mistake Result Fix
File name does not match the public class name Compilation error Save HelloWorld in HelloWorld.java.
Running java HelloWorld.class Class-launch failure Run java HelloWorld without the .class extension.
Writing Main instead of main JVM cannot find entry point Use lowercase main. Java is case-sensitive.
Missing semicolon Compilation error End each statement with ;.
Unmatched braces Compilation error Check every { has a matching }.

Practice

Problem 1: Print Your Details

Write a program that prints your name, course, and college on separate lines.

public class MyDetails {
    public static void main(String[] args) {
        System.out.println("Name   : Aarav Sharma");
        System.out.println("Course : Project Based Learning in Java");
        System.out.println("College: Chandigarh University");
    }
}

Problem 2: print vs println

Predict the output before running the program.

public class PrintDemo {
    public static void main(String[] args) {
        System.out.print("Java ");
        System.out.print("is ");
        System.out.println("fun.");
        System.out.println("Welcome!");
    }
}

Output:

Java is fun.
Welcome!

Problem 3: A Tiny Calculation

public class Sum {
    public static void main(String[] args) {
        int a = 12;
        int b = 8;
        int total = a + b;
        System.out.println("Sum of " + a + " and " + b + " = " + total);
    }
}

Quick Check

  1. What is bytecode?
  2. Which tool converts .java source into .class bytecode?
  3. What does the JVM do?
  4. Why can the same .class file run on different operating systems?
  5. What is the difference between print and println?

Lecture Quiz

1. Which JVM component is used to load a .class file?

The class loader loads .class files into the JVM.

2. Write the correct order of Java program execution: source code, compilation, class loading, bytecode verification, interpretation, execution.

The order is: Java source code, compilation, class loading, bytecode verification, interpretation or JIT compilation, and execution.

3. What is the extension of a compiled Java file?

The compiled Java file has the .class extension.

4. Which declaration is a valid Unicode character literal: char ch = '\utea';, char ca = 'tea';, char cr = '\u0223';, or char cc = '\itea';?

char cr = '\u0223'; is valid because a Unicode escape uses \u followed by exactly four hexadecimal digits.

Summary

Java is a portable, class-based language with strong object-oriented support. A program is written as source code, compiled by javac into bytecode, and executed by the JVM. A modern JDK supplies both the development tools and a runtime image; “JRE” describes the runtime environment needed to run Java code.