[Go to site: main page, start]

0% found this document useful (0 votes)
4 views51 pages

Java Comprehensive Guide

The Comprehensive Java Programming Guide covers a wide range of topics from basic syntax to advanced concepts like recursion and object-oriented programming. It includes detailed sections on data types, loops, conditionals, file processing, and algorithm principles, making it suitable for all skill levels. The guide emphasizes Java's key features such as being statically typed, compiled, and its mantra of 'Write Once, Run Anywhere'.

Uploaded by

entity9993
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views51 pages

Java Comprehensive Guide

The Comprehensive Java Programming Guide covers a wide range of topics from basic syntax to advanced concepts like recursion and object-oriented programming. It includes detailed sections on data types, loops, conditionals, file processing, and algorithm principles, making it suitable for all skill levels. The guide emphasizes Java's key features such as being statically typed, compiled, and its mantra of 'Write Once, Run Anywhere'.

Uploaded by

entity9993
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples


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

Covers: Basics · Data Types · Loops · Scope · Operations · Methods


Input · Conditionals · String Formatting · Random · Algorithm Principles
File I/O · Arrays · ArrayList/HashMap · OOP · Big 4 · Sorting · Recursion

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.

Anatomy of a Java Program


// File: [Link]
public class Hello { // Class name MUST match filename
public static void main(String[] args) { // Entry point
[Link]("Hello, World!"); // Statement
}
}

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");

// print — prints WITHOUT a newline


[Link]("Hello, ");
[Link]("World!"); // same line: Hello, World!

// printf — formatted output (covered in Section 9)


[Link]("Pi = %.2f%n", 3.14159); // Pi = 3.14

// Printing different types


[Link](42);
[Link](3.14);
[Link](true);
[Link]('A');

// 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) { }

Compiling and Running


Java requires two steps: compile with javac, then run with java.
# In terminal:
javac [Link] # produces [Link]
java Hello # runs the program (no .class extension!)

# If your class is in a package:

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

§2 Data Types & Type Casting


primitive types · String · wrapper classes · casting · overflow

Primitive Types
byte 8-bit signed integer. Range: -128 to 127.

short 16-bit signed integer. Range: -32,768 to 32,767.

int 32-bit signed integer. Range: ~-2.1B to ~2.1B. Most common integer
type.

long 64-bit signed integer. Suffix L: 9_000_000_000L

float 32-bit IEEE 754 floating-point. Suffix f: 3.14f

double 64-bit IEEE 754 floating-point. Default decimal type: 3.14159

boolean true or false only (not 0/1 like C).

char 16-bit Unicode character. Single quotes: 'A', '\n', '\u0041'

int age = 25;


long population = 8_000_000_000L; // L suffix required
double pi = 3.14159265;
float tax = 0.075f; // f suffix required
boolean isOpen = true;
char grade = 'A';

// Integer literals in different bases


int hex = 0xFF; // 255
int binary = 0b1010; // 10
int big = 1_000_000; // underscores for readability

// Default values (in class fields, NOT local variables)


// int → 0, double → 0.0, boolean → false, char → \u0000

String — Reference Type


String is NOT a primitive — it is a class. Strings are immutable: every modification creates a new object.
String literals are stored in the String Pool.
String name = "Alice";
String greeting = "Hello, " + name + "!"; // concatenation

// Useful String methods


[Link]([Link]()); // 5

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

// Equality — ALWAYS use .equals(), not ==


String a = new String("hello");
String b = new String("hello");
[Link](a == b); // false (different objects)
[Link]([Link](b)); // true (same content)
[Link]([Link]("HELLO")); // true

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).

int → Integer [Link]("42"), Integer.MAX_VALUE,


[Link](n)

double → Double [Link]("3.14"), [Link](x)

boolean → Boolean [Link]("true")

char → Character [Link](c), [Link](c), [Link](c)

// Autoboxing — auto-convert primitive to wrapper


Integer boxed = 42; // int → Integer automatically

// Unboxing — auto-convert wrapper to primitive


