Skip to content

Instantly share code, notes, and snippets.

@JoergWMittag
Created March 22, 2014 03:17
Show Gist options
  • Save JoergWMittag/9700582 to your computer and use it in GitHub Desktop.
Save JoergWMittag/9700582 to your computer and use it in GitHub Desktop.
Demonstrate the difference between mutating a value and reassigning a different value.
class MutableInt {
private int value;
MutableInt(int value) {
this.value = value;
}
void mutate() {
value++;
}
MutableInt add(MutableInt other) {
return new MutableInt(value + other.value);
}
public String toString() {
return new Integer(value).toString();
}
}
public class DemonstrateMutableVsImmutable {
public static void main(String... args) {
demonstrateMutable();
demonstrateImmutable();
}
static void demonstrateMutable() {
MutableInt one = new MutableInt(1);
System.out.println(one.add(one)); // 2
MutableInt two = one;
two.mutate();
System.out.println(one.add(one)); // 4
}
static void demonstrateImmutable() {
int one = 1;
System.out.println(one + one); // 2
int two = one;
two++;
System.out.println(one + one); // 2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment