Skip to content

Java Complete Reference

Mattscreative edited this page Mar 9, 2026 · 1 revision

Java Complete Reference Guide

Table of Contents


Data Types

Primitive Types

Type Size Default Range
byte 8-bit 0 -128 to 127
short 16-bit 0 -32,768 to 32,767
int 32-bit 0 -2.1B to 2.1B
long 64-bit 0L -9.2Q to 9.2Q
float 32-bit 0.0f ±3.4e38
double 64-bit 0.0 ±1.7e308
boolean 1-bit false true/false
char 16-bit '\u0000' 0 to 65,535

Reference Types

  • String - Text
  • Arrays - Fixed-size collections
  • Classes - Custom types
  • Interfaces - Contracts

Type Conversion

// Implicit (widening)
int i = 100;
long l = i;  // int to long

// Explicit (narrowing)
double d = 100.5;
int i2 = (int) d;  // 100

// String to number
int i3 = Integer.parseInt("42");
double d2 = Double.parseDouble("3.14");

// Number to String
String s = String.valueOf(42);
String s2 = Integer.toString(42);

Operators

Arithmetic Operators

+   // Addition
-   // Subtraction
*   // Multiplication
/   // Division
%   // Modulus (remainder)
++  // Increment
--  // Decrement
+=  // Add and assign
-=  // Subtract and assign
*=  // Multiply and assign
/=  // Divide and assign
%=  // Modulus and assign

Comparison Operators

==  // Equal to
!=  // Not equal to
>   // Greater than
<   // Less than
>=  // Greater or equal
<=  // Less or equal

Logical Operators

&&  // Logical AND
||  // Logical OR
!   // Logical NOT
&   // Bitwise AND
|   // Bitwise OR
^   // Bitwise XOR
~   // Bitwise NOT
<<  // Left shift
>>  // Right shift
>>> // Unsigned right shift

Ternary Operator

String result = (condition) ? "true" : "false";

Control Flow

If-Else

if (condition) {
    // code
} else if (condition2) {
    // code
} else {
    // code
}

Switch

switch (variable) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code
}

// Java 14+ (switch expression)
String result = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
    default -> "Invalid";
};

For Loop

// Traditional
for (int i = 0; i < 10; i++) {
    // code
}

// For-each
for (Type item : collection) {
    // code
}

While Loop

while (condition) {
    // code
}

do {
    // code (runs at least once)
} while (condition);

Loop Control

break;      // Exit loop
continue;   // Skip to next iteration

Classes and Objects

Class Definition

public class ClassName {
    // Fields
    private Type fieldName;
    
    // Constructor
    public ClassName(Type parameter) {
        this.fieldName = parameter;
    }
    
    // Getter
    public Type getFieldName() {
        return fieldName;
    }
    
    // Setter
    public void setFieldName(Type fieldName) {
        this.fieldName = fieldName;
    }
    
    // Method
    public returnType methodName(parameters) {
        // code
    }
}

Creating Objects

ClassName obj = new ClassName(argument);

Access Modifiers

Modifier Class Package Subclass World
public
protected
default
private

Static vs Instance

public class Example {
    static int staticVar = 0;  // Shared by all instances
    int instanceVar = 0;       // Unique to each instance
    
    static void staticMethod() { }  // Call: Example.staticMethod()
    void instanceMethod() { }       // Call: obj.instanceMethod()
}

Inheritance and Polymorphism

Inheritance

public class Parent {
    public void method() { }
}

public class Child extends Parent {
    // Inherits method() automatically
    
    @Override
    public void method() {  // Override parent method
        // new implementation
    }
}

super Keyword

public class Child extends Parent {
    public Child() {
        super();  // Call parent constructor
    }
    
    public void childMethod() {
        super.method();  // Call parent method
    }
}

Polymorphism

Parent obj = new Child();  // Reference type Parent, object type Child
obj.method();  // Calls Child's implementation

final Keyword

final class CannotExtend { }  // Class cannot be extended

class Example {
    final int CONSTANT = 100;  // Cannot be changed
    
    final void cannotOverride() { }  // Cannot be overridden
}

Interfaces and Abstract Classes

Interface

public interface InterfaceName {
    // Abstract method (Java 7)
    void method1();
    
    // Default method (Java 8)
    default void method2() {
        // implementation
    }
    
    // Static method (Java 8)
    static void method3() {
        // implementation
    }
    
    // Private method (Java 9)
    private void helper() { }
}

