# Java Complete Reference Guide ## Table of Contents - [Data Types](#data-types) - [Operators](#operators) - [Control Flow](#control-flow) - [Classes and Objects](#classes-and-objects) - [Inheritance and Polymorphism](#inheritance-and-polymorphism) - [Interfaces and Abstract Classes](#interfaces-and-abstract-classes) - [Exception Handling](#exception-handling) - [Collections](#collections) - [Generics](#generics) - [Lambda Expressions and Streams](#lambda-expressions-and-streams) - [Common Methods Quick Reference](#common-methods-quick-reference) - [Best Practices](#best-practices) - [Common Errors and Solutions](#common-errors-and-solutions) --- ## 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 ```java // 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 ```java + // 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 ```java == // Equal to != // Not equal to > // Greater than < // Less than >= // Greater or equal <= // Less or equal ``` ### Logical Operators ```java && // Logical AND || // Logical OR ! // Logical NOT & // Bitwise AND | // Bitwise OR ^ // Bitwise XOR ~ // Bitwise NOT << // Left shift >> // Right shift >>> // Unsigned right shift ``` ### Ternary Operator ```java String result = (condition) ? "true" : "false"; ``` --- ## Control Flow ### If-Else ```java if (condition) { // code } else if (condition2) { // code } else { // code } ``` ### Switch ```java 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 ```java // Traditional for (int i = 0; i < 10; i++) { // code } // For-each for (Type item : collection) { // code } ``` ### While Loop ```java while (condition) { // code } do { // code (runs at least once) } while (condition); ``` ### Loop Control ```java break; // Exit loop continue; // Skip to next iteration ``` --- ## Classes and Objects ### Class Definition ```java 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 ```java ClassName obj = new ClassName(argument); ``` ### Access Modifiers | Modifier | Class | Package | Subclass | World | |----------|-------|---------|----------|-------| | `public` | ✓ | ✓ | ✓ | ✓ | | `protected` | ✓ | ✓ | ✓ | ✗ | | `default` | ✓ | ✓ | ✗ | ✗ | | `private` | ✓ | ✗ | ✗ | ✗ | ### Static vs Instance ```java 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 ```java 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 ```java public class Child extends Parent { public Child() { super(); // Call parent constructor } public void childMethod() { super.method(); // Call parent method } } ``` ### Polymorphism ```java Parent obj = new Child(); // Reference type Parent, object type Child obj.method(); // Calls Child's implementation ``` ### final Keyword ```java 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 ```java 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 ```java public abstract class AbstractClass { // Abstract method - no body public abstract void abstractMethod(); // Regular method public void regularMethod() { // implementation } } ``` ### Implementing ```java public class ConcreteClass implements InterfaceName, AnotherInterface { @Override public void method1() { } @Override public void anotherMethod() { } } ``` --- ## Exception Handling ### Try-Catch-Finally ```java try { // Code that might throw exception } catch (ExceptionType1 e) { // Handle ExceptionType1 } catch (ExceptionType2 e) { // Handle ExceptionType2 } finally { // Always executes } ``` ### Common Exceptions ```java 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 ```java public void method() throws IOException { if (error) { throw new IOException("Error message"); } } ``` ### Custom Exception ```java public class MyException extends Exception { public MyException() { } public MyException(String message) { super(message); } } ``` --- ## Collections ### List Implementations ```java List arrayList = new ArrayList<>(); // Fast random access List linkedList = new LinkedList<>(); // Fast insert/delete List vector = new Vector<>(); // Thread-safe ``` ### Set Implementations ```java Set hashSet = new HashSet<>(); // No order, fast Set linkedHashSet = new LinkedHashSet<>(); // Insertion order Set treeSet = new TreeSet<>(); // Sorted order ``` ### Map Implementations ```java Map hashMap = new HashMap<>(); // No order Map linkedHashMap = new LinkedHashMap<>(); // Insertion order Map treeMap = new TreeMap<>(); // Sorted by keys Map hashTable = new Hashtable<>(); // Thread-safe ``` ### Collection Methods ```java // 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 ```java 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 ```java class Box { private T content; public void set(T content) { this.content = content; } public T get() { return content; } } // Usage Box stringBox = new Box<>(); Box intBox = new Box<>(); ``` ### Generic Method ```java public static void print(T item) { System.out.println(item); } public static > T max(T a, T b) { return a.compareTo(b) > 0 ? a : b; } ``` ### Wildcards ```java // ? extends Type - read-only void read(List list) { } // ? super Type - write-only void write(List list) { } // Unbounded void process(List list) { } ``` --- ## Lambda Expressions and Streams ### Lambda Syntax ```java // No parameters () -> expression // One parameter param -> expression (param) -> expression // Multiple parameters (a, b) -> expression // Multiple statements (a, b) -> { // statements return result; } ``` ### Common Functional Interfaces ```java Predicate // T -> boolean Function // T -> R Consumer // T -> void Supplier // () -> T UnaryOperator // T -> T BinaryOperator // (T, T) -> T ``` ### Stream Operations ```java // 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 ```java 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 ```java 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 ```java 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 ```java 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 ```java // 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 ```java // 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 ```java // 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 ```java // 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 ```java // Problem Object obj = "Hello"; Integer num = (Integer) obj; // ClassCastException! // Solution - use instanceof if (obj instanceof Integer) { Integer num = (Integer) obj; } ``` ### ConcurrentModificationException ```java // Problem - modifying list while iterating List list = new ArrayList<>(); list.add("A"); for (String s : list) { if ("A".equals(s)) { list.remove(s); // CME! } } // Solution - use iterator Iterator 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 - [Java Beginner Part 1](./Java-Beginner-Guide.md) - Fundamentals - [Java Beginner Part 2](./Java-Beginner-Part2.md) - Control Flow - [Java Beginner Part 3](./Java-Beginner-Part3.md) - Methods & Arrays - [Java Intermediate Guide](./Java-Intermediate-Guide.md) - OOP Deep Dive - [Java Advanced Guide](./Java-Advanced-Guide.md) - Modern Java --- *You've completed the Java learning journey! Keep practicing and building projects! 🚀*