0% found this document useful (0 votes)
3 views25 pages

Java Complete Reference

Uploaded by

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

Java Complete Reference

Uploaded by

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

Java Complete Reference Guide

JAVA
Complete Reference Guide
Data Types · OOP · Collections · Generics · Streams · Concurrency & More

Page 1
Java Complete Reference Guide

1. Data Types
Java is a statically typed language. Every variable must be declared with a type before use. Java has
two categories: primitive types and reference types.

1.1 Primitive Data Types


Java has 8 built-in primitive types. They are stored directly on the stack and are not objects.

Type Size Range / Notes Default


Value
byte 8-bit -128 to 127 0
short 16-bit -32,768 to 32,767 0
int 32-bit -2,147,483,648 to 0
2,147,483,647
long 64-bit -9.2×10¹⁸ to 9.2×10¹⁸ (suffix 0L
L)
float 32-bit ~6-7 decimal digits (suffix f) 0.0f
double 64-bit ~15 decimal digits 0.0d
char 16-bit 0 to 65,535 (Unicode UTF- '\u0000'
16)
boolean 1-bit true / false false

1.2 Wrapper / Reference Types


Each primitive has a corresponding wrapper class in [Link]. They allow primitives to be used as
objects (e.g., in Collections).

byte → Byte Byte.MIN_VALUE / MAX_VALUE; parseByte(String)


short → Short Short.MIN_VALUE / MAX_VALUE; parseShort(String)
int → Integer [Link](), toBinaryString(), MAX_VALUE
long → Long [Link](), Long.MAX_VALUE
float → Float [Link](), isNaN(), isInfinite()
double → Double [Link](), [Link]()
char → Character [Link](), isLetter(), toUpperCase()
boolean → Boolean [Link](), TRUE / FALSE constants

Page 2
Java Complete Reference Guide

1.3 Autoboxing & Unboxing


Java automatically converts between primitives and wrapper types.
Integer x = 42; // autoboxing: int → Integer
int y = x; // unboxing: Integer → int
List<Integer> list = new ArrayList<>();
[Link](5); // autoboxing happens automatically

1.4 String & Text


String is immutable, stored in the String Pool. Use StringBuilder for mutable string building.
String s = "Hello";
[Link]() // 5
[Link](0) // 'H'
[Link](1, 3) // "el"
[Link]("ell") // true
[Link]("l", "r") // "Herro"
[Link]() // "HELLO"
[Link]() // removes whitespace
[Link](",") // returns String[]
[Link]("%s=%d", "x", 5) // "x=5"

1.5 var (Local Variable Type Inference — Java 10+)


var lets the compiler infer the type of a local variable.
var message = "Hello"; // inferred as String
var list = new ArrayList<String>(); // ArrayList<String>
for (var item : list) { ... }

Page 3
Java Complete Reference Guide

2. Object-Oriented Programming (OOP)

2.1 Classes & Objects