int primitive = boxed; // Integer → int automatically

// 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

// Narrowing — explicit cast required


double pi = 3.99;
int piInt = (int) pi; // 3 — truncates decimal!
[Link](piInt); // 3

// char ↔ int conversions


char ch = 'A';
int code = ch; // 65 (Unicode code point)
char back = (char)(code + 1); // 'B'

// Overflow
int max = Integer.MAX_VALUE; // 2147483647
[Link](max + 1); // -2147483648 (overflow wraps!)

// Use long to avoid overflow


long safe = (long) max + 1;
[Link](safe); // 2147483648

■ 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

for Loop (Traditional)


The classic C-style for loop: initialization; condition; update. Best when you know the exact number of
iterations.
// Basic for loop
for (int i = 0; i < 5; i++) {
[Link](i + " "); // 0 1 2 3 4
}

// 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
}

for-each Loop (Enhanced for)


Iterates over every element in an array or iterable. Cleaner but no index access.
int[] nums = {10, 20, 30, 40, 50};
for (int n : nums) {
[Link](n + " "); // 10 20 30 40 50
}

String[] fruits = {"apple", "banana", "cherry"};


for (String fruit : fruits) {
[Link]([Link]());
}

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!
}

// Input validation loop


Scanner sc = new Scanner([Link]);
int age = -1;
while (age < 0 || age > 120) {
[Link]("Enter age (0-120): ");
age = [Link]();
}
[Link]("Valid age: " + age);

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);

[Link]("You chose: " + choice);

break and continue


// break — exit loop immediately
for (int i = 0; i < 10; i++) {
if (i == 5) break;
[Link](i + " "); // 0 1 2 3 4
}

// continue — skip rest of current iteration


for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
[Link](i + " "); // 1 3 5 7 9
}

Labeled break/continue (Nested Loop Control)


outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) continue outer; // skip to next i
[Link](i + "," + j);
}
}

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

§4 Nested Structures & Scope


nested loops · nested if · block scope · variable shadowing · lifetime

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

public static void main(String[] args) {

Page 12
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

int methodLevel = 10; // method scope


[Link](classLevel); // 100 (visible)
[Link](methodLevel); // 10

if (true) {
int blockLevel = 5; // block scope
[Link](blockLevel);// 5 (visible here)
[Link](methodLevel);// 10 (outer scope visible)
}
// [Link](blockLevel); // ERROR — out of scope!

for (int i = 0; i < 3; i++) {


// i is scoped to this for loop only
}
// [Link](i); // 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

public void setName(String name) { // parameter shadows field


// Without this: assignment does nothing useful
[Link] = name; // '[Link]' = field, 'name' = parameter
}
}

Variable Lifetime vs Scope


Lifetime
How long a variable exists in memory. Local variables are created on entry to their block and
destroyed on exit. Object fields live as long as the object is reachable.

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

/ Division: 7 / 2 = 3 (int÷int = int!), 7.0 / 2 = 3.5

% Modulus (remainder): 7 % 3 = 1

++ Increment: i++ (post) or ++i (pre)

-- Decrement: i-- (post) or --i (pre)

// Integer division TRUNCATES — common bug!


[Link](7 / 2); // 3 NOT 3.5
[Link](7.0 / 2); // 3.5
[Link]((double)7/2); // 3.5 — cast first!

// Modulus
[Link](10 % 3); // 1
[Link](15 % 2 == 0); // false — odd check

// Pre vs Post increment


int a = 5;
[Link](a++); // 5 (uses then increments)
[Link](a); // 6

int b = 5;
[Link](++b); // 6 (increments then uses)
[Link](b); // 6

Comparison & Logical Operators


// Comparison — always produce boolean
[Link](5 == 5); // true
[Link](5 != 3); // true
[Link](5 > 3); // true
[Link](5 >= 5); // true

// Logical

Page 14
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

[Link](true && false); // false (AND)


[Link](true || false); // true (OR)
[Link](!true); // false (NOT)

// Short-circuit: && stops at first false, || at first true


