-
-
Notifications
You must be signed in to change notification settings - Fork 2
Java Complete Reference
Mattscreative edited this page Mar 9, 2026
·
1 revision
- Data Types
- Operators
- Control Flow
- Classes and Objects
- Inheritance and Polymorphism
- Interfaces and Abstract Classes
- Exception Handling
- Collections
- Generics
- Lambda Expressions and Streams
- Common Methods Quick Reference
- Best Practices
- Common Errors and Solutions
| 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 |
-
String- Text -
Arrays- Fixed-size collections -
Classes- Custom types -
Interfaces- Contracts
// 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);+ // Addition
- // Subtraction
* // Multiplication
/ // Division
% // Modulus (remainder)
++ // Increment
-- // Decrement
+= // Add and assign
-= // Subtract and assign
*= // Multiply and assign
/= // Divide and assign
%= // Modulus and assign== // Equal to
!= // Not equal to
> // Greater than
< // Less than
>= // Greater or equal
<= // Less or equal&& // Logical AND
|| // Logical OR
! // Logical NOT
& // Bitwise AND
| // Bitwise OR
^ // Bitwise XOR
~ // Bitwise NOT
<< // Left shift
>> // Right shift
>>> // Unsigned right shiftString result = (condition) ? "true" : "false";if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}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";
};// Traditional
for (int i = 0; i < 10; i++) {
// code
}
// For-each
for (Type item : collection) {
// code
}while (condition) {
// code
}
do {
// code (runs at least once)
} while (condition);break; // Exit loop
continue; // Skip to next iterationpublic 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
}
}ClassName obj = new ClassName(argument);| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
public |
✓ | ✓ | ✓ | ✓ |
protected |
✓ | ✓ | ✓ | ✗ |
default |
✓ | ✓ | ✗ | ✗ |
private |
✓ | ✗ | ✗ | ✗ |
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()
}public class Parent {
public void method() { }
}
public class Child extends Parent {
// Inherits method() automatically
@Override
public void method() { // Override parent method
// new implementation
}
}public class Child extends Parent {
public Child() {
super(); // Call parent constructor
}
public void childMethod() {
super.method(); // Call parent method
}
}Parent obj = new Child(); // Reference type Parent, object type Child
obj.method(); // Calls Child's implementationfinal class CannotExtend { } // Class cannot be extended
class Example {
final int CONSTANT = 100; // Cannot be changed
final void cannotOverride() { } // Cannot be overridden
}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() { }
}public abstract class AbstractClass {
// Abstract method - no body
public abstract void abstractMethod();
// Regular method
public void regularMethod() {
// implementation
}
}public class ConcreteClass implements InterfaceName, AnotherInterface {
@Override
public void method1() { }
@Override
public void anotherMethod() { }
}try {
// Code that might throw exception
} catch (ExceptionType1 e) {
// Handle ExceptionType1
} catch (ExceptionType2 e) {
// Handle ExceptionType2
} finally {
// Always executes
}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 argumentpublic void method() throws IOException {
if (error) {
throw new IOException("Error message");
}
}public class MyException extends Exception {
public MyException() { }
public MyException(String message) {
super(message);
}
}List<Type> arrayList = new ArrayList<>(); // Fast random access
List<Type> linkedList = new LinkedList<>(); // Fast insert/delete
List<Type> vector = new Vector<>(); // Thread-safeSet<Type> hashSet = new HashSet<>(); // No order, fast
Set<Type> linkedHashSet = new LinkedHashSet<>(); // Insertion order
Set<Type> treeSet = new TreeSet<>(); // Sorted orderMap<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// 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.put(key, value);
map.get(key);
map.containsKey(key);
map.containsValue(value);
map.remove(key);
map.keySet();
map.values();
map.entrySet();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<>();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;
}// ? 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) { }// No parameters
() -> expression
// One parameter
param -> expression
(param) -> expression
// Multiple parameters
(a, b) -> expression
// Multiple statements
(a, b) -> {
// statements
return result;
}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// 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()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.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.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.ESystem.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// 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;// 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 { }
}-
Prefer immutability - Use
finalfor fields that don't change - Minimize mutability - Make classes immutable when possible
- Favor composition over inheritance
- Use interfaces - Program to interfaces, not implementations
- Prefer for-each loops - Cleaner than iterator loops
- Check for null - Use Optional or null checks
- Use exceptions only for exceptional conditions
- Follow single responsibility - One class, one purpose
- Write clear comments - Explain why, not what
- Write tests - Unit tests catch bugs early
// 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()));// 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]);
}// Problem
Object obj = "Hello";
Integer num = (Integer) obj; // ClassCastException!
// Solution - use instanceof
if (obj instanceof Integer) {
Integer num = (Integer) obj;
}// 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();
}
}| 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 |
- Variables, data types, operators
- Control flow (if, switch, loops)
- Methods and arrays
- Classes and objects
- Constructors
- Encapsulation
- Inheritance
- Polymorphism
- Abstract classes and interfaces
- Exception handling
- Collections framework
- Generics
- Lambda expressions
- Stream API
- Functional interfaces
- Method references
- Optional
- Multithreading
- File I/O
- Date/Time API
- Annotations
- Java Beginner Part 1 - Fundamentals
- Java Beginner Part 2 - Control Flow
- Java Beginner Part 3 - Methods & Arrays
- Java Intermediate Guide - OOP Deep Dive
- Java Advanced Guide - Modern Java
You've completed the Java learning journey! Keep practicing and building projects! 🚀