A class is a blueprint; an object is an instance of a class.
public class Person {
private String name;
private int age;

public Person(String name, int age) {


[Link] = name;
[Link] = age;
}

public String getName() { return name; }


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

Person p = new Person("Alice", 30);

2.2 Inheritance
A subclass extends a superclass and inherits its non-private members. Java supports single inheritance
for classes.
public class Employee extends Person {
private String department;

public Employee(String name, int age, String dept) {


super(name, age);
[Link] = dept;
}
}

2.3 Polymorphism
Objects of different types can be treated via a common interface. Method overriding enables runtime
polymorphism.
class Animal { public void sound() { [Link]("..."); } }
class Dog extends Animal { @Override public void sound() { [Link]("Woof"); } }
Animal a = new Dog(); [Link](); // prints 'Woof'

2.4 Abstraction — Abstract Classes & Interfaces


abstract class Cannot be instantiated; may have abstract methods and concrete

Page 4
Java Complete Reference Guide

methods; can hold state


interface All methods public (default abstract); since Java 8 can have
default/static methods; no state (only static final fields)

public abstract class Shape {


public abstract double area();
public void describe() { [Link]("Area: " + area()); }
}

public interface Drawable {


void draw();
default void print() { [Link]("Drawing"); }
}

2.5 Encapsulation
Keep fields private and expose behaviour through public methods (getters/setters). Use records (Java
16+) for immutable data classes.
public record Point(double x, double y) {} // compact record
Point p = new Point(3.0, 4.0);
p.x(); // accessor method auto-generated

2.6 Access Modifiers


Modifier Same Class Same Package Subclass World
private ✓ ✗ ✗ ✗
(default) ✓ ✓ ✗ ✗
protected ✓ ✓ ✓ ✗
public ✓ ✓ ✓ ✓

2.7 Static Members & Nested Classes


• static fields/methods belong to the class, not instances
• static nested class: no reference to outer class instance
• inner class (non-static): has access to outer class members
• anonymous class: one-off implementation inline
• local class: defined inside a method

Page 5
Java Complete Reference Guide

3. Collections Framework
The Java Collections Framework ([Link]) provides unified interfaces and implementations for data
structures. All collections use generics.

3.1 Collection Hierarchy


Iterable Root — anything you can iterate with for-each
Collection Extends Iterable; add, remove, contains, size, iterator
List Ordered; duplicates allowed; index-based access
Set No duplicates; may or may not be ordered
Queue / Deque FIFO / double-ended queue
Map Key→value pairs (NOT a Collection); unique keys

3.2 List Implementations


List<String> arrayList = new ArrayList<>(); // O(1) get, amortised O(1) add
List<String> linkedList = new LinkedList<>(); // O(1) add/remove at ends
List<String> vector = new Vector<>(); // synchronized ArrayList (legacy)
List<Integer> fixed = [Link](1, 2, 3); // immutable (Java 9+)

Operation ArrayList LinkedList


get(i) O(1) O(n)
add(end) O(1)* O(1)
add(middle) O(n) O(1) after traversal
remove(middle) O(n) O(1) after traversal
contains O(n) O(n)

3.3 Set Implementations


Set<String> hashSet = new HashSet<>(); // O(1) add/contains (unordered)
Set<String> linkedHash = new LinkedHashSet<>(); // insertion-order
Set<String> treeSet = new TreeSet<>(); // sorted (natural order)
Set<String> immutable = [Link]("a", "b", "c"); // Java 9+, unordered

3.4 Map Implementations


Map<String, Integer> hashMap = new HashMap<>(); // O(1) get/put (unordered)
Map<String, Integer> linked = new LinkedHashMap<>(); // insertion-order
Map<String, Integer> treeMap = new TreeMap<>(); // sorted by key

Page 6
Java Complete Reference Guide
Map<String, Integer> table = new Hashtable<>(); // synchronized (legacy)
Map<String, Integer> imm = [Link]("a", 1, "b", 2); // Java 9+

Common Map operations:


[Link]("key", 10);
[Link]("key"); // 10
[Link]("x", 0); // 0 if missing
[Link]("key", 99);
[Link]("k", k -> [Link]());
[Link]("k", 1, Integer::sum); // accumulate
[Link]((k, v) -> [Link](k + "=" + v));

3.5 Queue & Deque


Queue<Integer> queue = new LinkedList<>();
[Link](1); [Link](2);
[Link](); // removes & returns head → 1
[Link](); // returns head without removing

Deque<Integer> deque = new ArrayDeque<>();


[Link](0); [Link](1);
[Link](); [Link]();

// PriorityQueue — min-heap by default


PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](5); [Link](1); [Link](); // returns 1

3.6 Stack
Deque<Integer> stack = new ArrayDeque<>(); // preferred
[Link](10); [Link](20);
[Link](); // 20
[Link](); // 10

3.7 Utility Methods — Collections & Arrays


[Link](list);
[Link](list, [Link]());
[Link](list);
[Link](list);
[Link](list, element);
[Link](set1, set2);

[Link](arr);
[Link](arr, target);
[Link](arr, newLength);
[Link](arr, value);

Page 7
Java Complete Reference Guide
[Link](1, 2, 3); // fixed-size List backed by array

Page 8
Java Complete Reference Guide

4. Iterators, Comparable & Comparator

4.1 Iterator
Iterator<String> it = [Link]();
while ([Link]()) {
String s = [Link]();
if ([Link]()) [Link](); // safe removal during iteration
}

4.2 Comparable (Natural Ordering)


Implement Comparable<T> so your class has a natural sort order.
public class Student implements Comparable<Student> {
String name; int grade;
@Override
public int compareTo(Student o) {
return [Link]([Link], [Link]);
}
}
List<Student> students = ...;
[Link](students); // uses compareTo

4.3 Comparator (External Ordering)


// Lambda style
Comparator<Student> byName = (a, b) -> [Link]([Link]);

// Method reference style


Comparator<Student> byGrade = [Link](s -> [Link]);

// Chaining
[Link]([Link](Student::getName)
.thenComparingInt(Student::getGrade)
.reversed());

Page 9
Java Complete Reference Guide

5. Generics
Generics provide compile-time type safety and eliminate the need for casts. They are erased at runtime
(type erasure).

