Download Programming in Java: A Full, Detailed Guide and more Study notes Javascript programming in PDF only on Docsity!
Programming in Java
A Full, Detailed Guide
From Core Syntax to Modern Java, Concurrency, Design Patterns,
and the JVM
A comprehensive reference and learning companion, with diagrams and complete code
examples
Table of Contents
Chapter 1 — Introduction to Java
Chapter 2 — Variables, Data Types, and Operators
Chapter 3 — Classes, Objects, and Constructors
Chapter 4 — Polymorphism, Abstraction, and Interfaces
Chapter 5 — Encapsulation, Access Modifiers, and Packages
Chapter 6 — Exception Handling
Chapter 7 — The Collections Framework
Chapter 8 — Generics
Chapter 9 — Multithreading and Concurrency
Chapter 10 — File I/O and Serialization
Chapter 11 — Lambda Expressions and Functional Interfaces
Chapter 12 — The Streams API
Chapter 13 — JDBC: Database Connectivity
Chapter 14 — Common Design Patterns in Java
Chapter 15 — JVM Internals, Memory Management, and Garbage Collection
Chapter 16 — Testing with JUnit
Chapter 17 — Modern Java: Records, Pattern Matching, Text Blocks
Appendix A — Quick Reference
CHAPTER 1: Introduction to Java
Java is a general-purpose, class-based, object-oriented programming language originally developed by
James Gosling and his team at Sun Microsystems, first released publicly in 1995. Sun Microsystems was
later acquired by Oracle Corporation in 2010, and Oracle continues to steward the language today. Java
was designed around a small set of guiding principles that still define it: it should be simple,
object-oriented, familiar to C/C++ programmers, robust, secure, architecture-neutral, portable,
high-performance, interpreted, threaded, and dynamic. The single idea that made Java revolutionary at
the time was "Write Once, Run Anywhere" (WORA) — the promise that compiled Java code could run
unmodified on any device equipped with a Java Virtual Machine, regardless of the underlying hardware or
operating system.
1.1 Why Java Is Platform Independent
Most traditional compiled languages, such as C or C++, translate source code directly into native machine
code specific to a particular processor architecture and operating system. A program compiled for
Windows on x86 hardware will not run on a Linux ARM device without recompilation. Java takes a
different approach. The Java compiler (javac) does not produce native machine code. Instead, it
produces an intermediate representation called bytecode , stored in .class files. This bytecode is not tied
to any specific hardware; it is designed to be executed by the Java Virtual Machine (JVM). Every platform
that wants to run Java software needs its own JVM implementation, but that JVM understands the exact
same bytecode. This means a .class file compiled on a Windows machine will run unchanged on a Linux
server, a macOS laptop, or an embedded device, provided a compatible JVM is present.
1.2 The Java Platform: JDK, JRE, and JVM
These three acronyms are frequently confused by newcomers, so it is worth being precise about each:
l JVM (Java Virtual Machine) : An abstract computing machine that provides a runtime environment in
which Java bytecode can be executed. The JVM is responsible for loading class files, verifying
bytecode, allocating memory, executing instructions, and performing automatic garbage collection. The
JVM specification is implemented differently by different vendors (HotSpot from Oracle, OpenJ9 from
Eclipse, GraalVM, and others), but all implementations must honor the same bytecode contract.
l JRE (Java Runtime Environment) : A software package that provides everything needed to^ run^ a
Java application, but not to develop one. It bundles the JVM together with the core class libraries
(java.lang, java.util, java.io, and so on) and supporting files. If you only need to run a compiled
Java program, the JRE alone is sufficient.
l JDK (Java Development Kit) : A superset of the JRE that additionally includes the tools required to
develop Java software: the compiler (javac), the debugger (jdb), the archiver (jar), the documentation
generator (javadoc), and, since Java 9, the interactive shell jshell. Since Java 11, Oracle
restructured distribution so that the JDK is effectively the only thing you download; the JRE is no longer
distributed as a separate installable package by Oracle, though other vendors like Eclipse Temurin still
offer both.
1.3 Key Features of Java
Simple. Java removed several complexity-inducing features of C++ such as explicit pointer arithmetic,
multiple inheritance of classes (though multiple inheritance of interfaces is retained), operator overloading,
and manual memory management via malloc/free.
Object-Oriented. Nearly everything in Java is modeled as an object, with the notable exception of the
eight primitive types (byte, short, int, long, float, double, char, boolean), which exist for performance
reasons. Java strongly enforces encapsulation, inheritance, and polymorphism as first-class language
concepts.
Robust. Java performs extensive compile-time checking combined with runtime checking to eliminate
error-prone situations. Automatic garbage collection removes an entire category of memory bugs
(dangling pointers, double frees) that plague manually-managed languages. Exception handling provides
a structured mechanism to detect and manage runtime errors.
Secure. Java was designed with network-distributed applications in mind. The bytecode verifier checks
that loaded classes obey the language's safety rules before execution, the class loader isolates different
sources of code, and the security manager (historically) allowed fine-grained control over what untrusted
code was permitted to do.
Architecture-Neutral and Portable. As explained above, compiled bytecode does not depend on any
specific processor architecture.
Multithreaded. Java has built-in language-level and library-level support for concurrent programming via
the Thread class, the Runnable interface, synchronization primitives, and the modern
java.util.concurrent package.
High Performance. While early Java implementations were purely interpreted and comparatively slow,
modern JVMs use Just-In-Time (JIT) compilation, which translates frequently executed bytecode into
optimized native machine code at runtime, closing much of the historical performance gap with C/C++.
Dynamic. Java programs carry substantial runtime type information, enabling reflection, dynamic class
loading, and runtime linking of new code modules.
1.4 History and Version Timeline
Java's evolution has accelerated considerably in the last decade. A brief summary of major milestones:
l^1995 — Java 1.0 released publicly by Sun Microsystems.
l 1997–2000^ —^ Java^ 1.1^ through^ 1.3^ add^ inner^ classes,^ JDBC,^ Swing,^ and^ JIT^ compilation
improvements.
l^2004 — Java 5 (codenamed Tiger) is a watershed release, introducing generics, enhanced for-loops,
autoboxing/unboxing, enums, varargs, and annotations.
l^2011 — Java 7 adds try-with-resources, the diamond operator, and improved switch statements on
strings.
1.6 Anatomy of a Java Program
Breaking down the HelloWorld example line by line:
l public^ class^ HelloWorld^ {^ ...^ }^ declares a class named^ HelloWorld. In Java, all code must live
inside a class (or, since Java 21, inside an implicitly declared class for very short programs). The
public access modifier means this class is visible from any other class, in any package.
l public^ static^ void^ main(String[]^ args)^ {^ ...^ }^ declares the method that the JVM calls to start
execution. public makes it callable from outside the class; static means it belongs to the class itself
rather than to an instance, so the JVM can invoke it without first constructing an object; void means it
returns no value; String[] args receives command-line arguments passed when the program is
launched.
l System.out.println("Hello,^ World!");^ calls the^ println^ method on the^ out^ object, which is a
static field of the System class representing standard output. println prints its argument followed by
a newline character.
1.7 Comments and Documentation
Java supports three comment styles:
// Single-line comment
/* Multi-line comment */
/**
- Javadoc comment — used to generate HTML API documentation
- via the javadoc tool. Supports tags like @param, @return, @throws.
- @author Jane Doe
- @version 1. */ public class Example { }
Javadoc comments are a distinctive Java convention: nearly the entire standard library's official
documentation is generated directly from these comments embedded in the source code, which keeps
documentation and implementation tightly coupled.
CHAPTER 2: Variables, Data Types, and Operators
2.1 Primitive Data Types
Java is a statically typed language: every variable must be declared with a type before use, and that type
cannot change. Java defines exactly eight primitive types, each with a fixed size regardless of platform —
a deliberate design choice that guarantees portability.
Type Size Range / Notes Default
byte 8 bits -128 to 127 0
short 16 bits -32,768 to 32,767 0
int 32 bits -2,147,483,648 to
long 64 bits ~-9.2×10^18 to 9.2×10^
(suffix L)
0L
float 32 bits IEEE 754 single precision
(suffix f)
0.0f
double 64 bits IEEE 754 double precision
(default for decimals)
0.0d
char 16 bits Single Unicode character
(0 to 65,535)
'\u0000'
boolean 1 bit* true or false only false
byte b = 100; short s = 20000; int i = 100000; long l = 10000000000L; // L suffix required — literal exceeds int range float f = 3.14f; // f suffix required, otherwise treated as double double d = 3.14159265358979; char c = 'A'; boolean flag = true;
Unlike primitives, every other type in Java — including arrays and every class you write or use — is a
reference type. A reference variable holds the memory address of an object on the heap, not the object
itself.
2.2 Type Casting and Conversion
Java distinguishes between widening (implicit) conversions, which never lose information, and
narrowing (explicit) conversions, which may lose precision and therefore require an explicit cast.
int i = 100; long l = i; // widening: automatic, always safe double d = l; // widening: long -> double automatic
double pi = 3.99; int truncated = (int) pi; // narrowing: explicit cast required, result = 3 (truncates, does not round)
int big = 130; byte overflowed = (byte) big; // narrowing beyond byte range wraps around: result = -
// Classic switch — requires break to prevent fall-through int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Some other day"); }
// Modern switch expression (Java 14+) — no fall-through, can return a value String dayName = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; default -> "Unknown"; };
Loops: for, while, do-while, enhanced for
for (int i = 0; i < 5; i++) { System.out.println(i); }
int count = 0; while (count < 5) { System.out.println(count); count++; }
int n = 0; do { System.out.println(n); // always executes at least once n++; } while (n < 5);
int[] numbers = {10, 20, 30}; for (int num : numbers) { // enhanced for-each, read-only iteration System.out.println(num); }
break exits the nearest enclosing loop or switch entirely; continue skips to the next iteration of the
nearest enclosing loop. Both can be combined with labels to target an outer loop directly:
outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) continue outer; System.out.println(i + "," + j); } }
2.5 Arrays
Arrays in Java are fixed-size, zero-indexed, homogeneous containers, and — unlike C — they are
themselves objects with a length field, and every access is automatically bounds-checked at runtime (an
out-of-range access throws ArrayIndexOutOfBoundsException rather than corrupting memory).
int[] scores = new int[5]; // array of 5 ints, all initialized to 0 scores[0] = 95; int[] literal = {10, 20, 30, 40}; // array literal, length inferred as 4 System.out.println(literal.length); // 4 — note: length is a field, not a method
// Multidimensional arrays are arrays of arrays int[][] grid = new int[3][3]; grid[1][2] = 7;
int[][] jagged = new int[3][]; // rows can have different lengths jagged[0] = new int[]{1}; jagged[1] = new int[]{1, 2, 3};
// Useful helpers in java.util.Arrays int[] copy = Arrays.copyOf(literal, literal.length); Arrays.sort(literal); System.out.println(Arrays.toString(literal)); // [10, 20, 30, 40] System.out.println(Arrays.deepToString(jagged)); // handles nested arrays
2.6 Strings
String in Java is a reference type, backed since Java 9 by a byte[] (previously char[]), and — critically
— immutable : once created, a String object's contents can never change. Every apparent "modification"
(concatenation, substring, replace, and so on) actually returns a brand-new String object.
String greeting = "Hello"; String upper = greeting.toUpperCase(); // "HELLO" — greeting itself is unchanged String combined = greeting + ", World!"; // concatenation creates a new String
System.out.println(greeting.length()); // 5 System.out.println(greeting.charAt(1)); // 'e' System.out.println(greeting.substring(1, 3)); // "el" System.out.println(greeting.indexOf('l')); // 2 System.out.println(greeting.replace('l', 'L'));// "HeLLo" System.out.println(greeting.equals("Hello")); // true — content comparison System.out.println(greeting == "Hello"); // often true due to string pooling, but unreliable — never re System.out.println(" padded ".trim()); // "padded" System.out.println(String.join(", ", "a", "b", "c")); // "a, b, c"
Because String immutability means repeated concatenation in a loop creates many throwaway
intermediate objects, Java provides mutable alternatives for performance-sensitive text building:
StringBuilder sb = new StringBuilder(); for (int i = 0; i < 5; i++) { sb.append(i).append(","); } String result = sb.toString(); // "0,1,2,3,4,"
StringBuilder is not thread-safe but fast; its older sibling StringBuffer has the identical API but
synchronizes every method, making it thread-safe at a performance cost. In modern code, StringBuilder
is almost always the right choice unless the same buffer is genuinely shared across threads.
2.7 The var Keyword (Local Variable Type Inference)
Since Java 10, the compiler can infer the type of a local variable from its initializer using var, reducing
boilerplate without sacrificing static typing — the type is still fixed at compile time, it is simply not written
out explicitly.
CHAPTER 3: Classes, Objects, and Constructors
Figure 3.1 — The four pillars of object-oriented programming
3.1 Classes and Objects
A class is a blueprint that defines the state (fields) and behavior (methods) that its instances will have. An
object is a concrete instance of a class, created at runtime and living on the heap. The relationship is
analogous to an architectural blueprint versus the actual houses built from it — one blueprint, many
houses, each with its own address (identity) even if built identically.
public class Car { // Fields (instance variables) — each object gets its own copy private String model; private int year; private double price;
// Constructor — initializes a new object public Car(String model, int year, double price) { this.model = model; // 'this' disambiguates the field from the parameter this.year = year; this.price = price; }
// Methods define behavior public void displayInfo() { System.out.println(year + " " + model + " - $" + price); }
public double applyDiscount(double percent) { return price - (price * percent / 100); } }
public class Main {
public static void main(String[] args) { Car car1 = new Car("Civic", 2023, 25000); Car car2 = new Car("Model 3", 2024, 42000); car1.displayInfo(); // 2023 Civic - $25000. car2.displayInfo(); // 2024 Model 3 - $42000. } }
3.2 Constructors in Depth
A constructor shares its name with the class and has no return type, not even void. Its job is to bring a
new object into a valid initial state. Key rules:
l If a class defines no constructor at all, the compiler silently supplies a public, no-argument^ default
constructor that does nothing beyond calling the superclass's constructor.
l The moment you write^ any^ constructor yourself, the compiler no longer provides the default one — if
you still want a no-argument constructor, you must write it explicitly.
l Constructors^ can^ be^ overloaded^ (multiple^ constructors^ with^ different^ parameter^ lists),^ and^ one
constructor can call another in the same class using this(...) as the very first statement, avoiding
duplicated initialization logic.
public class Rectangle { private double width, height;
public Rectangle(double width, double height) { this.width = width; this.height = height; }
public Rectangle(double side) { this(side, side); // delegates to the two-arg constructor -> a square }
public Rectangle() { this(1.0, 1.0); // delegates again } }
3.3 Instance Members vs Static Members
Every field and method belongs either to individual instances or to the class as a whole:
public class Counter { private static int totalCount = 0; // shared across ALL instances private int id; // unique per instance
public Counter() { totalCount++; this.id = totalCount; }
public static int getTotalCount() { // static methods cannot access instance fields directly return totalCount; }
public int getId() {
Dog rex = new Dog("Rex"); rex.eat(); // inherited from Animal: "Rex is eating." rex.makeSound(); // overridden: "Rex barks: Woof!" rex.fetch(); // defined in Dog only
Every class in Java implicitly extends java.lang.Object if no other superclass is specified, either directly
or transitively. Object supplies default implementations of methods every object has, including
toString(), equals(Object), hashCode(), and getClass().
If a subclass constructor does not explicitly call super(...), the compiler inserts an implicit call to the
superclass's no-argument constructor as the first statement — which fails to compile if the superclass has
no such constructor available.
3.6 Method Overriding vs Method Overloading
These two mechanisms are often confused but are fundamentally different:
Overriding — a subclass provides a new implementation of a method already defined in its superclass,
with an identical signature (name, parameter types, and count). It is resolved at runtime based on the
actual object type (dynamic dispatch), and is what enables polymorphism.
Overloading — multiple methods in the same class share a name but differ in parameter list (type,
number, or order of parameters). It is resolved at compile time based on the arguments provided.
public class Calculator { // Overloading: same name "add", different parameter lists public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } }
The @Override annotation is optional but strongly recommended on every overriding method: it instructs
the compiler to verify that a matching superclass or interface method actually exists, catching typos (e.g.,
equal instead of equals) that would otherwise silently create a new overloaded method instead of
overriding anything.
3.7 The Object Class Contract: equals, hashCode, toString
Correctly overriding equals() and hashCode() together is one of the most important — and most
frequently botched — tasks in everyday Java code, because broken implementations silently corrupt
hash-based collections like HashMap and HashSet.
public class Point { private final int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Point)) return false; Point p = (Point) o; return x == p.x && y == p.y;
@Override public int hashCode() { return Objects.hash(x, y); // combines fields consistently with equals }
@Override public String toString() { return "Point(" + x + ", " + y + ")"; } }
The governing contract, which must never be violated: (1) if a.equals(b) is true, then a.hashCode() ==
b.hashCode() must also be true; (2) equals must be reflexive, symmetric, transitive, and consistent; (3)
hashCode need not produce different values for unequal objects, but doing so improves hash table
performance. Since Java 14, records (covered in Chapter 20) generate correct equals, hashCode, and
toString automatically for simple data-carrier classes, eliminating this entire category of bugs for the
common case.
System.out.println(name + "'s pay: $" + calculatePay()); }
// Abstract method — no body; each subclass MUST supply its own public abstract double calculatePay(); }
public class SalariedEmployee extends Employee { public SalariedEmployee(String name, double baseSalary) { super(name, baseSalary); } @Override public double calculatePay() { return baseSalary; } }
public class CommissionEmployee extends Employee { private double commission; public CommissionEmployee(String name, double base, double commission) { super(name, base); this.commission = commission; } @Override public double calculatePay() { return baseSalary + commission; } }
Use an abstract class when related types share meaningful common state or behavior and there is a clear
"is-a" relationship — abstract classes support constructors, instance fields, and access modifiers that pure
interfaces historically could not.
4.3 Interfaces
An interface defines a contract — a set of method signatures that implementing classes agree to provide
— without (traditionally) supplying any implementation. Unlike classes, a single class can implement any
number of interfaces , which is Java's primary mechanism for something resembling multiple inheritance.
public interface Payable { double calculatePay(); // implicitly public abstract } public interface Reportable { void generateReport(); }
public class Contractor implements Payable, Reportable { private double hourlyRate, hoursWorked; public Contractor(double rate, double hours) { hourlyRate = rate; hoursWorked = hours; }
@Override public double calculatePay() { return hourlyRate * hoursWorked; } @Override public void generateReport() { System.out.println("Contractor paid: $" + calculatePay()); } }
Since Java 8, interfaces may also define default methods (with a body, providing a fallback
implementation that implementing classes can inherit or override) and static methods (called on the
interface itself). Since Java 9, interfaces can also have private methods , used to share code between
default methods without exposing it publicly.
public interface Vehicle { void drive();
default void honk() { // default method — has a body System.out.println("Beep beep!"); }
static Vehicle createDefault() { // static factory method on the interface return () -> System.out.println("Driving a generic vehicle"); } }
Default methods were introduced specifically to let library designers add new methods to existing
interfaces (like java.util.Collection) without breaking every class that already implemented them
across the ecosystem.
4.4 Abstract Class vs Interface — When to Choose Which
Aspect Abstract Class Interface
Instantiation Never Never
Multiple inheritance A class extends only one A class implements many
Constructors Yes No
Instance fields (state) Yes, any access modifier Only public static final
constants
Method bodies Any method can have one Only default, static, private
methods
Access modifiers on methods Any Implicitly public (abstract methods)
Typical use Shared base implementation among
closely related types
A capability/contract unrelated types
can opt into
A common guideline: prefer interfaces to describe what something can do (Comparable, Runnable,
Serializable), and reserve abstract classes for what something fundamentally is , when you also need to
share real state or partial implementation.
4.5 Sealed Classes and Interfaces (Java 17+)
Sealed types restrict which other classes or interfaces are permitted to extend or implement them, giving
the author of a hierarchy exhaustive control over its shape — useful for domain modeling where you want
the compiler to guarantee every subtype is accounted for.
public sealed interface Shape permits Circle, Square, Triangle { }
public final class Circle implements Shape { /* ... / } public final class Square implements Shape { / ... */ } public non-sealed class Triangle implements Shape { } // non-sealed reopens extension
Combined with pattern matching for switch (finalized in Java 21), sealed hierarchies let the compiler
verify a switch covers every possible subtype with no default branch needed, catching missing cases at
compile time rather than at runtime.