Pass-by-Value in Java
Understand Java's pass-by-value: primitives vs references, reassignment vs mutation, arrays and immutability pitfalls.
Pass-by-value overview
Goal: Learn how Java passes parameters. Compare primitives vs references, reassignment vs mutation, arrays, and immutability.
Primitives copy
Primitives are passed by value: the callee gets a copy. Reassigning the parameter does not change the caller's variable.
public class Main {
static void inc(int x) {
x = x + 1; // modifies the local copy only
}
public static void main(String[] args) {
int a = 5;
inc(a);
System.out.println("a after inc(a) = " + a); // still 5
}
}
All lessons in this course
- Pass-by-Value in Java
- Static vs Instance Methods
- Method Decomposition & Clean Code