12. Java Core
T
Tuan Nguyen

12. Java Core

This section focuses on core Java concepts including JVM internals, memory management, collections, concurrency, exceptions, streams, generics, multithreading, and modern Java features commonly used in enterprise backend development.

1. Difference between JDK, JRE, and JVM?

This is one of the most common Java interview questions.


JVM

JVM stands for Java Virtual Machine.

It is the runtime engine that executes Java bytecode.

Responsibilities:

Load classes
Execute bytecode
Manage memory
Perform garbage collection
Handle threads

JVM is platform-dependent because each operating system has its own JVM implementation.


JRE

JRE stands for Java Runtime Environment.

JRE contains:

JVM
Core Java libraries
Runtime components

JRE is used to run Java applications.

It does not contain development tools.


JDK

JDK stands for Java Development Kit.

JDK contains:

JRE
Compiler (javac)
Debugger
Development tools

JDK is used to develop Java applications.


Relationship:

JDK
 └── JRE
      └── JVM

2. What is JVM?

JVM is the engine that executes Java bytecode.

When Java code is compiled:

User.java

becomes:

User.class

The .class file contains bytecode.

JVM loads and executes this bytecode.

Major JVM responsibilities:

Class loading
Memory management
Garbage collection
JIT compilation
Thread management
Security checks

JVM is one reason Java applications can run on multiple operating systems.


3. What is bytecode?

Bytecode is the intermediate compiled code generated by the Java compiler.

Example:

javac User.java

produces:

User.class

This .class file contains bytecode.

Bytecode is not machine code directly.

The JVM interprets or compiles bytecode into native machine instructions at runtime.

This enables Java portability.


4. Why is Java platform independent?

Java is platform independent because Java code compiles into bytecode instead of operating-system-specific machine code.

Flow:

Java Source Code
→ Bytecode
→ JVM
→ Native Machine Code

As long as a JVM exists for the operating system, the same bytecode can run there.

This is the meaning of:

Write Once, Run Anywhere

5. Difference between primitive type and reference type?


Primitive Types

Store actual values directly.

Examples:

int
long
double
boolean
char

Characteristics:

Faster
Fixed size
Stored directly
Cannot be null

Reference Types

Store memory references to objects.

Examples:

String
User
List
ArrayList

Characteristics:

Can be null
Stored in heap memory
More flexible
Object-oriented

6. What is autoboxing and unboxing?

Autoboxing automatically converts primitive types into wrapper objects.

Example:

Integer x = 5;

Internally:

Integer x = Integer.valueOf(5);

Unboxing converts wrapper objects back into primitives.

Example:

int y = x;

Internally:

int y = x.intValue();

Autoboxing simplifies working with collections and generics.


7. Difference between == and .equals()?

This is a very important interview question.


==

Compares memory references for objects.

Example:

String a = new String("abc");
String b = new String("abc");

a == b

Result:

false

because references are different.

For primitives, == compares actual values.


equals()

Compares logical content.

Example:

a.equals(b)

Result:

true

because String overrides equals().


8. What is hashCode()?

hashCode() returns an integer hash value representing an object.

It is heavily used in:

HashMap
HashSet
Hashtable

Example:

user.hashCode();

Hash-based collections use hashCode for fast lookup.


9. Contract between equals() and hashCode()?

Important rule:

If two objects are equal,
they must have same hashCode.

Example:

a.equals(b) == true

then:

a.hashCode() == b.hashCode()

must also be true.

Otherwise collections like HashMap behave incorrectly.


10. Why is String immutable?

String objects cannot change after creation.

Example:

String s = "abc";
s.concat("d");

Original string remains unchanged.

Reasons for immutability:

Security
Thread safety
String pool optimization
HashMap performance
Caching

String immutability is extremely important inside JVM internals.


11. Difference between String, StringBuilder, and StringBuffer?


String

Immutable.

Every modification creates new object.


StringBuilder

Mutable and not thread-safe.

Faster for single-threaded string manipulation.


StringBuffer

Mutable and thread-safe.

Methods are synchronized.

Slower than StringBuilder.


Main difference:

Type

Mutable

Thread-safe

String

No

Yes

StringBuilder

Yes

No

StringBuffer

Yes

Yes


12. What is String pool?

String pool is a special JVM memory area storing reusable String literals.

Example:

String a = "hello";
String b = "hello";

Both references may point to same pooled object.

Benefits:

Memory optimization
Reuse
Better performance

13. What is final keyword?

final means something cannot be changed further.


final variable

Cannot be reassigned.

final int x = 10;

final method

Cannot be overridden.


final class

Cannot be inherited.

Example:

public final class String

14. What is static keyword?

static belongs to the class instead of object instances.

Example:

static int count;

Shared among all objects.

Static members can be accessed without object creation.

Example:

Math.max()

15. Difference between checked and unchecked exception?


Checked Exception

Checked at compile time.

Example:

IOException
SQLException

Must be handled or declared.


Unchecked Exception

Occurs at runtime.

Example:

NullPointerException
IllegalArgumentException

Usually caused by programming mistakes.


16. Difference between throw and throws?


throw

Actually throws exception.

Example:

throw new RuntimeException();

throws

Declares possible exceptions.

Example:

public void test() throws IOException

