C vs Java and Immutable Objects
viaLeetCode
Prompt Explain the key differences between C and Java, then explain immutable objects: what they are, why they are useful, and how to write an immutable class in Java.
Be ready to discuss
- C vs Java: compiled-to-native vs bytecode on the JVM; manual memory management (malloc/free, pointers) vs garbage collection and references; no OOP vs classes/interfaces; undefined behaviour vs runtime safety (bounds checks, NullPointerException); portability and performance trade-offs.
- Immutability definition: state cannot change after construction — all fields final, no setters.
- Recipe for an immutable Java class: declare the class final (or make constructors private with static factories), all fields private final, defensive copies of mutable inputs (Date, arrays, collections) both in the constructor and in getters, don't leak
thisduring construction. - Why it's useful: thread safety without locks, safe sharing/caching (String pool), reliable hash keys (HashMap keys shouldn't mutate), simpler reasoning.
- Examples: String, Integer, LocalDate; records in modern Java as concise immutable carriers.
asked …