Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Calling Instance Methods

Lesson ~10 min read 8 MCQs

In simple terms: In simple terms, calling an instance method is like asking a specific object, like your phone, to do something it knows how to do, like "play a song" or "get the time."

Why this matters

Imagine you're at a food truck festival in Austin. There's a taco truck, a pizza truck, and a smoothie truck. Each truck is an "object." You wouldn't go to the pizza truck and ask for a taco. You walk up to the specific truck you want—the taco truck—and give it a command: "I'd like one al pastor taco." You've just "called a method" on the "taco truck object."

In programming, we do the same thing. We don't just shout commands into the void; we direct our requests to specific objects that know how to handle them. Today, we'll learn the precise Java syntax for telling objects what to do, how to understand their responses, and how to avoid the common error of talking to a truck that isn't even there.

Classes as blueprints, objects as specific instances.

Concept overview

flowchart TD
    A[Start] --> B{Is object reference null?};
    B -->|No| C[Call method using dot operator: object.method()];
    C --> D[Method executes];
    D --> E[Program continues];
    B -->|Yes| F(NullPointerException);
    F --> G[Program crashes];
This flowchart shows the logic for calling an instance method. A decision point checks if the object is null. If it is, the path leads to a "NullPointerException" and a program crash. If not, the path shows using the dot operator to execute the method, after which the program continues.

Core explanation

Hello there! I'm Saavi, and I'm so glad you're here. Let's dive into one of the most fundamental actions in programming: making things happen.

So far, you know that a class is a blueprint (like the blueprint for a Ford Mustang) and an object is a specific instance created from that blueprint (like your specific red Mustang in the driveway).

Instance methods are the actions that a specific object can perform. The blueprint—the Mustang class—defines that a Mustang can accelerate(), brake(), and turnOnRadio(). But you don't ask the blueprint to accelerate. You ask your specific car to do it.

The Dot Operator: Your Command Button

So how do you tell your specific car object to accelerate? You use the dot operator (.).

Think of it like a TV remote. Your SamsungTV object sits in the living room. Your remote is the tool you use to command it. The dot is like pointing the remote at the TV and pressing a button.

The syntax looks like this: objectName.methodName();

Let's break it down with a String object, which you've already seen.

// 1. Create a String object
String teamName = "Seattle Seahawks";

// 2. Call the length() method on the teamName object
int len = teamName.length(); // len is now 16



<figure class="lesson-figure"><div class="shr-widget" data-shr-widget="{&quot;code&quot;:[&quot;String teamName = \&quot;Seattle Seahawks\&quot;;&quot;,&quot;int len = teamName.length();&quot;,&quot;String loudName = teamName.toUpperCase();&quot;],&quot;type&quot;:&quot;for_loop_trace&quot;,&quot;array&quot;:[],&quot;trace_steps&quot;:[{&quot;line&quot;:1,&quot;vars&quot;:{&quot;teamName&quot;:&quot;\&quot;Seattle Seahawks\&quot;&quot;}},{&quot;line&quot;:2,&quot;vars&quot;:{&quot;len&quot;:16,&quot;teamName&quot;:&quot;\&quot;Seattle Seahawks\&quot;&quot;}},{&quot;line&quot;:3,&quot;vars&quot;:{&quot;len&quot;:16,&quot;loudName&quot;:&quot;\&quot;SEATTLE SEAHAWKS\&quot;&quot;,&quot;teamName&quot;:&quot;\&quot;Seattle Seahawks\&quot;&quot;}}]}" aria-label="Animation showing Java code executing. Variables `teamName`, `len`, and `loudName` update as `length()` and `toUpperCase()` methods are called on `teamName`."></div><figcaption class="lesson-figure-caption">Tracing String method calls: `length()` and `toUpperCase()`.</figcaption></figure>



// 3. Call the toUpperCase() method on the teamName object
String loudName = teamName.toUpperCase(); // loudName is now "SEATTLE SEAHAWKS"

In this code:

  • teamName is the object. It's our specific thing.
  • The . is the dot operator. It connects the object to the command.
  • length() and toUpperCase() are the instance methods. They are actions the String class blueprint says all String objects can do.

Notice the parentheses () after the method name. You must include them, even if there's nothing inside. They are what signal to Java that you are calling a method.

"But Where Does the Object Come From?"

This is a great question. You get an object in one of two ways for now:

  1. You construct it yourself using the new keyword (e.g., Rectangle box = new Rectangle();).
  2. A method gives one back to you (e.g., teamName.toUpperCase() gives you a new String object).

