DEV Community

DevCorner
DevCorner

Posted on

Core Java: Essential Concepts and Internals

1. JVM, JDK, JRE, and Just-In-Time (JIT) Compiler

JVM (Java Virtual Machine)

The JVM is an abstract machine that enables Java bytecode to be executed on any platform. It provides features such as memory management, garbage collection, and security.

JDK (Java Development Kit)

JDK is a complete package for Java development, including:

  • Java Compiler (javac)
  • JRE (Java Runtime Environment)
  • Development tools (debuggers, documentation, etc.)

JRE (Java Runtime Environment)

JRE contains the necessary libraries and JVM required to run Java applications but does not include development tools like the compiler.

JIT (Just-In-Time) Compiler

JIT Compiler optimizes Java bytecode into native machine code at runtime, improving execution speed by reducing interpretation overhead.


2. Garbage Collection (GC) in Java

What is Garbage Collection?

Garbage Collection (GC) is an automatic memory management process that reclaims unused objects, preventing memory leaks.

Types of GC Algorithms in Java

  1. Serial GC - Suitable for small applications, single-threaded.
  2. Parallel GC (Throughput Collector) - Uses multiple threads for better performance.
  3. CMS (Concurrent Mark-Sweep) GC - Low-latency, concurrent collection.
  4. G1 (Garbage First) GC - Designed for large heap sizes, replaces CMS in newer versions.
  5. ZGC & Shenandoah GC - Ultra-low latency collectors for large applications.

3. Immutability in Java

What is Immutability?

An immutable object cannot be modified after its creation. Examples include String, Integer, Double.

How to Make a Class Immutable?

  1. Declare the class as final.
  2. Mark all fields as private and final.
  3. Provide only getter methods (no setters).
  4. Use defensive copying for mutable fields.
  5. Ensure methods don’t modify the object’s state.

Example:

public final class ImmutableExample {
    private final int value;

    public ImmutableExample(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Difference Between String, StringBuffer, and StringBuilder

Feature String StringBuffer StringBuilder
Mutability Immutable Mutable Mutable
Thread-Safety Yes (Immutable) Yes (Synchronized) No
Performance Slow (new object creation) Slower due to synchronization Fast

5. Java Memory Areas

1. Heap Memory

  • Stores objects and class instances.
  • Divided into Young (Eden, Survivor) and Old (Tenured) generations.

2. Stack Memory

  • Stores method calls, local variables, and references.

3. Metaspace (Replaces PermGen)

  • Stores class metadata.

6. Fail-Fast vs. Fail-Safe Iterators

Feature Fail-Fast Fail-Safe
Behavior Throws ConcurrentModificationException if modified while iterating Doesn’t throw an exception
Implementation Uses original collection Works on a cloned copy
Examples ArrayList, HashMap CopyOnWriteArrayList, ConcurrentHashMap

7. How HashMap Works Internally in Java 8

  1. Uses an array of Node<K, V> (buckets).
  2. Uses hashCode() to determine bucket index.
  3. Handles collisions via linked list or balanced tree (for large chains).
  4. Uses equals() to compare keys for retrieval.
  5. Resizes dynamically (threshold: load factor 0.75).

8. Difference Between Comparator and Comparable

Feature Comparator Comparable
Purpose Custom sorting Default natural ordering
Interface java.util.Comparator java.lang.Comparable
Method compare(T o1, T o2) compareTo(T o)
Multiple Sorting Yes No

Example:

// Using Comparable
class Student implements Comparable<Student> {
    private int age;
    public int compareTo(Student s) { return this.age - s.age; }
}

// Using Comparator
class AgeComparator implements Comparator<Student> {
    public int compare(Student s1, Student s2) { return s1.age - s2.age; }
}
Enter fullscreen mode Exit fullscreen mode

9. WeakHashMap, LinkedHashMap, and TreeMap

WeakHashMap

  • Uses weak references for keys.
  • Entries get removed when no strong references exist.

LinkedHashMap

  • Maintains insertion order.
  • Useful for caching (supports access-order mode).

TreeMap

  • Implements NavigableMap.
  • Keeps keys sorted based on natural ordering or Comparator.

10. Why Override hashCode() and equals()?

  • Ensures correct behavior in HashMap, HashSet, and Hashtable.
  • Prevents duplicate keys in collections.
  • Objects must be consistent (equals() true → same hashCode()).

Example:

@Override
public int hashCode() {
    return Objects.hash(id, name);
}

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null || getClass() != obj.getClass()) return false;
    MyClass myClass = (MyClass) obj;
    return id == myClass.id && Objects.equals(name, myClass.name);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding these Core Java concepts is crucial for writing efficient, high-performance applications. Whether preparing for interviews or optimizing your projects, mastering these topics will enhance your Java expertise.

Top comments (0)