17. What is try-with-resources?

Automatically closes resources.

Example:

try (BufferedReader br = new BufferedReader(...)) {

}

Java automatically calls:

close()

Benefits:

Cleaner code
Safer resource handling
Avoids resource leaks

18. Difference between ArrayList and LinkedList?

ArrayList

LinkedList

Dynamic array

Doubly linked list

Fast random access

Slow random access

Slow middle insertion

Faster middle insertion

Better cache locality

More memory overhead

ArrayList is more commonly used in real applications.


19. Difference between HashMap and HashSet?

HashMap stores key-value pairs.

Example:

Map<Integer, String>

HashSet stores unique values only.

Internally HashSet actually uses HashMap.


20. How does HashMap work internally?

HashMap uses:

Array + hash buckets

Flow:

  1. hashCode() calculated

  2. Bucket index determined

  3. Entry stored in bucket

  4. equals() used for collision comparison

Java 8 may convert large collision chains into balanced trees for better performance.

Average lookup complexity:

O(1)

21. Difference between HashMap and ConcurrentHashMap?

HashMap is not thread-safe.

ConcurrentHashMap is thread-safe.

ConcurrentHashMap allows concurrent reads/writes using advanced locking mechanisms.

Used in multithreaded systems.


22. What are generics?

Generics provide type safety at compile time.

Example:

List<String>

Benefits:

Type safety
Avoid casting
Cleaner code
Compile-time checks

Without generics:

List list

can store any object type.


23. What is Stream API?

Stream API provides functional-style data processing.

Example:

users.stream()
     .filter(u -> u.isActive())
     .map(User::getName)
     .toList();

Benefits:

Cleaner code
Functional operations
Parallel processing support

24. Difference between map() and flatMap()?


map()

Transforms one element into one element.

Example:

.map(String::toUpperCase)

flatMap()

Flattens nested structures.

Example:

List<List<String>>

becomes:

List<String>

Very common in Stream processing.


25. What is Optional?

Optional represents a value that may or may not exist.

Example:

Optional<User>

Used to reduce NullPointerException risks.

Example:

userRepository.findById(id)
    .orElseThrow();

26. What is lambda expression?

Lambda provides concise anonymous function syntax.

Example:

x -> x * 2

Used heavily with:

Streams
Functional interfaces
Collections

27. What is functional interface?

Functional interface contains exactly one abstract method.

Example:

@FunctionalInterface
interface Calculator {
    int add(int a, int b);
}

Lambdas work with functional interfaces.

Examples:

Runnable
Callable
Consumer
Supplier
Function

28. What is garbage collection?

Garbage Collection automatically removes unused objects from memory.

JVM tracks objects no longer referenced and frees heap memory automatically.

Benefits:

Automatic memory management
Reduced memory leaks
Safer applications

29. Difference between heap and stack memory?


Heap

Stores objects.

Shared among threads.

Managed by garbage collector.


Stack

Stores:

Method calls
Local variables
Execution frames

Each thread has its own stack.


30. What is thread?

A thread is a lightweight execution unit inside a process.

Multiple threads allow concurrent execution.

Java applications often use threads for:

Parallel processing
Async tasks
Web requests
Background jobs

31. Difference between Runnable and Callable?

Runnable

Callable

No return value

Returns value

Cannot throw checked exception

Can throw checked exception

run()

call()

Callable is more flexible.


32. What is synchronized?

synchronized prevents multiple threads from accessing critical code simultaneously.

Example:

synchronized void increment() {
}

Used to avoid race conditions.


33. Difference between synchronized and volatile?


synchronized

Provides:

Mutual exclusion
Visibility
Atomicity

volatile

Provides only:

Visibility

No locking or atomicity.


34. What is race condition?

Race condition happens when multiple threads modify shared data simultaneously without proper synchronization.

Example:

Two threads increment counter at same time

Result may become incorrect.


35. What is deadlock?

Deadlock occurs when threads wait for each other indefinitely.

Example:

Thread A waits for lock B
Thread B waits for lock A

Neither can continue.


36. What are virtual threads?

Virtual threads are lightweight threads introduced in modern Java.

They allow massive concurrency with lower memory overhead compared to platform threads.

Useful for:

High-concurrency backend systems
IO-heavy applications
Microservices

37. What is record in Java?

Record is a concise immutable data carrier.

Example:

public record UserDto(Long id, String name) {
}

Java automatically generates:

Constructor
Getter
equals()
hashCode()
toString()

Useful for DTOs.


38. What is enum?

Enum represents fixed constant values.

Example:

public enum Status {
    ACTIVE,
    INACTIVE
}

Enums are type-safe and cleaner than string constants.


39. Why use BigDecimal for money?

Floating-point types like double can produce precision errors.

Example:

0.1 + 0.2 != 0.3

BigDecimal provides precise decimal arithmetic.

Critical for:

Banking
Payments
Financial systems

40. Why should Spring services usually be stateless?

Spring services are singleton by default.

If services contain mutable shared state:

private int counter;

multiple threads may modify it simultaneously.

This creates:

Race conditions
Thread safety issues
Unpredictable behavior

Stateless services are:

Thread-safe
Easier to scale
Safer for concurrent requests
Cleaner design

Comments