The key is that you must have a variable that points to an actual object before you can call a method on it.

The Dreaded NullPointerException

What happens if you have a remote but no TV? What if you have a dog leash but no dog at the end of it? If you try to give a command—"turn on," "fetch"—what happens?

Nothing. Or rather, in Java, your program crashes.

In Java, the keyword null means "no object." It's a placeholder for a variable that doesn't point to anything yet. It's the empty leash.

Look at this code:

// Create a String variable, but don't assign it an object.
// It points to nothing.
String studentName = null;

// Now, try to ask it for its length.
int nameLength = studentName.length(); // CRASH!

When the computer tries to run studentName.length(), it follows the studentName variable to find the object. But it finds null. It finds the empty leash. The program immediately stops and throws a NullPointerException.

The error message is your friend. It's Java's way of telling you, "Hey, you told me to call a method on an object, but the variable you gave me was null!"

To summarize:

  • You call instance methods on objects, not classes.
  • You use the dot operator (.) to connect the object to the method.
  • objectName.methodName();
  • Trying to call a method on a null reference causes a NullPointerException and crashes your program.

Learning to read your code and trace which variables might be null is a superpower. Let's start developing it.

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's walk through a couple of examples together. The goal here isn't just to get the right answer, but to understand the process of thinking like a programmer.

    Example 1: Using the String Class

    Problem: You are given a String variable containing a person's full name. Write code to find the number of characters in the name and also create a new string that is the "yell-able" version of the name (all uppercase).

    Solution Walkthrough:

    1. Set up the initial object. We need a String to work with.

      String fullName = "Priya Sharma";

      Here, fullName is our object reference. It points to a String object in memory that holds the characters "Priya Sharma".

    2. Call the length() method. The problem asks for the number of characters. We know from the String class documentation (or from memory!) that the length() method does this.

      int charCount = fullName.length();
    3. Call the toUpperCase() method. The problem asks for a "yell-able" version. The toUpperCase() method is perfect for this.

      String shoutedName = fullName.toUpperCase();
    4. Display the results.

      System.out.println("Original: " + fullName); // Prints "Priya Sharma"
      System.out.println("Character count: " + charCount); // Prints 12
      System.out.println("Shouted: " + shoutedName); // Prints "PRIYA SHARMA"
    Always capture the return value of methods that don't modify the original object.

    Example 2: The NullPointerException in Action

    Problem: Your friend wrote some code to get the first initial from a name, but it keeps crashing. Find the bug.

    // Friend's code
    String middleName = null; // This person doesn't have a middle name
    String initial = middleName.substring(0, 1);
    System.out.println("The initial is: " + initial);

    Solution Walkthrough:

    1. 1
      Trace the variable
      We start at the first line: String middleName = null;. We immediately see the null keyword. This should set off alarm bells in our heads. The middleName variable is an empty leash—it's not pointing to any String object.
    2. 2
      Analyze the method call
      The next line is String initial = middleName.substring(0, 1);. The code is attempting to call the substring() method.
    3. 3
      Connect the dots (or the lack thereof)
      To call substring(), Java needs an object. It looks at the middleName variable. What does it find? null.
    4. 4
      Identify the error
      The computer cannot execute a method on null. It's like asking an empty parking space to start its engine. At this exact point, the program will halt and throw a NullPointerException. The System.out.println line will never even be reached.

    The Fix: The code needs to handle the case where middleName might be null. A more advanced way uses an if statement (which we'll cover later), but for now, the bug is simply that you cannot call a method on null. The fix is to not write code that does this!

    A `NullPointerException` occurs when calling a method on a `null` reference.

    Try it yourself

    Time to get your hands on the keyboard. Don't worry about getting it perfect the first time; the goal is to try.

    Practice 1: The Rectangle Class

    Assume you have a Rectangle class available that you can create objects from.

    • A Rectangle is created like this: Rectangle myRect = new Rectangle(width, height);
    • It has an instance method getArea() that returns the area as an int.
    • It has an instance method getPerimeter() that returns the perimeter as an int.

    Your Task: Write Java code that creates a Rectangle object with a width of 10 and a height of 25. Then, call its methods to calculate and print its area and perimeter to the console.

    Practice 2: Predict the Crash

    Read the following code snippet. What will be printed to the console? Or will the program crash? If it crashes, on which line and why?

    String city = "Atlanta";
    String state = null;
    System.out.println(city.toLowerCase());
    System.out.println(state.toLowerCase());
    System.out.println("Done!");
    Flowchart for handling `null` references before method calls.
    Tracing the `Rectangle` object creation and method calls.