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:

  1. Why doesn't String one == String two?
  2. Why can't we use the .equals() operator on a and b?

Hints

You should:

  1. Copy, compile and run the ValRef.java code (as usual)
  2. Read the code and your reference books closely to make sure that you understand why the program does what it does
  3. If you're having problems understanding what's going on, try drawing some diagrams
  4. 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):

  1. Why, when we print a again, is it the same?
  2. Why then, does array c change?
  3. 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?
  4. 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:

  1. Copy, compile and run the Copying.java code
  2. Read the code and your reference books closely
  3. Create a copy d of c by creating a new array and copying in the elements one by one.
  4. 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