5.1 Generic Classes & Methods


public class Pair<A, B> {
private final A first;
private final B second;
public Pair(A first, B second) { [Link]=first; [Link]=second; }
public A getFirst() { return first; }
}

// Generic method
public <T extends Comparable<T>> T max(T a, T b) {
return [Link](b) >= 0 ? a : b;
}

5.2 Wildcards
? Unbounded wildcard — any type
? extends T Upper bounded — T or any subtype (covariant, read-only)
? super T Lower bounded — T or any supertype (contravariant, write-only)

void printAll(List<?> list) { [Link]([Link]::println); }


double sum(List<? extends Number> list) { /* read numbers */ }
void addIntegers(List<? super Integer> list) { [Link](42); }

5.3 Bounded Type Parameters


public <T extends Comparable<T> & Serializable> void process(T item) { }

Page 10
Java Complete Reference Guide

6. Functional Programming — Lambdas & Functional


Interfaces

6.1 Lambda Expressions


A lambda is a concise way to provide the implementation of a functional interface (an interface with
exactly one abstract method).
// Syntax: (parameters) -> expression OR (parameters) -> { statements; }
Runnable r = () -> [Link]("Run!");
Comparator<String> cmp = (a, b) -> [Link](b);
Function<Integer, Integer> square = x -> x * x;

6.2 Key Functional Interfaces ([Link])


Interface Method Description Example
Function<T,R> R apply(T) Transform T → R x -> x*2
Consumer<T> void accept(T) Consume T, no return s -> print(s)
Supplier<T> T get() Produce T, no input () -> new Obj()
Predicate<T> boolean test(T) Test T, return bool s -> [Link]()
BiFunction<T,U,R> R apply(T,U) Two inputs → result (a,b) -> a+b
UnaryOperator<T> T apply(T) Function<T,T> x -> -x
BinaryOperator<T> T apply(T,T) BiFunction<T,T,T> Math::max

6.3 Method References


Type Syntax Example
Static method Class::staticMethod Math::sqrt
Instance method (obj) instance::method [Link]::println
Instance method (type) Type::instanceMethod String::toUpperCase
Constructor Class::new ArrayList::new

Page 11
Java Complete Reference Guide

7. Streams API ([Link])


Streams provide declarative, pipeline-based processing of data sequences. They are lazy: intermediate
operations are not executed until a terminal operation is called.

7.1 Creating Streams


[Link](1, 2, 3)
[Link]()
[Link](arr)
[Link](0, 10) // 0..9
[Link](1, 5) // 1..5
[Link](Math::random) // infinite
[Link](1, x -> x * 2) // infinite: 1, 2, 4, 8, ...
[Link]([Link]("[Link]"))

7.2 Intermediate Operations (lazy)


Method Description
filter(Predicate) Keep elements matching condition
map(Function) Transform each element
mapToInt/Long/Double Map to primitive stream
flatMap(Function) Flatten nested streams
distinct() Remove duplicates
sorted() Natural sort order
sorted(Comparator) Custom sort
limit(n) Truncate to first n elements
skip(n) Skip first n elements
peek(Consumer) Debug: inspect without consuming
takeWhile(Predicate) Take while true (Java 9+)
dropWhile(Predicate) Drop while true (Java 9+)

7.3 Terminal Operations (eager)


Method Description
forEach(Consumer) Iterate side-effects
collect(Collector) Accumulate into collection
toList() Collect to List (Java 16+)
count() Number of elements
findFirst() / findAny() Returns Optional<T>

Page 12
Java Complete Reference Guide

anyMatch / allMatch / noneMatch Predicate tests → boolean


min(Comp) / max(Comp) Returns Optional<T>
reduce(identity, BinaryOp) Fold into single value
toArray() Collect to Object[]
sum / average / summaryStats Numeric stream aggregates

7.4 Collectors ([Link])


// Basic
[Link]()
[Link]()
[Link]()
[Link](keyFn, valueFn, mergeFunction)

// Joining
[Link](", ", "[", "]")

// Grouping
Map<String, List<Person>> byCity =
[Link]().collect([Link](Person::getCity));

// Grouping with downstream collector


Map<String, Long> countByCity =
[Link]().collect([Link](
Person::getCity, [Link]()));

// Partitioning (splits into true/false map)


Map<Boolean, List<Integer>> parts =
[Link]().collect([Link](n -> n % 2 == 0));

// Statistics
IntSummaryStatistics stats =
[Link]().collect([Link](Integer::intValue));
// [Link](), getMax(), getSum(), getAverage(), getCount()