int x = 0;
if (x != 0 && 10/x > 2) { // safe — 10/x never evaluated
[Link]("yes");
}

Augmented Assignment (Shorthand)


int x = 10;
x += 3; // x = x + 3 → 13
x -= 2; // → 11
x *= 4; // → 44
x /= 5; // → 8 (integer division!)
x %= 3; // → 2
// No **= in Java; use [Link]()

// String concatenation
String s = "Hello";
s += " World"; // "Hello World"

The Math Class


// All methods are static — call as [Link]()
[Link]([Link]); // 3.141592653589793
[Link](Math.E); // 2.718281828459045
[Link]([Link](144)); // 12.0
[Link]([Link](2, 10)); // 1024.0
[Link]([Link](-9)); // 9
[Link]([Link](-9.5)); // 9.5
[Link]([Link](5, 10)); // 10
[Link]([Link](5, 10)); // 5
[Link]([Link](3.9)); // 3.0
[Link]([Link](3.1)); // 4.0
[Link]([Link](3.5)); // 4 (rounds half up)
[Link]([Link](Math.E)); // 1.0 (natural log)
[Link](Math.log10(1000)); // 3.0
[Link]([Link]([Link]/2)); // 1.0
[Link]([Link]()); // [0.0, 1.0)

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

§6 Methods & Parameters


defining methods · return types · overloading · pass-by-value · Javadoc

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 }

public static int add(int a, int b) {


return a + b;
}

public static void greet(String name) { // void — no return


[Link]("Hello, " + name + "!");
}

public static void main(String[] args) {


int sum = add(3, 5); // 8
greet("Alice"); // Hello, Alice!
[Link](add(10, 20)); // 30
}

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

public static void main(String[] args) {


int n = 42;
tryChange(n);
[Link](n); // still 42!
}

// With arrays — the reference copy CAN mutate contents


public static void zeroFirst(int[] arr) {
arr[0] = 0; // mutates the ORIGINAL array
}

int[] data = {1, 2, 3};


zeroFirst(data);
[Link](data[0]); // 0

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));
}

// Compiler selects based on argument count/types


[Link](area(5)); // circle
[Link](area(4, 6)); // rectangle
[Link](area(3, 4, 5)); // triangle

Returning Multiple Values


// Java can only return ONE value — use arrays or objects
public static int[] minMax(int[] arr) {
int min = arr[0], max = arr[0];
for (int n : arr) {
if (n < min) min = n;
if (n > max) max = n;
}
return new int[]{min, max};
}

int[] result = minMax(new int[]{3,1,9,5});

Page 17
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

[Link](result[0] + " " + result[1]); // 1 9

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

The Scanner Class


Scanner is Java's primary tool for reading input from the keyboard ([Link]) or from files. Import it
from [Link].
import [Link];

public class InputDemo {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Reading different types


[Link]("Enter your name: ");
String name = [Link](); // reads whole line

[Link]("Enter your age: ");


int age = [Link](); // reads next token as int

[Link]("Enter GPA: ");


double gpa = [Link](); // reads next token as double

[Link]("Pass/Fail? ");
boolean pass = [Link](); // reads "true" or "false"

[Link](); // good practice to close when done


}
}

Token-Based vs Line-Based Reading


Token
A chunk of text separated by whitespace. nextInt(), nextDouble(), next() all read one token.

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

// Multiple values on one line

Page 19
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

// Input: "3 14 159"


int a = [Link]();
int b = [Link]();
int c = [Link]();

// Or read the line and split


String input = [Link](); // "10 20 30"
String[] parts = [Link](" ");
int x = [Link](parts[0]);
int y = [Link](parts[1]);

hasNext Methods
// Read until end of input
Scanner sc = new Scanner([Link]);
int sum = 0;
while ([Link]()) {
sum += [Link]();
}
[Link]("Sum: " + sum);

Input Validation with try-catch


Scanner sc = new Scanner([Link]);
int age = -1;

