Java Comprehensive Guide
Java Comprehensive Guide
■
Comprehensive
Java
Programming
Guide
From First [Link] to Recursion & OOP
Sections 1–18 · CS Definitions · Code Examples · All Skill Levels
Compiled · Statically Typed · Object-Oriented · Write Once Run Anywhere
Page 1
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Table of Contents
§1 Basics
[Link], output, what is Java, compilation
§2 Data Types & Type Casting
int, double, boolean, char, String + casting
§3 Loops
for, while, do-while, for-each, break/continue
§4 Nested Structures & Scope
nesting, block scope, variable shadowing
§5 Operations
arithmetic, Math library, concatenation, shorthand
§6 Methods & Parameters
methods, parameters, arguments, overloading, signatures
§7 Input
Scanner, tokens, nextInt/nextLine, parsing
§8 Conditionals
if / else if / else, switch, ternary
§9 String Formatting & printf
printf, [Link], format specifiers
§10 Random
[Link](), Random class, seeding
§11 Algorithm Principles
Boolean zen, assertions, lookahead, fencepost, DeMorgan
§12 File Processing
Scanner on files, PrintWriter, try-with-resources
§13 Arrays
array properties, value/reference, 2-D arrays
§14 ArrayList, HashMap & More
ArrayList, HashMap, Set, Collections utility
§15 Objects & Classes
fields, constructors, this, static vs instance
§16 The Big 4
abstraction, inheritance, polymorphism, encapsulation
§17 Sorting & Searching
[Link], comparators, binary search, algorithms
§18 Recursion
base case, call stack, classic problems, memoization
Page 2
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
§1 Basics
[Link] · output · what is Java · compilation · structure
What is Java?
Java is a high-level, class-based, object-oriented, statically-typed, compiled+interpreted programming
language developed by Sun Microsystems (now Oracle) in 1995. Its mantra is Write Once, Run
Anywhere (WORA) — Java source code compiles to platform-independent bytecode that runs on any
machine with a Java Virtual Machine (JVM).
Key CS Definitions
Compiled Language
Source code (.java) is translated by the compiler (javac) into bytecode (.class files) before
execution.
Interpreted / JVM
The JVM interprets or JIT-compiles bytecode to native machine instructions at runtime.
Statically Typed
Every variable must have a declared type at compile time. The compiler catches type errors before
the program runs.
Object-Oriented
Everything in Java is organised around classes and objects. Even the entry point is inside a class.
Strongly Typed
Types are strictly enforced; implicit conversions that could lose data are not allowed without an
explicit cast.
Statement
A single instruction ending with a semicolon: int x = 5;
Expression
A combination of values, variables, and operators that evaluates to a value: 2 + 3, x * y.
Page 3
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Every Java program needs: (1) a public class matching the filename, (2) a main method with the exact
signature shown above, (3) statements inside main that execute top-to-bottom.
[Link] vs [Link]
// println — prints and moves to the next line
[Link]("Hello, World!");
[Link]("Second line");
// Printing expressions
[Link](2 + 3); // 5
[Link]("Sum: " + (2+3)); // Sum: 5
Comments
// Single-line comment
/*
* Multi-line comment
* Used for block explanations
*/
/**
* Javadoc comment — generates API documentation
* @param args command-line arguments
*/
public static void main(String[] args) { }
Page 4
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
javac com/example/[Link]
java [Link]
■ Common beginner errors: (1) filename doesn't match class name, (2) missing semicolon, (3) wrong
capitalisation of System/String/main.
Page 5
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Primitive Types
byte 8-bit signed integer. Range: -128 to 127.
int 32-bit signed integer. Range: ~-2.1B to ~2.1B. Most common integer
type.
Page 6
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
[Link]([Link](0)); // A
[Link]([Link]()); // ALICE
[Link]([Link]()); // alice
[Link](" hello ".trim()); // "hello"
[Link]([Link](1, 3)); // li (end exclusive)
[Link]([Link]("lic")); // true
[Link]([Link]("Al","EL")); // ELice
[Link]([Link]("i")); // 2
[Link]("a,b,c".split(",")[1]); // b
Wrapper Classes
Each primitive has a corresponding wrapper class that provides utility methods and allows primitives to
be used where Objects are required (e.g., ArrayList).
// Parsing strings
int n = [Link]("123");
double d = [Link]("3.14");
// Converting to String
String s1 = [Link](42);
String s2 = [Link](3.14);
String s3 = "" + 42; // concatenation trick
Type Casting
Widening (Implicit)
Page 7
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Automatic conversion from smaller to larger type: int → long → double. Safe, no data loss.
Narrowing (Explicit)
Manual cast from larger to smaller type. Can lose data. Syntax: (type) value.
// Widening — automatic
int i = 42;
double d = i; // 42.0 — safe
// Overflow
int max = Integer.MAX_VALUE; // 2147483647
[Link](max + 1); // -2147483648 (overflow wraps!)
■ Java does NOT automatically convert between boolean and int (unlike C/Python). You cannot write: if (1) {...}
Page 8
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
§3 Loops
for · while · do-while · for-each · break · continue · labels
// Counting down
for (int i = 10; i >= 1; i--) {
[Link](i + " "); // 10 9 8 7 6 5 4 3 2 1
}
// Step by 2
for (int i = 0; i <= 20; i += 2) {
[Link](i + " "); // 0 2 4 6 8 10 12 14 16 18 20
}
// Multiple variables
for (int i = 0, j = 10; i < j; i++, j--) {
[Link](i + " " + j); // 0 10, 1 9, 2 8, 3 7, 4 6
}
while Loop
Repeats while a condition is true. Use when you don't know the iteration count in advance.
int count = 0;
while (count < 5) {
Page 9
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
[Link](count);
count++; // must update condition var!
}
do-while Loop
Like while, but the body executes AT LEAST ONCE before checking the condition. Useful for menus and
input prompts.
int choice;
do {
[Link]("1. Start 2. Help 3. Quit");
[Link]("Choice: ");
choice = [Link]();
} while (choice < 1 || choice > 3);
Page 10
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
// 0,0
// 1,0
// 2,0
■ Avoid labeled breaks in production code — they hurt readability. Refactor into a method instead.
Page 11
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Nested Loops
// Multiplication table
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
[Link]("%4d", i * j);
}
[Link]();
}
// 1 2 3
// 2 4 6
// 3 6 9
// Triangle pattern
for (int row = 1; row <= 5; row++) {
for (int col = 1; col <= row; col++) {
[Link]("* ");
}
[Link]();
}
Nested Conditionals
int x = 15;
if (x > 0) {
if (x % 2 == 0) {
[Link]("positive even");
} else {
[Link]("positive odd"); // printed
}
} else {
[Link]("non-positive");
}
Scope in Java
Scope
The region of code where a variable is visible and accessible. Java uses block scope — a variable
exists from its declaration to the closing } of its block.
public class ScopeDemo {
static int classLevel = 100; // class-level (field) scope
Page 12
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
if (true) {
int blockLevel = 5; // block scope
[Link](blockLevel);// 5 (visible here)
[Link](methodLevel);// 10 (outer scope visible)
}
// [Link](blockLevel); // ERROR — out of scope!
Variable Shadowing
A local variable can shadow (hide) a field with the same name. Use this to refer to the field inside
instance methods.
public class Person {
String name = "default"; // field
Page 13
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
§5 Operations
arithmetic · comparison · logical · bitwise · Math class · shorthand
Arithmetic Operators
+ Addition: 5 + 3 = 8
- Subtraction: 5 - 3 = 2
* Multiplication: 5 * 3 = 15
% Modulus (remainder): 7 % 3 = 1
// Modulus
[Link](10 % 3); // 1
[Link](15 % 2 == 0); // false — odd check
int b = 5;
[Link](++b); // 6 (increments then uses)
[Link](b); // 6
// Logical
Page 14
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
// String concatenation
String s = "Hello";
s += " World"; // "Hello World"
Operator Precedence
Highest to lowest: () → ++ -- (unary) → * / % → + - → comparisons → == != → && → || → = (assignment)
■ Integer division is Java's #1 beginner bug. Always check: if both operands are int, the result is int. Cast at least
one to double when you need decimals.
Page 15
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Defining Methods
Method
A named, reusable block of code that belongs to a class. Every Java method must be inside a class.
Return Type
The type of value the method returns. Use void if it returns nothing.
Method Signature
The name plus its parameter types: add(int, int). Return type is NOT part of the signature.
// Syntax: [modifiers] returnType methodName(paramType paramName, ...) { body }
Parameters vs Arguments
Parameter
Variable in the method definition (the placeholder): int a, int b.
Argument
Actual value passed at the call site: add(3, 5) — 3 and 5 are arguments.
Pass-by-Value
Java is ALWAYS pass-by-value. For primitives, a copy of the value is passed. For objects, a copy of the
REFERENCE (memory address) is passed — so you can mutate the object's contents, but you cannot
make the caller's variable point elsewhere.
public static void tryChange(int x) {
x = 999; // changes the LOCAL copy only
}
Page 16
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Method Overloading
Overloading allows multiple methods with the SAME name but DIFFERENT parameter lists (different
types, count, or order). The compiler picks the right version at compile time.
public static double area(double radius) { // circle
return [Link] * radius * radius;
}
public static double area(double width, double height) { // rectangle
return width * height;
}
public static double area(double a, double b, double c) { // triangle (Heron)
double s = (a + b + c) / 2;
return [Link](s * (s-a) * (s-b) * (s-c));
}
Page 17
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Javadoc
/**
* Converts Celsius to Fahrenheit.
*
* @param celsius the temperature in Celsius
* @return the equivalent temperature in Fahrenheit
*/
public static double toFahrenheit(double celsius) {
return celsius * 9.0 / 5.0 + 32;
}
Page 18
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
§7 Input
Scanner class · tokens · nextInt/nextLine · parsing · validation
[Link]("Pass/Fail? ");
boolean pass = [Link](); // reads "true" or "false"
nextLine() Pitfall
After nextInt()/nextDouble(), a newline character stays in the buffer. Call [Link]() once to
consume it before reading a full line.
Scanner sc = new Scanner([Link]);
int n = [Link]();
[Link](); // consume leftover newline!
String line = [Link](); // now reads correctly
Page 19
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
hasNext Methods
// Read until end of input
Scanner sc = new Scanner([Link]);
int sum = 0;
while ([Link]()) {
sum += [Link]();
}
[Link]("Sum: " + sum);
■ Always match the Scanner method to the data type expected. Calling nextInt() when the user types 'abc'
throws InputMismatchException.
Page 20
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
§8 Conditionals
if · else if · else · switch · switch expressions · ternary
if / else if / else
int score = 85;
String grade;
Ternary Operator
Compact single-expression conditional: condition ? valueIfTrue : valueIfFalse
int age = 20;
String status = (age >= 18) ? "adult" : "minor";
[Link](status); // adult
switch Statement
Switch tests a single value against multiple cases. More efficient than a long if-else chain when
comparing a variable to many constants.
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
Page 21
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
[Link]("Wednesday");
break;
// fall-through: no break means execution continues!
case 4:
case 5:
[Link]("Thu or Fri");
break;
default:
[Link]("Weekend");
}
■ Always include a default case in switch statements. Missing break; causes fall-through — a common,
hard-to-find bug.
Page 22
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Format Specifiers
%d int / long — decimal integer: 42
%b boolean
%n Platform newline
%o Integer as octal
double pi = 3.14159265;
// Integer formatting
int n = 1234567;
Page 23
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
// String formatting
[Link]("%-15s|%s%n", "Alice", "Score");
[Link]("%-15s|%d%n", "Bob", 92);
StringBuilder
For building strings in a loop, use StringBuilder instead of + concatenation. String + in a loop creates a
new String object every iteration — O(n²). StringBuilder is O(n).
// Inefficient — creates many intermediate String objects
String result = "";
for (int i = 0; i < 10; i++) {
result += i + " "; // BAD in tight loops!
}
// Efficient
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
[Link](i);
[Link](" ");
}
[Link]([Link]()); // 0 1 2 3 4 5 6 7 8 9
Page 24
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
§10 Random
[Link]() · Random class · seeding · SecureRandom
[Link]()
The simplest way to get a random number. Returns a double in [0.0, 1.0).
// [0.0, 1.0)
double r = [Link]();
// [0, n) integer
int roll = (int)([Link]() * 6); // 0–5
[Link]
The Random class provides more control: seeding, Gaussian, and nextXxx() methods.
import [Link];
// Generating numbers
[Link]([Link]()); // any int
[Link]([Link](10)); // [0, 10)
[Link]([Link](6) + 1); // die: [1,6]
[Link]([Link]()); // [0.0, 1.0)
[Link]([Link]()); // true or false
[Link]([Link]()); // mean=0, std=1
Seeding
Using the same seed produces the same sequence every run — essential for testing, simulations, and
reproducible results.
Random r1 = new Random(99);
Random r2 = new Random(99);
[Link]([Link](100)); // same
Page 25
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
[Link]([Link](100)); // same
[Link]([Link](100)); // same
[Link]([Link](100)); // same
SecureRandom (Cryptographic)
import [Link];
Page 26
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Boolean Zen
Avoid comparing booleans to true/false — the boolean IS the condition.
boolean isValid = true;
// BAD
if (isValid == true) { /* ... */ }
if (found == false) { /* ... */ }
// GOOD
if (isValid) { /* ... */ }
if (!found) { /* ... */ }
// GOOD
public static boolean isEven(int n) {
return n % 2 == 0;
}
Assertions
Java has a built-in assert statement for debugging. It's disabled by default; enable with the -ea JVM flag.
// assert expression : message;
public static double divide(double a, double b) {
assert b != 0 : "Denominator cannot be zero, got b=" + b;
return a / b;
}
// Checking postcondition
assert result >= 0 && result < [Link] : "Index out of range: " + result;
■ Never use assert for user-input validation — use if/throw instead. Assertions are for internal consistency
checks during development.
Page 27
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Fencepost Problem
The off-by-one error: n sections need n+1 posts. Applies whenever you print separators between items.
String[] fruits = {"apple", "banana", "cherry"};
Lookahead
Examine the NEXT element before deciding what to do with the current one.
int[] nums = {1, 2, 2, 3, 4, 4, 4, 5};
DeMorgan's Laws
!(A && B) ≡ !A || !B
!(A || B) ≡ !A && !B
int x = 3, y = 8;
// Original
if (!(x > 5 && y < 10)) [Link]("DeMorgan 1");
// Equivalent by DeMorgan
if (x <= 5 || y >= 10) [Link]("DeMorgan 1");
Page 28
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Page 29
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
try-with-resources (Recommended)
Java 7+ feature that automatically closes resources (files, connections). The resource is closed even if
an exception is thrown.
// try-with-resources — auto-closes the Scanner
try (Scanner sc = new Scanner(new File("[Link]"))) {
while ([Link]()) {
String line = [Link]();
[Link](line);
}
} // [Link]() called automatically here
catch (FileNotFoundException e) {
[Link]("Error: " + [Link]());
}
Page 30
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
// Mixed tokens
// File: "Alice 95
Bob 82
Carol 91"
try (Scanner sc = new Scanner(new File("[Link]"))) {
while ([Link]()) {
String name = [Link](); // next token as String
int score = [Link](); // next token as int
[Link]("%-10s %d%n", name, score);
}
} catch (FileNotFoundException e) { /* handle */ }
Appending to Files
import [Link];
import [Link];
Page 31
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
[Link]();
}
Page 32
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
§13 Arrays
declaration · properties · value/reference semantics · 2D arrays · Arrays class
Array Basics
Array
A fixed-size, ordered collection of elements of the SAME type. O(1) index access.
// Declaration and initialization
int[] nums = new int[5]; // [0, 0, 0, 0, 0] — default 0
int[] primes = {2, 3, 5, 7, 11}; // literal syntax
String[] names = new String[3]; // [null, null, null]
// Access (0-indexed)
[Link](primes[0]); // 2
[Link](primes[4]); // 11
primes[2] = 99; // mutation
// Iterate
for (int n : primes) {
[Link](n + " ");
}
Page 33
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
// Sorting
[Link](arr);
[Link]([Link](arr)); // [1, 2, 3, 5, 8, 9]
// Fill
[Link](arr, 0);
[Link]([Link](arr)); // [0, 0, 0, 0, 0, 0]
// Equality check
int[] a = {1,2,3}, b = {1,2,3};
[Link](a == b); // false (different objects)
[Link]([Link](a, b)); // true (same contents)
2D Arrays
// Rectangular 2D array
int[][] grid = new int[3][4]; // 3 rows, 4 columns
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Traverse
for (int r = 0; r < [Link]; r++) {
for (int c = 0; c < matrix[r].length; c++) {
[Link]("%3d", matrix[r][c]);
}
[Link]();
Page 34
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
■ ArrayIndexOutOfBoundsException is the most common Java runtime error. Always check: valid indices are 0
to [Link] - 1.
Page 35
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
ArrayList
ArrayList is a resizable array. Unlike arrays, it can grow and shrink dynamically. It can only hold Objects
(not primitives — use wrapper classes).
import [Link];
// Adding
[Link]("Alice");
[Link]("Bob");
[Link]("Carol");
[Link](1, "Dave"); // insert at index 1
// Access
[Link]([Link](0)); // Alice
[Link]([Link]()); // 4
[Link]([Link]("Bob")); // true
[Link]([Link]("Carol")); // 2
// Modification
[Link](0, "Anna"); // replace at index 0
[Link]("Bob"); // remove by value
[Link](2); // remove by index
// Iterate
for (String name : list) {
[Link](name);
}
HashMap
HashMap stores key-value pairs. Keys must be unique. Average O(1) for get/put/remove. Keys and
values must be Objects.
import [Link];
Page 36
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
// Adding / updating
[Link]("Alice", 95);
[Link]("Bob", 82);
[Link]("Carol", 91);
[Link]("Alice", 98); // overwrites 95
// Access
[Link]([Link]("Alice")); // 98
[Link]([Link]("Dave")); // null
[Link]([Link]("Dave", 0)); // 0
// Checking
[Link]([Link]("Bob")); // true
[Link]([Link](91)); // true
[Link]([Link]()); // 3
// Remove
[Link]("Bob");
// Iterating
for (String name : [Link]()) {
[Link](name + ": " + [Link](name));
}
for (var entry : [Link]()) {
[Link]([Link]() + " -> " + [Link]());
}
HashSet
HashSet stores unique elements. O(1) add/remove/contains. Unordered.
import [Link];
[Link]([Link]()); // 2
[Link]([Link]("Rome")); // false
[Link]("London");
Page 37
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
[Link](nums); // [1, 2, 5, 8, 9]
[Link](nums); // [9, 8, 5, 2, 1]
[Link](nums); // random order
[Link]([Link](nums)); // smallest
[Link]([Link](nums)); // largest
[Link](nums, 0); // all zeros
Page 38
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Object
An instance of a class — a concrete entity created with new.
Field
A variable declared at class level. Represents object state.
Constructor
Special method called when an object is created with new. Same name as class, no return type.
this
Reference to the current object. Used to resolve field/parameter name conflicts.
public class Dog {
// Instance fields — each Dog object has its own
private String name;
private int age;
private String breed;
// Constructor
public Dog(String name, int age, String breed) {
[Link] = name; // [Link] = field, name = parameter
[Link] = age;
[Link] = breed;
totalDogs++;
}
// Getters
public String getName() { return name; }
public int getAge() { return age; }
public String getBreed() { return breed; }
Page 39
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
// Instance method
public String bark() {
return name + " says: Woof!";
}
// Static method
public static int getTotalDogs() {
return totalDogs;
}
// Usage
Dog d1 = new Dog("Rex", 3, "German Shepherd");
Dog d2 = new Dog("Fluffy", 1, "Poodle");
[Link]([Link]()); // Rex says: Woof!
[Link](d1); // Dog[Rex, 3yo, German Shepherd]
[Link]([Link]()); // 2
[Link](d1 == d2); // false (different refs)
[Link]([Link](d2)); // false (different content)
Page 40
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
@Override
public String toString() {
return [Link]("(%.1f, %.1f)", x, y);
}
}
Page 41
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
1. Encapsulation
Encapsulation
Bundling data (fields) and methods together, and restricting direct access to fields via
private/protected + getters/setters. Protects invariants.
public class BankAccount {
private String owner;
private double balance; // private — hidden from outside
@Override
public String toString() {
return owner + ": $" + [Link]("%.2f", balance);
}
}
2. Inheritance
Inheritance
A subclass (child) extends a superclass (parent), inheriting its non-private fields and methods. Use
extends. Java supports single inheritance (one parent only).
public class Animal {
protected String name;
protected int age;
Page 42
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
@Override
public String speak() { // override parent
return "Woof!";
}
public String fetch() {
return name + " fetches the ball!";
}
}
3. Polymorphism
Polymorphism
Page 43
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
'Many forms'. The ability for objects of different types to respond to the same method call in different
ways. Achieved through method overriding and interfaces.
// All Animals treated uniformly
Animal[] animals = {
new Dog("Rex", 3, "Lab"),
new Cat("Luna", 2),
new Dog("Buddy", 1, "Poodle")
};
4. Abstraction
Abstraction
Hiding implementation details and exposing only the essential interface. Java provides abstract
classes and interfaces for this.
// Abstract class — cannot be instantiated
public abstract class Shape {
protected String color;
Page 44
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
}
}
Page 45
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Big O Complexity
O(1) Constant: array index, HashMap get
[Link] — Built-in
import [Link];
import [Link];
// Reverse order
[Link](words, [Link]());
// Sort ArrayList
ArrayList<Integer> list = new ArrayList<>([Link](5,2,8,1));
[Link](list);
[Link]([Link]()); // reverse
Page 46
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
// Manual implementation
public static int binarySearch(int[] arr, int target) {
int low = 0, high = [Link] - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // avoids overflow!
if (arr[mid] == target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
Page 47
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
}
}
Page 48
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
§18 Recursion
base case · recursive case · call stack · memoization · classic problems
What is Recursion?
A method calls itself to solve a smaller version of the same problem. Every recursive solution needs:
// Trace: factorial(4)
// = 4 * factorial(3)
// = 4 * 3 * factorial(2)
// = 4 * 3 * 2 * factorial(1)
// = 4 * 3 * 2 * 1 * factorial(0)
// = 4 * 3 * 2 * 1 * 1 = 24
[Link](factorial(5)); // 120
Fibonacci
// Naive — O(2^n)
public static int fib(int n) {
if (n <= 1) return n;
return fib(n-1) + fib(n-2);
}
// Memoized — O(n)
private static Map<Integer,Long> memo = new HashMap<>();
public static long fibMemo(int n) {
if (n <= 1) return n;
if ([Link](n)) return [Link](n);
Page 49
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Tower of Hanoi
public static void hanoi(int n, char src, char dst, char aux) {
if (n == 1) {
Page 50
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples
Stack depth Java's stack is limited. Deep recursion needs tail-call opt. or iteration.
Best uses Trees, graphs, divide & conquer, backtracking, parsing — recursion
shines.
End of Guide
You have covered all 18 sections of the Comprehensive Java Programming Guide.
Happy coding! ■
Page 51