Pointers in Mercury
Java doesn’t have pointers in the same way that some other languages do. Instead, it uses references for objects. Primitive types (like int
) are passed by value, while objects are passed by reference.
In this example, we’ve adapted the concept to show the difference between passing primitive types by value and objects by reference:
The
zeroval
method takes anint
parameter, which is passed by value. Changes to this parameter inside the method don’t affect the original variable.The
zeroref
method takes anInteger
object as a parameter.Integer
is a wrapper class forint
, and it’s passed by reference. Changes to this object inside the method affect the original reference.In the
main
method, we demonstrate both behaviors:- Calling
zeroval
doesn’t change the originali
variable. - Calling
zeroref
changes the value of theiRef
object.
- Calling
Instead of printing the memory address (which isn’t directly accessible in Java), we print the object’s hash code, which serves as a unique identifier for the object.
When you run this program, you’ll see output similar to this:
This shows that zeroval
didn’t change the original value, but zeroref
did change the value of the Integer
object. The hashcode provides a way to identify the object, similar to how a memory address would in languages with explicit pointers.