while (age < 0 || age > 120) {


[Link]("Enter age (0-120): ");
try {
age = [Link]([Link]().trim());
if (age < 0 || age > 120)
[Link]("Out of range.");
} catch (NumberFormatException e) {
[Link]("Please enter a whole number.");
}
}
[Link]("Valid age: " + age);

■ 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;

if (score >= 90) {


grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else {
grade = "F";
}
[Link]("Grade: " + grade); // Grade: B

Ternary Operator
Compact single-expression conditional: condition ? valueIfTrue : valueIfFalse
int age = 20;
String status = (age >= 18) ? "adult" : "minor";
[Link](status); // adult

// Nested ternary (use sparingly — hurts readability)


int x = 0;
String sign = (x > 0) ? "positive" : (x < 0) ? "negative" : "zero";

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");
}

// Switch on String (Java 7+)


String cmd = "quit";
switch (cmd) {
case "start": [Link]("Starting"); break;
case "stop": [Link]("Stopping"); break;
case "quit": [Link]("Quitting"); break;
default: [Link]("Unknown");
}

switch Expression (Java 14+)


Modern switch with arrow syntax — no fall-through, no break needed, can return a value.
// Arrow syntax — clean, no fall-through
int day = 3;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
default -> "Weekend";
};
[Link](name); // Wednesday

// Multiple labels per arm


int numLetters = switch (day) {
case 1, 5 -> 6; // Monday, Friday
case 2, 3, 4 -> 7; // Tue, Wed, Thu
default -> 8;
};

■ 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

§9 String Formatting & printf


[Link] · [Link] · format specifiers · StringBuilder

printf and [Link]


printf prints formatted output. [Link] returns a formatted String. Both use the same format
specifiers.
// Basic printf
[Link]("Hello, %s! You are %d years old.%n", "Alice", 25);
// Hello, Alice! You are 25 years old.

// %n = platform newline (use instead of \n in printf)


// \n works too in most cases

Format Specifiers
%d int / long — decimal integer: 42

%f float / double — decimal: 3.141593

%s String (or any Object via toString())

%c char — single character

%b boolean

%n Platform newline

%x Integer as hexadecimal (lowercase)

%o Integer as octal

%e Scientific notation: 3.141593e+00

double pi = 3.14159265;

// Width and precision


[Link]("%.2f%n", pi); // 3.14
[Link]("%.5f%n", pi); // 3.14159
[Link]("%10.2f%n",pi); // 3.14 (right-aligned)
[Link]("%-10.2f|%n",pi); // 3.14 | (left-aligned)
[Link]("%010.2f%n",pi); // 0000003.14 (zero-padded)
[Link]("%+.2f%n", pi); // +3.14

// Integer formatting
int n = 1234567;

Page 23
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

[Link]("%,d%n", n); // 1,234,567


[Link]("%08d%n", 42); // 00000042
[Link]("%x%n", 255); // ff

// String formatting
[Link]("%-15s|%s%n", "Alice", "Score");
[Link]("%-15s|%d%n", "Bob", 92);

// [Link] — returns a String (doesn't print)


String receipt = [Link]("%-20s $%6.2f", "Coffee", 3.5);
[Link](receipt); // Coffee $ 3.50

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

// Other StringBuilder methods


[Link](0, "Numbers: ");
[Link](0, 9);
[Link]();
[Link](0, 3, "XXX");
[Link]([Link]());

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

// [1, 6] die roll


int die = (int)([Link]() * 6) + 1; // 1–6

// [min, max] inclusive


int min = 10, max = 20;
int rand = (int)([Link]() * (max - min + 1)) + min;

[Link]
The Random class provides more control: seeding, Gaussian, and nextXxx() methods.
import [Link];

Random rng = new Random(); // random seed


Random seeded = new Random(42); // fixed seed — reproducible!

// 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

// Java 8+ — bounded nextInt with cleaner API


// [Link](min, max).findFirst().getAsInt()

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

Shuffling and Random Selection


import [Link];
import [Link];

ArrayList&lt;Integer&gt; deck = new ArrayList&lt;&gt;();


