Java Comparisons

All important differences and comparisons at one place for quick revision

Unit I: Java Fundamentals

JDK vs JRE vs JVM Unit I

Aspect JDK JRE JVM
Full Form Java Development Kit Java Runtime Environment Java Virtual Machine
Purpose Develop + Run Java programs Run Java programs Execute bytecode
Contains JRE + Dev tools (javac, jdb) JVM + Libraries Execution engine
User Developers End users Internal component
Platform Platform dependent Platform dependent Platform dependent

Method Overloading vs Method Overriding Unit I

Aspect Method Overloading Method Overriding
Definition Same method name, different parameters Same method signature in parent-child
Polymorphism Compile-time (Static) Runtime (Dynamic)
Classes Within same class Between parent-child classes
Parameters Must be different Must be same
Return Type Can be different Must be same or covariant
Access Modifier Can be any Cannot be more restrictive
static/private/final Can be overloaded Cannot be overridden
Binding Early binding Late binding

Abstract Class vs Interface Unit I

Aspect Abstract Class Interface
Methods Abstract + Concrete methods Abstract (default/static since Java 8)
Variables Any type (instance, static, final) Only public static final (constants)
Constructors Can have constructors Cannot have constructors
Inheritance Single (extends one) Multiple (implements many)
Access Modifiers Any access modifier Methods public by default
Keyword extends implements
When to Use Share code among related classes Define contract for unrelated classes

== vs equals() Unit I

Aspect == Operator equals() Method
Type Operator Method (Object class)
For Primitives Compares values Cannot be used
For Objects Compares references (memory address) Compares content (if overridden)
Override Cannot be overridden Can be overridden
Null Safe Yes No (throws NPE)

String vs StringBuilder vs StringBuffer Unit I

Aspect String StringBuilder StringBuffer
Mutability Immutable Mutable Mutable
Thread Safe Yes (immutable) No Yes (synchronized)
Performance Slow for modifications Fastest Slower than StringBuilder
Storage String Pool + Heap Heap only Heap only
When to Use Few modifications Single-threaded, many modifications Multi-threaded, many modifications

this vs super Keyword Unit I

Aspect this super
Refers to Current class instance Immediate parent class
Variables Access current class variables Access parent class variables
Methods Invoke current class methods Invoke parent class methods
Constructor this() - current class constructor super() - parent class constructor
Static Context Cannot be used Cannot be used

final vs finally vs finalize Unit I

Aspect final finally finalize
Type Keyword Block Method
Purpose Restrict modification Execute cleanup code Cleanup before GC
Usage Variable, method, class With try-catch Object class method
Execution Compile time check Always executes Called by GC (uncertain)

Access Modifiers Unit I

Modifier Same Class Same Package Subclass (Diff Pkg) Different Package
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No

Abstraction vs Encapsulation Unit I

Aspect Abstraction Encapsulation
Focus WHAT an object does HOW an object does it
Hides Implementation complexity Data from outside
Achieved By Abstract class, Interface Private fields, public methods
Level Design level Implementation level
Example Interface methods Getters/Setters

Unit II: Exception Handling, I/O, Multithreading

Checked vs Unchecked Exceptions Unit II

Aspect Checked Exceptions Unchecked Exceptions
Checked at Compile time Runtime
Handling Must handle (try-catch) or declare (throws) Optional to handle
Inheritance Extends Exception (not RuntimeException) Extends RuntimeException
Examples IOException, SQLException, FileNotFoundException NullPointerException, ArithmeticException
Cause External resources (file, network, DB) Programming errors (logic bugs)
Recovery Usually recoverable Usually indicates bugs

throw vs throws Unit II

Aspect throw throws
Purpose Actually throws an exception Declares exceptions method might throw
Location Inside method body In method signature
Syntax throw new Exception() method() throws Exception
Number One exception at a time Multiple exceptions (comma-separated)
Followed by Exception instance Exception class name(s)

Byte Stream vs Character Stream Unit II

Aspect Byte Stream Character Stream
Data Unit 8-bit bytes 16-bit Unicode characters
Base Classes InputStream, OutputStream Reader, Writer
Use For Binary data (images, audio, video) Text data
File Classes FileInputStream, FileOutputStream FileReader, FileWriter
Buffered Classes BufferedInputStream, BufferedOutputStream BufferedReader, BufferedWriter

