Pointers in CLIPS
Java doesn’t have pointers in the same way Go does, but we can demonstrate similar concepts using object references and primitive wrapper classes.
Our example will show how object references work in contrast to primitive values with two methods: changeValue
and changeReference
. changeValue
has an Integer
parameter, so arguments will be passed to it by value. changeValue
will get a copy of the Integer
object distinct from the one in the calling method.
changeReference
in contrast has an Integer[]
parameter, which is effectively a reference to an array containing an Integer
. Assigning a value to the first element of this array changes the value that the reference points to.
The System.identityHashCode()
method is used to print a unique identifier for the object, which is analogous to printing the memory address in languages with explicit pointer support.
When we run this program, we’ll see:
changeValue
doesn’t change the i
in main
, but changeReference
does because it has a reference to the array containing the Integer
object.
This example demonstrates that in Java:
- Primitive wrapper objects like
Integer
are immutable, sochangeValue
doesn’t affect the original value. - Arrays are passed by reference, so
changeReference
can modify the contents of the array. - We can use object references to achieve behavior similar to pointers in other languages.
While Java doesn’t have explicit pointer arithmetic or dereferencing, understanding object references is crucial for effective Java programming.