for (int i = 1; i &lt;= 52; i++) [Link](i);

[Link](deck); // in-place shuffle


[Link]([Link](0, 5)); // first 5 cards

// Random element from array


String[] colors = {"red", "green", "blue"};
Random rng = new Random();
String pick = colors[[Link]([Link])];

SecureRandom (Cryptographic)
import [Link];

SecureRandom sr = new SecureRandom();


byte[] token = new byte[16];
[Link](token); // cryptographically strong random bytes

Page 26
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

§11 Algorithm Principles


Boolean zen · assertions · lookahead · fencepost · DeMorgan's Law

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) { /* ... */ }

// BAD — returning boolean literal


public static boolean isEven(int n) {
if (n % 2 == 0) return true;
else return false;
}

// 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;
}

// Run with: java -ea ProgramName


divide(10, 0); // AssertionError: Denominator cannot be zero, got b=0.0

// 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"};

// WRONG: comma after last element


for (String f : fruits) {
[Link](f + ", ");
}
// apple, banana, cherry, ← extra comma!

// CORRECT pattern 1: separator before all but first


for (int i = 0; i < [Link]; i++) {
if (i > 0) [Link](", ");
[Link](fruits[i]);
}
// apple, banana, cherry

// CORRECT pattern 2: [Link]()


[Link]([Link](", ", 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};

// Detect consecutive duplicates


for (int i = 0; i < [Link] - 1; i++) { // -1 for safety
if (nums[i] == nums[i+1]) {
[Link]("Dup at index " + i + ": " + nums[i]);
}
}

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");

// Both print the same!

Page 28
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

// Practical example: loop exit condition


// "keep going while NOT (done OR error)"
// = "keep going while !done AND !error"
boolean done = false, error = false;
while (!done && !error) {
// process
}

Page 29
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

§12 File Processing


Scanner on files · PrintWriter · try-with-resources · token/line-based

Reading Files with Scanner


import [Link];
import [Link];
import [Link];

// Basic file reading


try {
Scanner fileScanner = new Scanner(new File("[Link]"));
while ([Link]()) {
String line = [Link]();
[Link](line);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
}

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]());
}

Token-Based File Reading


// Reading integers token by token
try (Scanner sc = new Scanner(new File("[Link]"))) {
int sum = 0;
while ([Link]()) {
sum += [Link]();
}
[Link]("Sum: " + sum);
} catch (FileNotFoundException e) { /* handle */ }

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 */ }

Writing Files with PrintWriter


import [Link];
import [Link];

// Write to file — creates or OVERWRITES


try (PrintWriter pw = new PrintWriter("[Link]")) {
[Link]("Hello, File!");
[Link]("Second line");
[Link]("Pi = %.4f%n", [Link]);
[Link]("No newline at end");
} catch (FileNotFoundException e) {
[Link]("Cannot create file: " + [Link]());
}

Appending to Files
import [Link];
import [Link];

// FileWriter with append=true


try (PrintWriter pw = new PrintWriter(new FileWriter("[Link]", true))) {
[Link]("New log entry: " + [Link]());
} catch ([Link] e) {
[Link]();
}

Declaring Exceptions with throws


Instead of try-catch, you can declare that a method might throw an exception, propagating it to the caller.
public static void processFile(String filename)
throws FileNotFoundException {
Scanner sc = new Scanner(new File(filename));
while ([Link]()) {
[Link]([Link]());
}

Page 31
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

[Link]();
}

