Pointers in Karel
Java supports references, which are similar to pointers in some ways. However, Java doesn’t have direct pointer manipulation like C or C++. Instead, we’ll demonstrate how reference passing works in Java.
In this Java example, we demonstrate the difference between passing by value and passing by reference:
The
zeroVal
method takes a primitiveint
, which is passed by value. Changes to this value inside the method don’t affect the original variable.The
zeroRef
method takes anInteger
object, which is passed by reference. However, due to the immutability ofInteger
objects, assigning a new value to the parameter doesn’t change the original object.In the
main
method, we create anInteger
object and pass it to both methods.We can’t directly print memory addresses in Java like we can in languages with explicit pointers. Instead, we print the object’s
hashCode
, which is often (but not always) related to the object’s memory address.
When you run this program, you’ll see output similar to this:
Note that neither zeroVal
nor zeroRef
changes the value of i
in main
. This is because:
zeroVal
receives a copy of the primitive value, so changes don’t affect the original.zeroRef
receives a reference to theInteger
object, butInteger
is immutable in Java. When we assign a new value to it inside the method, it creates a newInteger
object, leaving the original unchanged.
This behavior is different from languages with explicit pointers, where you can directly manipulate memory addresses. Java’s approach provides better safety and simplicity, at the cost of some low-level control.