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.
public class Pointers {
// This method takes an Integer object, which is passed by reference
static void zeroRef(Integer num) {
num = 0;
}
// This method takes a primitive int, which is passed by value
static void zeroVal(int num) {
num = 0;
}
public static void main(String[] args) {
Integer i = 1;
System.out.println("initial: " + i);
zeroVal(i);
System.out.println("zeroVal: " + i);
zeroRef(i);
System.out.println("zeroRef: " + i);
// In Java, we can't directly print memory addresses
// But we can print the hashCode, which is often related to the object's memory address
System.out.println("hashCode: " + System.identityHashCode(i));
}
}In this Java example, we demonstrate the difference between passing by value and passing by reference:
The
zeroValmethod takes a primitiveint, which is passed by value. Changes to this value inside the method don’t affect the original variable.The
zeroRefmethod takes anIntegerobject, which is passed by reference. However, due to the immutability ofIntegerobjects, assigning a new value to the parameter doesn’t change the original object.In the
mainmethod, we create anIntegerobject 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:
initial: 1
zeroVal: 1
zeroRef: 1
hashCode: 1829164700Note that neither zeroVal nor zeroRef changes the value of i in main. This is because:
zeroValreceives a copy of the primitive value, so changes don’t affect the original.zeroRefreceives a reference to theIntegerobject, butIntegeris immutable in Java. When we assign a new value to it inside the method, it creates a newIntegerobject, 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.