What is the difference between a value type and a reference type?
LanguagesJunior
In shortAssigning a value type copies the data, so each variable is independent. Assigning a reference type copies a reference, so several variables share one object and see each other's changes.
Model answer
With a value type, the variable holds the data itself. Assigning it or passing it to a function makes a copy, and changing the copy never affects the original. With a reference type, the variable holds a reference to an object; assignment copies the reference, so both variables point to the same object.
struct Point { var x = 0 } // value type
final class Counter { var n = 0 } // reference type
var a = Point(); var b = a; b.x = 5 // a.x is still 0
let c = Counter(); let d = c; d.n = 5 // c.n is now 5
Per language:
- Swift:
struct,enum, tuples,Stringand the collections are values (collections use copy-on-write, so copies are cheap until changed).classandactorare references. - Kotlin and Java: only primitives (
Int,int,Boolean…) behave as values. Everything else, including Kotlindata classand Javarecord, is a reference type. They get value-like behavior when they’re immutable.
Why it matters: shared mutable objects cause “action at a distance” bugs, where code in one place changes data another place is using. Values (or immutable objects) make that impossible and are safe to share between threads.
What they're looking for
A clear definition with an example of the different behavior after assignment, the right types per language (Swift struct vs class, JVM primitives vs objects), and why it matters for bugs. Bonus for mentioning immutability and copy-on-write.
Common mistakes
- Saying Kotlin data classes or Java records are value types.
- Answering only with "stack vs heap", which is about memory, not semantics.
- Not mentioning what happens when you change a shared object.
More languages questions
- How is memory managed in Swift compared to Kotlin or Java?Mid-level
- What is the difference between checked and unchecked exceptions, and how do Kotlin and Swift handle this?Mid-level
- What are type erasure and variance in generics, and how do Swift, Kotlin and Java differ?Senior
- When would you choose composition over inheritance?Mid-level