Cosmic Module
J
Qubits of DPK
March 14, 2026
Core Java
Purpose: Read this the night before your interview. Every 30-second answer in one place.
Java Fundamentals
Java Introduction
Java is a strongly-typed, object-oriented language that compiles to platform-independent bytecode executed by the JVM. Key strengths: portability, rich ecosystem, automatic GC, strong concurrency support.
How Java Works
javac compiles .java to bytecode (.class). JVM Class Loader loads it. Execution Engine runs it via Interpreter + JIT Compiler. GC manages heap. Write Once Run Anywhere.
JDK vs JRE vs JVM
JVM runs bytecode, platform dependent. JRE = JVM + class libraries, for running. JDK = JRE + dev tools (javac, jar, jdb), for developing.
Variables
Three types: local (method scope, no default), instance (object scope, has default, heap), static (class scope, shared, Method Area).
Data Types & Conversion
Data Types
8 primitives: byte/short/int/long (integers), float/double (decimals), char (Unicode character), boolean (true/false). Primitives in stack, non-primitives reference heap objects.
Literals
6 types: integer (decimal/binary 0b/octal 0/hex 0x), floating-point (double default, float needs f), character (single quotes, Unicode u), String (double quotes, String Pool), boolean (lowercase true/false), null (reference types only).
Type Conversion
Widening automatic (small to large, no loss). Narrowing manual via cast operator (data loss possible via truncation/overflow). byte/short/char auto-promoted to int in expressions.
️ Operators
All Operators
Arithmetic (watch int division), Unary (pre vs post increment), Assignment shorthand, Relational (never == for Strings), Logical (short-circuit evaluation order matters for null safety), Bitwise (XOR in DSA), Shift (fast multiply/divide by 2), Ternary (one-line if-else).
Conditional Statements
Conditionals
if/else/ladder/nested if for conditions. Switch for fixed values - break mandatory to prevent fall-through. Java 14+ enhanced switch with -> eliminates fall-through. Ternary for value assignment only.
Loops
Loops
for (known count), while (condition first, may not execute), do-while (body first, guaranteed once - menus/validation), for-each (read-only collection iteration, can't modify primitives or access index). break exits loop, continue skips iteration. Nested = O(n²).
️ OOP: Class & Object
Class and Object
Class = blueprint (fields + methods). Object = instance created with new, reference in stack, data in heap. Each object has independent copy of instance fields. this = current object reference. NullPointerException when calling method on null reference.
Why 1 Public Class Per File
ClassLoader finds classes by filename. Public = accessible everywhere = must be findable. Two public classes = naming conflict. Non-public classes have no restriction.
Static Keyword
Static Variable
Belongs to class, not object. One copy shared by all instances. Stored in Method Area. Initialized when class loads. Use for counters, constants (static final), config values.
Static Method
Belongs to class, no object needed. Cannot access instance variables or use this. main() is static because JVM calls it before any object exists. Ideal for utility/helper methods.
Static Block
Runs once automatically when class loads, before constructor, before main(). Used for one-time class-level setup: DB config, native library loading. Multiple blocks run in order.
Encapsulation
Encapsulation
Bundle data + methods, hide internal state with private fields, expose via public getters/setters with validation. Prevents invalid states, allows implementation change without breaking callers.
Constructors
Special method, same name as class, no return type, auto-called with new. Java provides default only if no constructor defined. Writing any constructor removes default. this() calls another constructor - must be first line.
Inheritance
Inheritance
Child acquires parent's fields/methods via extends. Single, multilevel, hierarchical supported. Multiple inheritance blocked (diamond problem) - use interfaces. super accesses parent members. super() calls parent constructor - must be first line. Constructors not inherited.
Method Overriding
Child redefines parent method - same name, same params, same return type. Resolved at runtime (dynamic polymorphism). Cannot override static/final/private. @Override annotation catches typos.
Access Modifiers
private (class only) < default (package) < protected (package + subclass) < public (everywhere).
Polymorphism
Polymorphism
Compile-time via overloading (same name, different params). Runtime via overriding + dynamic dispatch (JVM picks method based on actual object, not reference type).
Upcasting/Downcasting
Upcasting automatic (child ref to parent). Downcasting manual - can throw ClassCastException. Always instanceof check before downcast.
final Keyword
final variable = constant. final method = cannot override. final class = cannot extend (String is final).
equals() + hashCode()
Always override both together. Contract: if equals() true then hashCodes must match. Used by HashMap, HashSet internally.
Wrapper Classes
Wraps primitives as objects. Autoboxing (int to Integer automatic), unboxing (Integer to int automatic). Integer cache: -128 to 127 cached (== works), outside range == fails - always use equals().
Abstract & Interfaces
Abstract Class
Cannot instantiate. Mix of abstract (no body) + concrete methods. Has constructor. Use for IS-A with shared code.
Interface
Full contract - all methods abstract by default. No constructor. Variables are public static final. Class implements multiple interfaces (solves multiple inheritance). Java 8: default + static methods added.
Abstract vs Interface
Abstract: IS-A + shared code. Interface: CAN-DO capability contract + multiple implementation.
Exception Handling
Exceptions
Checked (compile-time, must handle: IOException), Unchecked (runtime, optional: NPE). throw explicitly throws. throws declares. finally always runs (cleanup). try-with-resources auto-closes AutoCloseable resources.
Custom Exception
Extend Exception (checked) or RuntimeException (unchecked). Call super(message). Throw with throw new CustomException(). Used in domain-specific error handling.
Multithreading
Threads
Runnable preferred over Thread (single inheritance). start() creates new thread, run() executes in current. Race condition = shared mutable state + no sync. synchronized = mutual exclusion. ExecutorService for production thread pools.
Thread States
New → Runnable → Running → Blocked/Waiting/TimedWaiting → Terminated.
Collections
Collections
List: ordered, duplicates (ArrayList fast access, LinkedList fast insert). Set: no duplicates (HashSet fastest, TreeSet sorted, LinkedHashSet ordered). Map: key-value (HashMap general, TreeMap sorted, LinkedHashMap ordered). Streams: lazy declarative pipelines - filter/map/reduce/sorted + terminal ops.
HashMap Internal
Array of buckets + linked list/tree per bucket. put(): hash key, find bucket, add. Collision: same bucket. Load factor 0.75, resizes at 75% capacity. Java 8: bucket converts to tree at 8 nodes (O(log n) vs O(n)).
Comparable vs Comparator
Comparable: natural ordering, implemented by the class itself (compareTo). Comparator: external custom ordering, passed to sort methods.