Pointers in Logo
Java does not have direct pointer manipulation like Go, but it does have reference types which can be used to achieve similar behavior. We’ll demonstrate this using object references and a mutable integer wrapper class.
class IntWrapper {
public int value;
public IntWrapper(int value) {
this.value = value;
}
}
public class PointersExample {
// This method demonstrates pass-by-value behavior
public static void zeroValue(int value) {
value = 0;
}
// This method demonstrates pass-by-reference behavior
public static void zeroReference(IntWrapper ref) {
ref.value = 0;
}
public static void main(String[] args) {
int i = 1;
System.out.println("initial: " + i);
zeroValue(i);
System.out.println("zeroValue: " + i);
IntWrapper wrapper = new IntWrapper(i);
zeroReference(wrapper);
System.out.println("zeroReference: " + wrapper.value);
// In Java, we can't print memory addresses directly,
// but we can print the object's hash code
System.out.println("object hashcode: " + wrapper.hashCode());
}
}In this example, we show how Java handles value types and reference types differently:
The
zeroValuemethod takes anintparameter, which is a primitive type in Java. When we passito this method, Java creates a copy of the value. Changes to this copy inside the method do not affect the original variable in themainmethod.The
zeroReferencemethod takes anIntWrapperparameter, which is a reference type. When we passwrapperto this method, Java passes a reference to the object. Changes made to the object through this reference inside the method affect the original object.In the
mainmethod, we create anintvariable and anIntWrapperobject to demonstrate these differences.We can’t directly print memory addresses in Java like we can in Go. Instead, we print the object’s hash code, which is a unique integer value for the object (although not guaranteed to be unique, it’s often used for similar purposes).
When you run this program, you should see output similar to this:
initial: 1
zeroValue: 1
zeroReference: 0
object hashcode: 1234567 // The actual number will varyThis output demonstrates that:
zeroValuedoesn’t change the originaliinmain.zeroReferencedoes change the value in theIntWrapperobject.- We can print a representation of the object’s identity using its hash code.
While Java doesn’t have explicit pointers like Go, understanding the difference between value types (primitives) and reference types (objects) is crucial for Java developers, as it affects how data is passed between methods and how it can be modified.