public static void main(String[] args) throws FileNotFoundException {


processFile("[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

// Length property (not a method!)


[Link]([Link]); // 5 (no parentheses)

// Iterate
for (int n : primes) {
[Link](n + " ");
}

// Iterate with index


for (int i = 0; i < [Link]; i++) {
[Link](i + ": " + primes[i]);
}

Value vs Reference Semantics


// Primitives — value semantics
int a = 5;
int b = a; // b is a COPY
b = 10;
[Link](a); // 5 — unaffected

// Arrays — reference semantics


int[] x = {1, 2, 3};
int[] y = x; // y points to SAME array!
y[0] = 99;
[Link](x[0]); // 99 — x is affected!

// To truly copy an array:

Page 33
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

int[] z = [Link](x, [Link]); // new independent copy


int[] z2 = [Link](); // also a copy

Arrays Utility Class


import [Link];

int[] arr = {5, 2, 8, 1, 9, 3};

// Sorting
[Link](arr);
[Link]([Link](arr)); // [1, 2, 3, 5, 8, 9]

// Binary search (array must be sorted first)


[Link]([Link](arr, 5)); // 3

// 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)

// Copy with different length


int[] bigger = [Link](a, 5); // [1,2,3,0,0]
int[] slice = [Link](a, 1, 3); // [2,3]

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}
};

[Link](matrix[1][2]); // 6 (row 1, col 2)


[Link]([Link]); // 3 (rows)
[Link](matrix[0].length); // 3 (cols in row 0)

// 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

// Jagged (ragged) arrays — rows of different lengths


int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{2, 3};
jagged[2] = new int[]{4, 5, 6};

■ 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

§14 ArrayList, HashMap & More


ArrayList · HashMap · HashSet · LinkedList · Collections utility · generics

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];

ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();

// 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);
}

// Convert to/from array


String[] arr = [Link](new String[0]);
ArrayList&lt;Integer&gt; fromArr = new ArrayList&lt;&gt;(
[Link](1, 2, 3, 4, 5));

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];

HashMap&lt;String, Integer&gt; scores = new HashMap&lt;&gt;();

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]());
}

// Word frequency counter


HashMap&lt;String, Integer&gt; freq = new HashMap&lt;&gt;();
String[] words = "the cat sat on the mat the cat".split(" ");
for (String word : words) {
[Link](word, [Link](word, 0) + 1);
}

HashSet
HashSet stores unique elements. O(1) add/remove/contains. Unordered.
import [Link];

HashSet&lt;String&gt; visited = new HashSet&lt;&gt;();


[Link]("Paris");
[Link]("London");
[Link]("Paris"); // ignored — already present

[Link]([Link]()); // 2
[Link]([Link]("Rome")); // false
[Link]("London");

Page 37
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

// Remove duplicates from ArrayList


ArrayList&lt;Integer&gt; withDups = new ArrayList&lt;&gt;(
[Link](1,2,2,3,3,3));
HashSet&lt;Integer&gt; unique = new HashSet&lt;&gt;(withDups);

Collections Utility Class


import [Link];

ArrayList&lt;Integer&gt; nums = new ArrayList&lt;&gt;(


[Link](5, 2, 8, 1, 9));

[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

§15 Objects & Classes


fields · constructors · this · static vs instance · toString · equals

OOP Core Terms


Class
Blueprint/template. Defines fields (state) and methods (behaviour).

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;

// Class variable — shared by ALL Dog objects


private static int totalDogs = 0;

// 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; }

// Setter with validation


public void setAge(int age) {
if (age >= 0) [Link] = age;
}

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;
}

// toString — called automatically in print statements


@Override
public String toString() {
return "Dog[" + name + ", " + age + "yo, " + breed + "]";
}

// equals — semantic equality


@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Dog)) return false;
Dog other = (Dog) obj;
return [Link]([Link]) && age == [Link];
}
}

// 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)

Multiple Constructors (Overloading)


public class Point {
private double x, y;

public Point() { this(0, 0); } // calls below


public Point(double x, double y){ this.x=x; this.y=y; }
public Point(Point other) { this(other.x, other.y); }

public double distanceTo(Point other) {


double dx = this.x - other.x;
double dy = this.y - other.y;
return [Link](dx*dx + dy*dy);
}

Page 40
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

@Override
public String toString() {
return [Link]("(%.1f, %.1f)", x, y);
}
}

Point origin = new Point();


Point p = new Point(3, 4);
[Link]([Link](origin)); // 5.0

Page 41
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

§16 The Big 4


