Skip Top Navigation Bar

Passing and Returning Reference Data

Methods can receive and return more than primitive values. They can also receive and return reference values.

Understanding reference values is important because a method can use a reference to access and modify the same object that the calling code is using.


Passing an Object to a Method

Suppose you have a Dice class.

You can pass a Dice object to a method in a Game class.

This will change the number of sides dice has before rolling it.

Call the method by passing a Dice object.

The reference mydice in the calling snippet and dice in the playGame method will point to the same object. So, making an update will change the object that both references refer to.

Returning an Object

A method can return a reference to an object.

For example, a method can create a new Dice object and return it.

The returned reference can be assigned to a variable.

The variable seconddice now refers to the object returned by the method.