7.5 Optional<T>
Optional wraps a value that may or may not be present, avoiding null checks.
Optional<String> opt = [Link]("hello");
Optional<String> empty = [Link]();

[Link]() // true
[Link]() // false (Java 11+)
[Link]() // "hello" (throws if empty)
[Link]("default")
[Link](() -> compute())
[Link](RuntimeException::new)

Page 13
Java Complete Reference Guide
[Link](String::toUpperCase) // Optional<String>
[Link](s -> [Link]() > 3)
[Link]([Link]::println)
[Link]([Link]::println, () -> log("empty")) // Java 9+

Page 14
Java Complete Reference Guide

8. Exception Handling

8.1 Exception Hierarchy


Throwable Root of all exceptions and errors
Error Serious JVM errors (OutOfMemoryError, StackOverflowError) —
don't catch
Exception Application-level issues — catch these
RuntimeException Unchecked (programmer error): NullPointerException,
ArrayIndexOutOfBoundsException
Checked exceptions Must be declared or caught: IOException, SQLException,
ClassNotFoundException

8.2 try-catch-finally & Multi-catch


try {
int[] a = new int[3];
int x = a[5]; // throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
[Link]("Error: " + [Link]());
} catch (Exception e) {
[Link]();
} finally {
[Link]("Always runs");
}

8.3 try-with-resources (AutoCloseable)


try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) [Link](line);
} catch (IOException e) { [Link](); }
// br is closed automatically

8.4 Custom Exceptions


public class InsufficientFundsException extends Exception {
private final double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds: " + amount);
[Link] = amount;
}
public double getAmount() { return amount; }
}

Page 15
Java Complete Reference Guide

Page 16
Java Complete Reference Guide

9. Concurrency & Multithreading

9.1 Creating Threads


// Extend Thread
Thread t = new Thread(() -> [Link]("Thread!"));
[Link]();

// Implement Runnable
Runnable r = () -> doWork();
new Thread(r).start();

// Callable (returns value, throws checked exception)


Callable<Integer> c = () -> 42;

9.2 ExecutorService
ExecutorService pool = [Link](4);
[Link](() -> doWork());
Future<Integer> future = [Link](() -> heavyComputation());
int result = [Link](); // blocks until done
[Link]();

9.3 CompletableFuture (Java 8+)


CompletableFuture<String> cf = CompletableFuture
.supplyAsync(() -> fetchData())
.thenApply(data -> process(data))
.thenCombine(otherFuture, (a, b) -> a + b)
.exceptionally(ex -> "fallback");
String result = [Link]();

9.4 Synchronization & Locks


// synchronized method
public synchronized void increment() { count++; }

// synchronized block
synchronized (lockObject) { criticalSection(); }

// ReentrantLock
ReentrantLock lock = new ReentrantLock();
[Link]();
try { criticalSection(); } finally { [Link](); }

Page 17
Java Complete Reference Guide

9.5 Atomic Variables & Volatile


AtomicInteger counter = new AtomicInteger(0);
[Link]();
[Link](expected, update);

volatile boolean running = true; // guarantees visibility

9.6 Concurrent Collections


• ConcurrentHashMap — thread-safe hash map
• CopyOnWriteArrayList — thread-safe list; writes copy the array
• BlockingQueue (ArrayBlockingQueue, LinkedBlockingQueue)
• ConcurrentLinkedQueue — non-blocking FIFO
• CyclicBarrier, CountDownLatch, Semaphore — coordination utilities

Page 18
Java Complete Reference Guide

10. I/O & NIO ([Link] / [Link])

10.1 Classic I/O


// Reading a file line by line
try (BufferedReader br = [Link]([Link]("[Link]"))) {
[Link]().forEach([Link]::println);
}

// Writing
try (BufferedWriter bw = [Link]([Link]("[Link]"))) {
[Link]("Hello"); [Link]();
}

10.2 NIO.2 — Path & Files (Java 7+)


Path p = [Link]("/home/user/[Link]");
[Link](p);
[Link](p); // List<String>
[Link](p); // Java 11+
[Link](p, "content"); // Java 11+
[Link](src, dst, StandardCopyOption.REPLACE_EXISTING);
[Link](src, dst);
[Link](p);
[Link](p);
[Link](startPath).filter(Files::isRegularFile).forEach([Link]::println);

Page 19
Java Complete Reference Guide

11. Modern Java Features

11.1 Sealed Classes (Java 17)


public sealed class Shape permits Circle, Rectangle, Triangle {}
public final class Circle extends Shape { double radius; }
public final class Rectangle extends Shape { double w, h; }

11.2 Pattern Matching


