What is meant by ‘value semantics’, and what is meant by ‘implicit pointer semantics’?
Basically, value semantics means that assigning one value to another creates a copy:
int x = 1;
int y = x;
x = 2; // y remains the same!
A special case is a function call which gets passed an argument:
void f(int x) {
x = 5;
}
int a = 1;
f(a);
// a is still 1
This is actually the same for Java and C++. However, Java knows only a few primitive types, among them int
, double
, boolean
and char
, along with enums which behave in this manner. All other types use reference semantics which means that an assignment of one value to another actually redirects a pointer instead of copying the underlying value:
class Foo {
int x;
public Foo(int x) { this.x = x; }
}
Foo a = new Foo(42);
Foo b = a; // b and a share the same instance!
a.x = 32;
//b.x is now also changed.
There are a few caveats however. For example, many reference types (String
, Integer
…) are actually immutables. Their value cannot be changed and any assignment to them overrides the old value.
Also, arguments still get passed by value. This means that the value of an object passed to a function can be changed but its reference can't:
void f(Foo foo) {
foo.x = 42;
}
void g(Foo foo) {
foo = new Foo(42);
}
Foo a = new Foo(23);
f(a);
// a.x is now 42!
Foo b = new Foo(1);
g(b);
// b remains unchanged!