Back🧩

Java Interview Concepts

AWAKENING0 / 100
[░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░]0%

Java Interview Concepts

Coding & Logic·intermediate·~25 min read

  • java
  • spring-boot
  • oop
  • collections
  • concurrency
  • interview

What you'll learn

  • 1. Interfaces vs Abstract Classes

  • Abstract Classes

  • Interfaces (Java 8+)

  • Default Methods (Java 8)

    Default methods allow adding new behavior to interfaces without breaking existing implementations. Key rules: - Can only call other interface methods (no access to instance state) - Main use case: higher-level convenience methods - Origi…

  • Comparison Table

    | Feature | Interface | Abstract Class | |---------|-----------|---------------| | Fields | Only static final constants | Any fields (private state) | | Constructors | No | Yes | | Multiple inheritance | Yes (implement many) | No (extend…

  • 2. Java Collections Framework

  • Collection Hierarchy

  • Map (Separate Hierarchy)

  • Key Implementations

    | Interface | Implementation | Ordering | Null | Thread-safe | |-----------|---------------|----------|------|-------------| | List | ArrayList | Insertion order | Yes | No | | List | LinkedList | Insertion order | Yes | No | | Set | Has…

  • List vs Set vs Map

    | Need | Use | |------|-----| | Ordered, duplicates allowed, index access | List (ArrayList for random access, LinkedList for frequent insert/delete) | | Unique elements, no duplicates | Set (HashSet for O(1) lookup, TreeSet for sorted)…

  • HashMap Internal Storage

    How HashMap works: 1. Compute key.hashCode() → bucket index 2. If bucket empty → store directly 3. If bucket occupied (collision) → linked list (Java 7) or red-black tree when >8 entries (Java 8+) 4. On get(): hash → bucket → traverse ch…

  • 3. Spring Boot

  • What Spring Boot Provides

    Spring Boot is an opinionated framework that auto-configures Spring applications with sensible defaults.

  • @SpringBootApplication (Combines Three)

  • Application Startup Process

  • Layered Architecture

    | Layer | Responsibility | Annotation | |-------|---------------|-----------| | Controller | HTTP request handling, validation | @RestController, @Controller | | Service | Business logic, transaction management | @Service | | Repository…

  • Dependency Injection

    | DI Type | Annotation | When | |---------|-----------|------| | Constructor | @Autowired on constructor | Preferred — immutable | | Setter | @Autowired on setter | Optional dependencies | | Field | @Autowired on field | Avoid — hard to…

  • Key Annotations

    | Annotation | Purpose | |-----------|---------| | @RestController | Controller + ResponseBody (returns JSON) | | @RequestMapping | Map URL to handler method | | @GetMapping / @PostMapping | HTTP method-specific mapping | | @PathVariable…

  • IoC Container (Inversion of Control)

    The Spring container manages object lifecycle and dependencies: ---

  • 4. Logging in Java

  • Facade Pattern for Logging

    Why use a facade? - Code depends on SLF4J API only - Switch implementation (Logback ↔ Log4j2) by changing only the dependency - Library authors use SLF4J → consumers choose their own backend

  • Log Levels (Severity Order)

  • Logback vs Log4j2

    | Feature | Logback | Log4j2 | |---------|---------|--------| | Async logging | Plugin | Built-in (faster) | | Lazy message eval | Via {} placeholders | Via lambda + {} | | Configuration | logback.xml | log4j2.xml | | Performance | Good…

  • 5. Concurrency in Java

  • Thread Creation

  • Synchronized & Locks

  • Key Concurrency Concepts

    | Concept | Meaning | |---------|---------| | volatile | Variable always read from main memory (visibility guarantee) | | synchronized | Mutual exclusion + happens-before guarantee | | AtomicInteger | Lock-free thread-safe integer (CAS o…

  • sleep vs wait vs notify (Common Interview Question)

    | Method | Class | Lock Released? | Purpose | |--------|-------|---------------|---------| | Thread.sleep(ms) | Thread | No — holds lock during sleep | Pause current thread for fixed time | | obj.wait() | Object | Yes — releases the moni…

  • Thread Pool Sizing

    ---

  • 6. Java Memory Model

  • Heap vs Stack

  • Garbage Collection Basics

    | GC Algorithm | Use Case | |-------------|----------| | Serial | Single-threaded, small apps | | Parallel | Throughput-focused (batch) | | G1 (default Java 9+) | Balanced latency + throughput | | ZGC / Shenandoah | Ultra-low latency ( a…

  • Stream API Example

    ---

  • 8. Monitoring Spring Boot with Prometheus & Grafana

  • Monitoring Stack

    Why this pattern mirrors SLF4J: - Micrometer = metrics facade (like SLF4J is for logging). Your code uses Micrometer API — swap backend without code changes. - Prometheus = metrics storage + scraper. Pull-based: it pulls /actuator/promet…

  • Spring Boot Setup

    Dependencies needed: Configuration (application.properties): Key endpoint: http://localhost:8080/actuator/prometheus — exposes all metrics in Prometheus text format.

  • Key Metrics to Monitor

    | Metric | What It Shows | |--------|--------------| | systemcpuusage | Overall CPU usage of the system | | httpserverrequestssecondsmax | Latency of slowest API (can filter by URI) | | jvmmemorycommittedbytes{area="heap"} | JVM heap mem…

  • Prometheus Configuration

    Pattern: Prometheus pulls (not push) from your app. This means your app doesn't need to know about Prometheus — it just exposes an endpoint. Multiple Prometheus instances can scrape the same app independently. ---

  • 9. REST API Design Best Practices

  • REST vs SOAP

    | Aspect | SOAP | REST | |--------|------|------| | Protocol/Style | Protocol (strict rules) | Architectural style (guidelines) | | Data Format | XML only | JSON, XML, any (JSON preferred) | | Transport | HTTP, MQ, SMTP | HTTP only | | S…

  • Richardson Maturity Model

    Measures how RESTful an API is: Most production APIs are at Level 2. Level 3 (HATEOAS) is the gold standard but adds complexity.

  • HATEOAS (Hypermedia As The Engine Of Application State)

    Responses include links to related resources/actions, so clients discover the API dynamically: Benefit: Clients don't hardcode URLs; if API structure changes, links update automatically.

  • API Versioning Strategies

    | Strategy | Example | Used By | |----------|---------|---------| | URI path | /v1/users, /v2/users | Twitter | | Request parameter | /users?version=1 | Amazon | | Custom header | X-API-VERSION: 1 | Microsoft | | Media type (content nego…

  • Content Negotiation

    Client specifies desired format via Accept header: - Accept: application/json → JSON response - Accept: application/xml → XML response Server specifies what it sends via Content-Type header.

  • Key REST Best Practices

    | Practice | Example | |----------|---------| | Use nouns for resources | /users not /getUsers | | Use HTTP methods correctly | GET (read), POST (create), PUT (replace), PATCH (partial), DELETE (remove) | | Return proper status codes | 2…

  • 8. Immutable Classes

    An immutable class is one whose instances cannot be modified after creation. This is essential for thread-safety, use as HashMap keys, and defensive programming.

  • Rules for Creating Immutable Classes

    1. Declare the class as final (prevent subclass from breaking immutability) 2. Make all fields private final 3. No setter methods 4. Initialize all fields via constructor 5. For mutable fields (collections, Date, etc.), return defensive…

  • Example

  • Why Defensive Copies?

    Without defensive copies: With a defensive copy in the constructor, the internal list is independent of the caller's reference.

  • Common Pitfalls

    | Pitfall | Fix | |---------|-----| | Returning mutable field directly in getter | Return a deep copy | | Using Collections.unmodifiableList() only | Still shares reference to underlying list | | Not copying collection elements if they a…

  • 9. ConcurrentModificationException and Fail-Fast Iterators

  • The Problem

    Modifying a collection while iterating over it with a for-each or Iterator throws ConcurrentModificationException.

  • Why It Happens

    Java collections maintain a modCount (modification counter). The Iterator records the modCount when created. On each next() call, it compares the current modCount to its recorded value. Any structural modification via the collection (not…

  • Internal Mechanism

  • Safe Alternatives

    | Approach | When to Use | |----------|-------------| | Iterator.remove() | Remove current element during iteration | | Copy collection first | Need arbitrary add/remove during iteration | | CopyOnWriteArrayList | Concurrent reads, rare…

  • Safe removal with Iterator:

    ---

  • 10. Interface Implementation with Conflicting Exceptions

    When a class implements two interfaces where methods have the same signature but different declared exceptions, the implementing class must satisfy both contracts.

  • Rules

    - Return type: Must be a subtype of both declared return types (covariant return) - Exceptions: Can only throw exceptions that are compatible with ALL interface contracts (typically means no checked exceptions) - Method signature: If inc…

  • Summary

    | Concept | Key Takeaway | |---------|-------------| | Interface vs Abstract | Interface: no state, multiple inheritance; Abstract: state + constructors | | Default methods | Evolve interfaces without breaking implementations; no instanc…

← back to Coding & Logic

Java Interview Concepts — Coding & Logic | GoCrack | GoCrack