ACSA Exam Prep
Unit 1 · Using Objects and Methods · Topic 1.14

Calling Instance Methods

Skill 2.CSkill 3.C

Big idea: Instance methods act on one particular object, so you call them on an object reference with a dot.

Learning objectives
  • Develop code to call instance methods and determine the result of these calls.

Calling a method on an object

obj.method(args) runs the method using that object's data. Two objects of the same class can return different results from the same method because their attributes differ.

Code
String s = "hello";
String t = "hi";
System.out.println(s.length() + " " + t.length());
Output
5 2

NullPointerException

If the reference is null, there is no object to run the method on, and Java throws a NullPointerException.

Code
String name = null;
System.out.println(name == null);
System.out.println(name.length());
Output
true
throws NullPointerException
Key points
  • Instance methods are called on an object: obj.method().
  • Calling a method on null throws a NullPointerException.
Watch out
  • When a reference might be null, check it first: if (s != null && s.length() > 0). Short-circuiting keeps the second part from running when s is null.
Quick check
What happens? String s; s = null; System.out.println(s.length());
Show answer
A NullPointerException is thrown at run time.