// instanceof pattern (Java 16+)
if (obj instanceof String s) { [Link]([Link]()); }

// Switch expressions (Java 14)


int numDays = switch (month) {
case JANUARY, MARCH, MAY -> 31;
case FEBRUARY -> 28;
default -> 30;
};

// Pattern matching switch (Java 21)


String desc = switch (shape) {
case Circle c -> "Circle r=" + [Link];
case Rectangle r -> "Rect " + r.w + "x" + r.h;
default -> "unknown";
};

11.3 Text Blocks (Java 15)


String json = """
{
"name": "Alice",
"age": 30
}
""";

11.4 Records (Java 16)


public record Point(double x, double y) {
// Compact constructor
Point { if (x < 0) throw new IllegalArgumentException(); }
public double distance() { return [Link](x, y); }
}
Point p = new Point(3, 4);
p.x(); p.y(); // auto-generated accessors

Page 20
Java Complete Reference Guide

11.5 Virtual Threads (Java 21 — Project Loom)


[Link]().start(() -> handleRequest());

// With executor
try (var exec = [Link]()) {
for (int i = 0; i < 10_000; i++) [Link](() -> doIO());
}

Page 21
Java Complete Reference Guide

12. Common Design Patterns in Java

12.1 Creational Patterns


Singleton
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) synchronized ([Link]) {
if (instance == null) instance = new Singleton();
}
return instance;
}
}

Builder
Person p = new [Link]("Alice")
.age(30).city("Delhi").build();

Factory Method
interface Animal { void speak(); }
class AnimalFactory {
static Animal create(String type) {
return switch (type) {
case "dog" -> () -> [Link]("Woof");
case "cat" -> () -> [Link]("Meow");
default -> throw new IllegalArgumentException();
};
}
}

12.2 Structural Patterns


• Adapter — wrap an incompatible interface
• Decorator — add behaviour dynamically ([Link] streams)
• Proxy — control access to an object
• Composite — treat single objects and groups uniformly

12.3 Behavioural Patterns


• Strategy — swap algorithms at runtime (Comparator is Strategy)
• Observer — notify dependents on state change (EventListener)

Page 22
Java Complete Reference Guide

• Command — encapsulate requests as objects


• Template Method — define skeleton in base, steps in subclasses
• Iterator — sequential access (built into Java Collections)

Page 23
Java Complete Reference Guide

13. Quick Reference Cheat Sheet

13.1 Common String Methods


Method Returns Example
length() int "abc".length() → 3
charAt(i) char "abc".charAt(1) → 'b'
indexOf(s) int "abc".indexOf('b') → 1
substring(s,e) String "hello".substring(1,3) → "el"
toUpperCase() String "hi".toUpperCase() → "HI"
trim() String " hi ".trim() → "hi"
replace(old,new) String "aab".replace('a','x') → "xxb"
split(regex) String[] "a,b".split(",") → ["a","b"]
contains(seq) boolean "hello".contains("ell") → true
startsWith(prefix) boolean "hello".startsWith("he") → true
isEmpty() boolean "".isEmpty() → true
isBlank() boolean " ".isBlank() → true (Java 11)
strip() String strips Unicode whitespace (Java 11)
repeat(n) String "ab".repeat(3) → "ababab" (Java 11)
[Link](x) String [Link](42) → "42"
[Link](s) int [Link]("7") → 7

13.2 Math Class


Method Description
[Link](x) Absolute value
[Link](a,b) Maximum of two values
[Link](a,b) Minimum of two values
[Link](base,exp) base^exp
[Link](x) Square root
[Link](x) Round down
[Link](x) Round up
[Link](x) Round to nearest integer
[Link](x) Natural logarithm
[Link]() Random double [0, 1)
[Link] π ≈ 3.14159...

Page 24
Java Complete Reference Guide

13.3 Java Version Feature Timeline


Java Key Features
Java 8 (2014) Lambdas, Stream API, Optional, Default methods, Date-Time API
Java 9 (2017) Module system (JPMS), jshell REPL, Collection factory methods
Java 10 (2018) var (local type inference), [Link]()
Java 11 (2018) String methods (strip, isBlank, repeat), [Link], HTTP Client
Java 14 (2020) Switch expressions (stable), Records (preview)
Java 15 (2020) Text Blocks (stable), Sealed Classes (preview)
Java 16 (2021) Records (stable), instanceof pattern matching (stable)
Java 17 (2021) Sealed Classes (stable), LTS release
Java 21 (2023) Virtual Threads, pattern matching switch, Sequenced Collections, LTS

Page 25

You might also like