Process vs Thread Unit II

Aspect Process Thread
Definition Independent program in execution Lightweight subprocess within process
Memory Own memory space (heap, stack) Shares memory with parent process
Communication Inter-process communication (IPC) - complex Direct via shared memory
Overhead Heavy - more resources Light - less resources
Creation Time Slower Faster
Context Switch Expensive Cheaper
Failure Impact One crash doesn't affect others Thread crash can affect entire process

wait() vs sleep() Unit II

Aspect wait() sleep()
Class Object Thread
Lock Releases the lock Holds the lock
Context Must be in synchronized block Can be called anywhere
Wake up notify()/notifyAll() or timeout After time elapsed
Purpose Inter-thread communication Pause execution
Static No (instance method) Yes (static method)

extends Thread vs implements Runnable Unit II

Aspect extends Thread implements Runnable
Inheritance Cannot extend another class Can extend another class
Reusability Less reusable More reusable
Thread Pool Cannot use directly Works with ExecutorService
Overhead Each object is a thread Separates task from thread
Recommendation Less preferred Preferred approach

Runnable vs Callable Unit II

Aspect Runnable Callable
Method run() call()
Return Type void (no return) Generic type V
Exceptions Cannot throw checked exceptions Can throw checked exceptions
Usage Thread, ExecutorService ExecutorService only
Result Cannot return result Returns Future<V>

synchronized vs volatile Unit II

Aspect synchronized volatile
Atomicity Yes (compound operations) No (only read/write)
Visibility Yes Yes
Blocking Yes (acquires lock) No
Use On Methods, blocks Variables only
Performance Slower Faster
When to Use Compound operations, mutual exclusion Simple flags, single writes

Unit III: Modern Java Features

Intermediate vs Terminal Operations (Streams) Unit III

Aspect Intermediate Operations Terminal Operations
Return Type Returns Stream Returns non-Stream (void, Optional, etc.)
Execution Lazy - not executed until terminal called Eager - triggers pipeline execution
Chaining Can be chained Ends the pipeline
Examples filter, map, flatMap, sorted, distinct, peek, limit, skip forEach, collect, reduce, count, min, max, findFirst

Lambda vs Anonymous Class Unit III

Aspect Lambda Expression Anonymous Class
Syntax Concise: (x) -> x * 2 Verbose: new Interface() { ... }
Interface Only functional interfaces Any interface or abstract class
this Keyword Refers to enclosing class Refers to anonymous class itself
State Cannot have state (fields) Can have instance variables
Compilation Uses invokedynamic Creates separate .class file

Functional Interface Types Unit III

Interface Method Input Output Use Case
Predicate<T> test(T t) T boolean Filtering, conditions
Function<T,R> apply(T t) T R Transformations
Consumer<T> accept(T t) T void Side effects
Supplier<T> get() None T Factory, lazy values
BiFunction<T,U,R> apply(T t, U u) T, U R Two-input transform
UnaryOperator<T> apply(T t) T T Same type transform

Stream vs Collection Unit III

Aspect Collection Stream
Storage Stores elements Doesn't store elements
Modification Can add/remove elements Cannot modify source
Iteration External iteration Internal iteration
Traversal Multiple times Single traversal only
Evaluation Eager Lazy
Parallelism Manual Built-in (parallelStream)

map() vs flatMap() Unit III

Aspect map() flatMap()
Transformation One-to-one One-to-many (flattened)
Output Stream<Stream<R>> possible Stream<R> (flattened)
Function returns Single value Stream of values
Use case Simple transformations Nested collections/Optional

Unit IV: Collections Framework

ArrayList vs LinkedList Unit IV

Aspect ArrayList LinkedList
Internal Structure Dynamic array Doubly linked list
Random Access O(1) - excellent O(n) - poor
Insert at beginning O(n) - shifts elements O(1) - just update links
Insert at end O(1) amortized O(1)
Memory Contiguous, less overhead Non-contiguous, more overhead
Cache Locality Good Poor
Implements List, RandomAccess List, Deque, Queue

HashSet vs LinkedHashSet vs TreeSet Unit IV

Aspect HashSet LinkedHashSet TreeSet
Internal Structure Hash table Hash table + Linked list Red-Black tree
Ordering No order Insertion order Sorted order
Performance O(1) O(1) O(log n)
Null Elements One null allowed One null allowed No null
Memory Less More More

