impera Open Impera

AP Computer Science A · Using objects and methods

Calling methods

1Objects, classes and constructors

A class is a blueprint; an object is an instance made from it. Objects are created with new and a constructor:

Turtle t = new Turtle(world);
Rectangle r = new Rectangle(4, 7);

A class may have several overloaded constructors with different parameter lists: new Rectangle() and new Rectangle(4, 7) can both exist. Java chooses which one by the number, types and order of the arguments.

Check yourself

Which keyword creates a new object?

  • object

  • new

  • class

  • create

Show the answer

new

new calls a constructor.

2Calling methods

A method is a named block of code. Call an instance method on an object with the dot operator:

r.getArea();
t.forward(50);
  • Arguments are the values passed in; parameters are the variables in the method header that receive them.
  • Arguments must match the parameters in number, order and type.
  • Java uses call by value: the method receives a copy of each argument. For a primitive, changing the parameter inside the method does not change the caller's variable.
Check yourself

In t.forward(50), what is 50?

  • A parameter

  • A constructor

  • An argument

  • A return type

Show the answer

An argument

The value passed in.

3Void and non-void methods

  • A void method performs an action and returns nothing: t.forward(50); is a complete statement.
  • A non-void method returns a value that should be used: stored, printed or used in an expression.
int area = r.getArea();
System.out.println(r.getPerimeter() * 2);

Calling a non-void method on its own line, such as r.getArea();, compiles, but the returned value is thrown away.

Method signature: name plus parameter list, e.g. getArea() or setSize(int w, int h). The header also shows the return type: public int getArea().

Reading a method header and matching a call to it

Check yourself

What does a void method return?

  • true

  • 0

  • Nothing

  • null

Show the answer

Nothing

It only performs an action.

4Null references

If a reference variable is null, calling a method on it throws a NullPointerException:

String s = null;
int n = s.length();   // NullPointerException

Always make sure an object has been created before calling its methods.

Check yourself

Calling a method on a null reference causes:

  • The method returns 0

  • A NullPointerException

  • Nothing

  • A compile-time error always

Show the answer

A NullPointerException

No object to call it on.

5Going deeper: signatures, pass-by-value and reading documentation

A method call has the form object.methodName(arguments) for an instance method, or ClassName.methodName(arguments) for a static method.

The signature is the method's name and its parameter list (number, types and order). The call must match it.

  • public double area(double width, double height) can be called as r.area(3, 4.5) (the int 3 is widened to 3.0).
  • r.area(3) and r.area("3", 4) do not compile.

Overloading: several methods may share a name if their parameter lists differ. Java picks the one whose parameters match the arguments. A different return type alone is not enough.

Return values

  • A non-void method produces a value, which must be used: stored, printed, compared or passed on. Calling s.toUpperCase(); on its own computes the result and throws it away.
  • A void method performs an action and returns nothing. It cannot appear in an expression: int x = list.clear(); does not compile.

Java passes arguments by value. The parameter receives a copy of the argument.

  • For a primitive, the copy is the number. Changing the parameter does not affect the caller's variable.
  • For a reference, the copy is the location of the object. The method can change the object through it, but reassigning the parameter does not affect the caller's variable.

Worked example (primitive): what is printed?

public static void addTen(int n) {
    n = n + 10;
}
// later, in the calling code:
int value = 5;
addTen(value);
System.out.println(value);
  1. n starts as a copy: 5. It becomes 15.
  2. value is untouched.
  3. Output: 5.

Worked example (reference): what is printed?

public static void change(int[] data) {
    data[0] = 100;
    data = new int[3];
    data[1] = 200;
}
// later, in the calling code:
int[] nums = {1, 2, 3};
change(nums);
System.out.println(nums[0] + " " + nums[1]);
  1. data and nums refer to the same array. data[0] = 100 changes it.
  2. data = new int[3] points the parameter at a new array; nums still refers to the original.
  3. data[1] = 200 changes only the new array.
  4. Output: 100 2.

Calling a method on null: if a reference variable holds null, calling a method through it throws a NullPointerException at run time.

String s = null;
int len = s.length();   // NullPointerException

Chaining: when a method returns an object, another method can be called on the result: name.trim().toUpperCase().substring(0, 1). Evaluate left to right.

Nesting: arguments are evaluated first: in Math.sqrt(Math.abs(x)), the inner call runs before the outer.

Reading an API description: exam questions give a class's method headers and comments. For each method, note:

  1. Its return type: what you get back and what you can do with it.
  2. Its parameters: what you must supply.
  3. Whether it is static.
  4. Any precondition (what must be true before the call; you need not check it) and postcondition (what is guaranteed afterward).

Then use the methods given; do not re-write what a provided method already does. Losing marks for re-implementing a helper incorrectly is common.

Common mistakes

  • Ignoring a return value (str.substring(2); does nothing useful).
  • Expecting a method to change a primitive argument.
  • Supplying arguments in the wrong order or of the wrong type.
  • Calling an instance method with the class name, or forgetting the object.
  • Calling a method on a reference that may be null.
Check yourself

A method public static void reset(int x) { x = 0; } is called as reset(count); where count is 7. What is count afterward?

  • null

  • 7

  • 0

  • The code does not compile

Show the answer

7

The method receives a copy of the value.

6For top marks

  • Read method headers carefully: return type, name, parameter types.
  • Use the returned value of a non-void method: store it or use it immediately.
  • Pass arguments in the order the parameters are listed.
  • Remember call by value: a method cannot change a caller's primitive variable.
Example

given public double getDistance(Point other), the correct call is double d = p1.getDistance(p2);.

Check yourself

Given public boolean isEmpty(), which call uses it correctly?

  • box.isEmpty(5);

  • if (box.isEmpty()) { ... }

  • isEmpty.box();

  • int n = box.isEmpty();

Show the answer

if (box.isEmpty()) { ... }

Returns a boolean.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera