Exercise: objects and references
The aim of this exercise is for you to become familiar with the different behaviours
exhibited when using the Java primitive data types and Java objects.
References
If you need to, look at ValRef.java and answer
the following questions:
- Why doesn't String one == String two?
- Why can't we use the .equals() operator on a and b?
Hints
You should:
- Copy, compile and run the ValRef.java code (as usual)
- Read the code and your reference books closely to make sure that you understand
why the program does what it does
- If you're having problems understanding what's going on, try drawing some
diagrams
- When you think you do understand, write some experimental programs that
do similar things and try to predict what will happen when you run them.
Assignments vs copies
If you need to, look again at Copying.java.
Answer the following questions (on paper, with diagrams):
- Why, when we print a again, is it the same?
- Why then, does array c change?
- What would happen if d was initialised to {1,1,1,1,1} instead of
copying c? Would changes to d hae an effect on c?
- What would happen if d was initialised to a new array and the elements of
c were copied in one by one? Would changes to d hae an effect on c?
Hints
You should:
- Copy, compile and run the Copying.java code
- Read the code and your reference books closely
- Create a copy d of c by creating a new array and copying in the elements
one by one.
- Experiment!
Parameter passing
Write a program to show how a method which gets an array as argument can change
the array.

© 2001 Mark Ryan and Alan Sexton