HashMap vs LinkedHashMap vs TreeMap Unit IV

Aspect HashMap LinkedHashMap TreeMap
Internal Structure Hash table Hash table + Linked list Red-Black tree
Ordering No order Insertion/Access order Sorted by keys
Performance O(1) O(1) O(log n)
Null Keys One allowed One allowed Not allowed
Thread-safe No No No

HashMap vs Hashtable Unit IV

Aspect HashMap Hashtable
Thread Safety Not synchronized Synchronized (thread-safe)
Null Keys One null key allowed Not allowed
Null Values Multiple allowed Not allowed
Performance Faster Slower
Inheritance AbstractMap Dictionary (legacy)
Introduced Java 1.2 Java 1.0

Comparable vs Comparator Unit IV

Aspect Comparable Comparator
Package java.lang java.util
Method compareTo(Object o) compare(Object o1, Object o2)
Implementation Class itself implements Separate class or lambda
Sort Sequences Single natural ordering Multiple custom orderings
Modification Requires modifying original class No modification needed

Iterator vs ListIterator Unit IV

Aspect Iterator ListIterator
Direction Forward only Forward and backward
Methods hasNext(), next() + hasPrevious(), previous()
Modification remove() only + add(), set()
Index Access No nextIndex(), previousIndex()
Works With Any Collection List only

Fail-fast vs Fail-safe Iterator Unit IV

Aspect Fail-fast Fail-safe
Concurrent Modification Throws ConcurrentModificationException No exception
Works On Original collection Clone of collection
Memory No extra memory Extra memory for clone
Examples ArrayList, HashMap ConcurrentHashMap, CopyOnWriteArrayList

List vs Set vs Map Unit IV

Aspect List Set Map
Duplicates Allowed Not allowed Duplicate values allowed, not keys
Ordering Maintains insertion order Depends on implementation Depends on implementation
Null Multiple nulls allowed One null (HashSet) One null key (HashMap)
Index Access Yes (get(i)) No By key (get(key))
Examples ArrayList, LinkedList HashSet, TreeSet HashMap, TreeMap

Unit V: Spring Framework

Spring vs Spring Boot Unit V

Aspect Spring Framework Spring Boot
Configuration Manual (XML or Java config) Auto-configuration
Server External (Tomcat, Jetty) Embedded server
Dependencies Manage individually Starter dependencies
Setup Time Longer Minimal
Deployment WAR to external server JAR with embedded server
Properties Multiple config files application.properties/yml

BeanFactory vs ApplicationContext Unit V

Aspect BeanFactory ApplicationContext
Bean Loading Lazy (on request) Eager (at startup)
AOP Support No Yes
i18n No Yes (MessageSource)
Event Publishing No Yes
Web Support No Yes (WebApplicationContext)
Use Case Simple apps, memory constrained Enterprise applications

Constructor vs Setter vs Field Injection Unit V

Aspect Constructor Setter Field
Recommended Yes (preferred) Sometimes No
Immutability Supports (final fields) No No
Required Dependencies Best for required Best for optional No indication
Testing Easy (no reflection) Easy Needs reflection
Circular Dependencies Prevented Allowed Allowed

@Controller vs @RestController Unit V

Aspect @Controller @RestController
Return Type View name (String) Data (JSON/XML)
@ResponseBody Required on each method Implicit on all methods
Use Case MVC web applications REST APIs
Combines @Component @Controller + @ResponseBody

@PathVariable vs @RequestParam Unit V

Aspect @PathVariable @RequestParam
Source URL path: /users/{id} Query string: /users?id=123
Required Yes by default Yes by default (configurable)
Default Value Not supported Supported (defaultValue)
RESTful More RESTful (resource identifier) For filtering, pagination

Stereotype Annotations Unit V

Annotation Layer Special Behavior Use Case
@Component Any Base annotation Generic beans
@Service Service Semantic clarity Business logic
@Repository DAO Exception translation Data access
@Controller Web MVC controller Web requests
@RestController REST @Controller + @ResponseBody REST APIs

Bean Scopes Unit V

Scope Instances Lifecycle Use Case
singleton One per container Container lifetime Stateless services, DAO
prototype New per request Client manages Stateful beans
request One per HTTP request Request lifetime Request data
session One per HTTP session Session lifetime User session data
application One per ServletContext Application lifetime Application-wide data