Encapsulation · Inheritance · Polymorphism · Abstraction

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

public BankAccount(String owner, double balance) {


[Link] = owner;
[Link] = (balance >= 0) ? balance : 0;
}

public double getBalance() { return balance; } // controlled access

public void deposit(double amount) {


if (amount > 0) balance += amount;
}
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}

@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

public Animal(String name, int age) {


[Link] = name;
[Link] = age;
}
public void eat() {
[Link](name + " is eating.");
}
public String speak() {
return "...";
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + name + ")";
}
}

public class Dog extends Animal {


private String breed;

public Dog(String name, int age, String breed) {


super(name, age); // MUST call super constructor
[Link] = breed;
}

@Override
public String speak() { // override parent
return "Woof!";
}
public String fetch() {
return name + " fetches the ball!";
}
}

public class Cat extends Animal {


public Cat(String name, int age) { super(name, age); }
@Override
public String speak() { return "Meow!"; }
}

Dog d = new Dog("Rex", 3, "Lab");


[Link]([Link]()); // Woof!
[Link](); // Rex is eating. (inherited)
[Link](d instanceof Animal); // true

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")
};

for (Animal a : animals) {


[Link]([Link] + ": " + [Link]());
// Rex: Woof!
// Luna: Meow!
// Buddy: Woof!
}

// Interfaces — Java's mechanism for multiple polymorphism


interface Drawable {
void draw(); // implicitly public abstract
}
interface Resizable {
void resize(double factor);
}

class Circle implements Drawable, Resizable {


private double radius;
public Circle(double r) { [Link] = r; }
public void draw() { [Link]("Drawing circle r=" + radius);
}
public void resize(double factor) { radius *= factor; }
}

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;

public Shape(String color) { [Link] = color; }

public abstract double area(); // MUST be overridden


public abstract double perimeter();

public void describe() { // concrete method


[Link]("%s: area=%.2f%n",
getClass().getSimpleName(), area());

Page 44
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

}
}

public class Circle extends Shape {


private double radius;
public Circle(String color, double r) { super(color); radius = r; }
@Override public double area() { return [Link] * radius * radius; }
@Override public double perimeter() { return 2 * [Link] * radius; }
}

public class Rectangle extends Shape {


private double w, h;
public Rectangle(String color, double w, double h) {
super(color); this.w=w; this.h=h;
}
@Override public double area() { return w * h; }
@Override public double perimeter() { return 2*(w+h); }
}

Shape[] shapes = { new Circle("red", 5), new Rectangle("blue", 4, 6) };


for (Shape s : shapes) [Link]();
// Circle: area=78.54
// Rectangle: area=24.00

Page 45
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

§17 Sorting & Searching


[Link] · Comparator · linear search · binary search · sort algorithms · Big O

Big O Complexity
O(1) Constant: array index, HashMap get

O(log n) Logarithmic: binary search

O(n) Linear: linear search, single loop

O(n log n) Linearithmic: merge sort, [Link] (Dual-Pivot Quicksort)

O(n²) Quadratic: bubble/insertion sort (worst), nested loops

O(2■) Exponential: naive recursion

[Link] — Built-in
import [Link];
import [Link];

// Primitive arrays — sorts in place (Dual-Pivot Quicksort)


int[] nums = {5, 2, 8, 1, 9, 3};
[Link](nums);
[Link]([Link](nums)); // [1, 2, 3, 5, 8, 9]

// Object arrays — Timsort (stable)


String[] words = {"banana", "apple", "cherry"};
[Link](words);
[Link]([Link](words)); // [apple, banana, cherry]

// Custom order with Comparator


[Link](words, [Link](String::length));
// [apple, banana, cherry] — by length

// Reverse order
[Link](words, [Link]());

// Sort ArrayList
ArrayList&lt;Integer&gt; list = new ArrayList&lt;&gt;([Link](5,2,8,1));
[Link](list);
[Link]([Link]()); // reverse

Linear Search — O(n)

Page 46
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

