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.
In this example, we show how Java handles value types and reference types differently:
The
zeroValue
method takes anint
parameter, which is a primitive type in Java. When we passi
to this method, Java creates a copy of the value. Changes to this copy inside the method do not affect the original variable in themain
method.The
zeroReference
method takes anIntWrapper
parameter, which is a reference type. When we passwrapper
to 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
main
method, we create anint
variable and anIntWrapper
object 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:
This output demonstrates that:
zeroValue
doesn’t change the originali
inmain
.zeroReference
does change the value in theIntWrapper
object.- 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.