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:

  1. The zeroVal method takes a primitive int, which is passed by value. Changes to this value inside the method don’t affect the original variable.

  2. The zeroRef method takes an Integer object, which is passed by reference. However, due to the immutability of Integer objects, assigning a new value to the parameter doesn’t change the original object.

  3. In the main method, we create an Integer object and pass it to both methods.

  4. 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: 1829164700

Note that neither zeroVal nor zeroRef changes the value of i in main. This is because:

  1. zeroVal receives a copy of the primitive value, so changes don’t affect the original.
  2. zeroRef receives a reference to the Integer object, but Integer is immutable in Java. When we assign a new value to it inside the method, it creates a new Integer 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.