public static int linearSearch(int[] arr, int target) {


for (int i = 0; i < [Link]; i++) {
if (arr[i] == target) return i;
}
return -1; // not found
}

int[] data = {4, 2, 7, 1, 9};


[Link](linearSearch(data, 7)); // 2
[Link](linearSearch(data, 5)); // -1

Binary Search — O(log n)


Requires a SORTED array. Halves the search space each step.
// Built-in
[Link](nums);
int idx = [Link](nums, 5); // returns index

// 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;
}

Selection Sort — O(n²)


public static void selectionSort(int[] arr) {
for (int i = 0; i < [Link]; i++) {
int minIdx = i;
for (int j = i+1; j < [Link]; j++) {
if (arr[j] < arr[minIdx]) minIdx = j;
}
int tmp = arr[i]; arr[i] = arr[minIdx]; arr[minIdx] = tmp;
}
}

Merge Sort — O(n log n)


public static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid+1, right);
merge(arr, left, mid, right);

Page 47
■ Comprehensive Java Programming Guide Sections 1–18 · CS Definitions · Examples

}
}

public static void merge(int[] arr, int l, int m, int r) {


int n1 = m-l+1, n2 = r-m;
int[] L = [Link](arr, l, m+1);
int[] R = [Link](arr, m+1, r+1);
int i=0, j=0, k=l;
while (i<n1 && j<n2)
arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}

// Call: mergeSort(arr, 0, [Link] - 1);

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:

• Base case — the simplest input solved directly without recursion.


• Recursive case — break the problem smaller and call self.
• Progress — each call must move CLOSER to the base case.
Call Stack
Each method call pushes a frame onto the stack. Recursive calls stack up until the base case, then
unwind. Java's default stack depth is ~500–1000 frames depending on JVM settings. Exceeding it
causes StackOverflowError.

Factorial — Classic Example


// n! = n * (n-1) * ... * 1, 0! = 1
public static long factorial(int n) {
if (n == 0) return 1; // base case
return n * factorial(n - 1); // recursive case
}

// 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&lt;Integer,Long&gt; memo = new HashMap&lt;&gt;();
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

long result = fibMemo(n-1) + fibMemo(n-2);


[Link](n, result);
return result;
}

// First 10: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Array Sum — Recursive


public static int sum(int[] arr, int i) {
if (i == [Link]) return 0; // base: past end
return arr[i] + sum(arr, i+1); // recursive case
}

// Call: sum(new int[]{1,2,3,4,5}, 0) → 15

Power — Divide & Conquer


// Naive O(n)
public static double power(double base, int exp) {
if (exp == 0) return 1;
return base * power(base, exp-1);
}

// Fast O(log n) — divide and conquer


public static double fastPow(double base, int exp) {
if (exp == 0) return 1;
if (exp % 2 == 0) {
double half = fastPow(base, exp/2);
return half * half;
}
return base * fastPow(base, exp-1);
}
[Link](fastPow(2, 10)); // 1024.0

Binary Search — Recursive


public static int bsRec(int[] arr, int target, int low, int high) {
if (low > high) return -1;
int mid = low + (high - low) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) return bsRec(arr, target, mid+1, high);
else return bsRec(arr, target, low, mid-1);
}

// Call: bsRec(arr, target, 0, [Link]-1)

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

[Link]("Move disk 1: " + src + " -> " + dst);


return;
}
hanoi(n-1, src, aux, dst);
[Link]("Move disk " + n + ": " + src + " -> " + dst);
hanoi(n-1, aux, dst, src);
}

hanoi(3, 'A', 'C', 'B');


// Requires 2^n - 1 = 7 moves for 3 disks

Recursion vs Iteration — Summary


Readability Recursion mirrors mathematical definitions. Iteration is more explicit.

Performance Iteration is faster (no call overhead). Recursion risks StackOverflow.

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.

Memoization HashMap/array cache turns exponential recursive into linear.

End of Guide
You have covered all 18 sections of the Comprehensive Java Programming Guide.
Happy coding! ■

Page 51

You might also like