Abstract Class

public abstract class AbstractClass {
    // Abstract method - no body
    public abstract void abstractMethod();
    
    // Regular method
    public void regularMethod() {
        // implementation
    }
}

Implementing

public class ConcreteClass implements InterfaceName, AnotherInterface {
    @Override
    public void method1() { }
    
    @Override
    public void anotherMethod() { }
}

Exception Handling

Try-Catch-Finally

try {
    // Code that might throw exception
} catch (ExceptionType1 e) {
    // Handle ExceptionType1
} catch (ExceptionType2 e) {
    // Handle ExceptionType2
} finally {
    // Always executes
}

Common Exceptions

NullPointerException      // Using null object
ArrayIndexOutOfBoundsException  // Invalid array index
ArithmeticException       // Math errors (division by zero)
IOException               // I/O errors
NumberFormatException     // Invalid number format
ClassCastException        // Invalid casting
IllegalArgumentException  // Invalid method argument

Throwing Exceptions

public void method() throws IOException {
    if (error) {
        throw new IOException("Error message");
    }
}

Custom Exception

public class MyException extends Exception {
    public MyException() { }
    
    public MyException(String message) {
        super(message);
    }
}

Collections

List Implementations

List<Type> arrayList = new ArrayList<>();      // Fast random access
List<Type> linkedList = new LinkedList<>();     // Fast insert/delete
List<Type> vector = new Vector<>();             // Thread-safe

Set Implementations

Set<Type> hashSet = new HashSet<>();           // No order, fast
Set<Type> linkedHashSet = new LinkedHashSet<>(); // Insertion order
Set<Type> treeSet = new TreeSet<>();           // Sorted order

Map Implementations

Map<Key, Value> hashMap = new HashMap<>();           // No order
Map<Key, Value> linkedHashMap = new LinkedHashMap<>(); // Insertion order
Map<Key, Value> treeMap = new TreeMap<>();           // Sorted by keys
Map<Key, Value> hashTable = new Hashtable<>();       // Thread-safe

Collection Methods

// Adding
list.add(element);
list.addAll(collection);

// Removing
list.remove(element);
list.clear();

// Querying
list.size();
list.isEmpty();
list.contains(element);
list.get(index);

// Iterating
for (Type t : list) { }
list.forEach(consumer);
iterator.remove();

Map Methods

map.put(key, value);
map.get(key);
map.containsKey(key);
map.containsValue(value);
map.remove(key);
map.keySet();
map.values();
map.entrySet();

Generics

Generic Class

class Box<T> {
    private T content;
    
    public void set(T content) { this.content = content; }
    public T get() { return content; }
}

// Usage
Box<String> stringBox = new Box<>();
Box<Integer> intBox = new Box<>();

Generic Method

public static <T> void print(T item) {
    System.out.println(item);
}

public static <T extends Comparable<T>> T max(T a, T b) {
    return a.compareTo(b) > 0 ? a : b;
}

Wildcards

// ? extends Type - read-only
void read(List<? extends Number> list) { }

// ? super Type - write-only
void write(List<? super Integer> list) { }

// Unbounded
void process(List<?> list) { }

Lambda Expressions and Streams

Lambda Syntax

// No parameters
() -> expression

// One parameter
param -> expression
(param) -> expression

// Multiple parameters
(a, b) -> expression

// Multiple statements
(a, b) -> {
    // statements
    return result;
}

Common Functional Interfaces

Predicate<T>     // T -> boolean
Function<T, R>   // T -> R
Consumer<T>      // T -> void
Supplier<T>      // () -> T
UnaryOperator<T> // T -> T
BinaryOperator<T> // (T, T) -> T

Stream Operations

// Creation
Stream.of(values)
Arrays.stream(array)
collection.stream()

// Intermediate operations
.filter(predicate)
.map(function)
.flatMap(function)
.sorted()
.distinct()
.limit(n)
.skip(n)

// Terminal operations
.forEach(consumer)
.collect(collector)
.count()
.min(comparator)
.max(comparator)
.reduce(accumulator)
.toArray()

Common Methods Quick Reference

String Methods

str.length()
str.charAt(index)
str.substring(start, end)
str.indexOf(char)
str.lastIndexOf(char)
str.replace(old, new)
str.split(regex)
str.toUpperCase()
str.toLowerCase()
str.trim()
str.equals(other)
str.equalsIgnoreCase(other)
str.contains(substring)
str.startsWith(prefix)
str.endsWith(suffix)
str.isEmpty()
str.concat(other)

Array Methods

array.length
Arrays.toString(array)
Arrays.sort(array)
Arrays.fill(array, value)
Arrays.copyOf(array, newLength)
Arrays.copyOfRange(array, from, to)
Arrays.binarySearch(array, key)
Arrays.equals(arr1, arr2)
Arrays.toList(array)

Math Methods

Math.max(a, b)
Math.min(a, b)
Math.abs(value)
Math.sqrt(value)
Math.pow(base, exponent)
Math.floor(value)
Math.ceil(value)
Math.round(value)
Math.random()
Math.PI
Math.E

System Methods

System.out.println()
System.out.print()
System.out.printf()
System.currentTimeMillis()
System.arraycopy(src, srcPos, dest, destPos, length)
System.exit(code)
System.gc()  // Suggest garbage collection

Best Practices

Naming Conventions

// Classes - PascalCase
class UserAccount { }

// Methods - camelCase
public void calculateTotal() { }

// Variables - camelCase
int userAge = 25;

// Constants - UPPER_SNAKE_CASE
final int MAX_SIZE = 100;

// Packages - lowercase
package com.example.myapp;

Code Organization

// 1. Package declaration
package com.example;

// 2. Imports
import java.util.*;

// 3. Class declaration
public class MyClass {
    // 4. Static variables
    private static int count;
    
    // 5. Instance variables
    private String name;
    
    // 6. Constructors
    public MyClass() { }
    
    // 7. Methods
    public void method() { }
    
    // 8. Inner classes
    class InnerClass { }
}

Effective Java Tips

  1. Prefer immutability - Use final for fields that don't change
  2. Minimize mutability - Make classes immutable when possible
  3. Favor composition over inheritance
  4. Use interfaces - Program to interfaces, not implementations
  5. Prefer for-each loops - Cleaner than iterator loops
  6. Check for null - Use Optional or null checks
  7. Use exceptions only for exceptional conditions
  8. Follow single responsibility - One class, one purpose
  9. Write clear comments - Explain why, not what
  10. Write tests - Unit tests catch bugs early

Common Errors and Solutions

NullPointerException

// Problem
String str = null;
System.out.println(str.length());  // NPE!

// Solution
if (str != null) {
    System.out.println(str.length());
}
// Or use Optional
Optional.ofNullable(str).ifPresent(s -> System.out.println(s.length()));

ArrayIndexOutOfBoundsException

// Problem
int[] arr = {1, 2, 3};
System.out.println(arr[3]);  // Index 3 doesn't exist!

// Solution - always check bounds
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

ClassCastException

// Problem
Object obj = "Hello";
Integer num = (Integer) obj;  // ClassCastException!

// Solution - use instanceof
if (obj instanceof Integer) {
    Integer num = (Integer) obj;
}

ConcurrentModificationException

// Problem - modifying list while iterating
List<String> list = new ArrayList<>();
list.add("A");
for (String s : list) {
    if ("A".equals(s)) {
        list.remove(s);  // CME!
    }
}

// Solution - use iterator
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    if ("A".equals(it.next())) {
        it.remove();
    }
}

Java Version Features

Version Year Key Features
Java 8 2014 Lambdas, Streams, Optional, Default Methods
Java 9 2017 Modules, Private Interface Methods
Java 10 2018 Local-Variable Type Inference (var)
Java 11 2018 HTTP Client, String Methods
Java 12 2019 Switch Expressions
Java 14 2020 Records, Pattern Matching for instanceof
Java 16 2021 Sealed Classes
Java 17 2021 Sealed Classes, Pattern Matching
Java 18 2022 UTF-8 by Default
Java 19 2022 Virtual Threads (Preview)
Java 20 2023 Scoped Values, Virtual Threads

Learning Path Summary

Beginner (Parts 1-3)

  • Variables, data types, operators
  • Control flow (if, switch, loops)
  • Methods and arrays

Intermediate

  • Classes and objects
  • Constructors
  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstract classes and interfaces
  • Exception handling

Advanced

  • Collections framework
  • Generics
  • Lambda expressions
  • Stream API
  • Functional interfaces
  • Method references
  • Optional
  • Multithreading
  • File I/O
  • Date/Time API
  • Annotations

Related Guides


You've completed the Java learning journey! Keep practicing and building projects! 🚀

Clone this wiki locally