Getting Started
In object-oriented programming, creating objects is only the first step. To build useful programs, we need to make these objects interact and perform actions. This is achieved by "calling" or "invoking" their methods. Calling a method is how you ask an object to perform one of its defined behaviors, such as calculating a value, changing its internal state, or printing information to the console.
What You Should Be Able to Do
Call a method on an object using the dot operator (
.).Pass values, known as arguments, to a method that match its required parameter types.
Correctly call a
voidmethod to make an object perform an action.Call a non-
voidmethod and correctly store or use its return value.Distinguish between a method call that is a statement and a method call that is an expression.
Key Concepts & Java Implementation
The Core Idea
An object is an instance of a class, containing both state (data in instance variables) and behavior (actions defined in methods). To make an object perform a behavior, you must call one of its methods. Think of an object as a real-world entity, like a Dog, and its methods as the commands you can give it, like bark() or fetch().
The syntax for this is simple and intuitive: you specify which object you are commanding, followed by a dot (.), followed by the name of the method you want to execute.
There are two fundamental types of methods:
voidMethods: These methods perform an action but do not send back any information. A call to avoidmethod is a complete command, like telling a robot tomoveForward().Non-
voidMethods: These methods perform a computation and return a single value back to the code that called it. A call to a non-voidmethod is like asking a question, such asgetBatteryLevel(), which you expect an answer to. The call itself is an expression that evaluates to the returned value.
When a method requires information to do its job (e.g., how far to move), we provide that information as arguments inside the parentheses of the method call. These arguments must match the type and order of the parameters defined in the method's signature.
Syntax & Implementation
To illustrate method calls, we will use a simple Robot class. Imagine this class has already been defined with the following methods:
public void move(int distance): Moves the robot and consumes battery.public void speak(String message): Prints a message.public int getBatteryLevel(): Returns the current battery percentage.
Syntax Table
| Method Type | General Syntax | Java Example |
|---|---|---|
void Method | objectReference.methodName(arguments); | myBot.move(50); |
non-void Method | DataType variable = objectReference.methodName(arguments); | int charge = myBot.getBatteryLevel(); |
Annotated Java Examples
Let's see these method calls in action within a main method or another class.
1. Calling void Methods
A void method call is a complete statement that ends with a semicolon. It instructs an object to perform an action.
// Assume a Robot class exists and we are in a method like main
Robot myBot = new Robot(); // Create an instance of the Robot class
// Call a void method with a String argument
myBot.speak("Hello, world!"); // The myBot object will now execute its speak behavior.
// Call a void method with an int argument
myBot.move(100); // The myBot object will now move.
2. Calling non-void Methods
A non-void method returns a value. The method call is an expression, and its result should typically be stored in a variable or used immediately.
Robot myBot = new Robot(); // Create a Robot object
// 1. Store the return value in a variable
// The getBatteryLevel() method returns an int.
// We declare an int variable `currentCharge` to hold that value.
int currentCharge = myBot.getBatteryLevel();
// Now we can use the stored value
System.out.println("Current battery is: " + currentCharge);
// 2. Use the return value directly in another expression
// Here, the return value of getBatteryLevel() is passed directly
// to the println method without being stored in a variable first.
System.out.println("Battery status: " + myBot.getBatteryLevel() + "%");
Tracing & Analysis
Execution Trace
Let's trace the state of our variables as we call methods on a Robot object. Assume the Robot starts with 100 battery and the move method consumes 1 unit of battery for every 1 unit of distance.
Code to Trace:
1: Robot wallE = new Robot(100); // Constructor sets battery to 100
2: wallE.move(30); // move(d) reduces battery by d
3: int battery = wallE.getBatteryLevel();
4: System.out.println("Final battery: " + battery);
Trace Table:
| Line of Code | wallE's Battery | Variable battery | Output |
|---|---|---|---|
| Before Line 1 | (does not exist) | (not declared) | |
| After Line 1 | 100 | (not declared) | |
| After Line 2 | 70 | (not declared) | |
| After Line 3 | 70 | 70 | |
| After Line 4 | 70 | 70 | Final battery: 70 |
Analysis
The trace shows that calling the void method move(30) changed the internal state of the wallE object (its battery level decreased). The call to the non-void method getBatteryLevel() did not change the object's state; it only retrieved a value from it. The returned value was then assigned to the local variable battery.
Java Syntax Quick-Reference
A compact list of the syntax related to calling methods.
.(Dot Operator): The operator used to access a member (method or instance variable) of an object. It connects an object reference to the method being called.object.methodName();: Calls a method on an object that takes no arguments.object.methodName(arg1, arg2);: Calls a method on an object, passingarg1andarg2as arguments. The type ofarg1must match the type of the method's first parameter, and so on.variable = object.methodName();: Calls a non-voidmethod and assigns its return value to a variable of a compatible type.
Core Code Examples & Terminology
Object: An instance of a class. An object has a state (data) and behaviors (methods). It is created using the
newkeyword.Method: A named block of code within a class that defines a behavior an object can perform.
Parameter: A variable in a method's definition that acts as a placeholder for a value that will be passed in when the method is called.
Argument: The actual value that is passed into a method's parameter during a specific method call.
voidMethod: A method that performs an action but does not return a value. Its method signature uses thevoidkeyword as the return type.Return Value: The value that a non-
voidmethod calculates and sends back to the calling code. The type of this value is specified in the method's signature.Core Snippet 1: Calling a
voidmethod with an argument// Assume a 'player' object of type Player exists // and has a method: public void setName(String newName) player.setName("Alice");This code calls the
setNamemethod on theplayerobject, passing theStringliteral"Alice"as an argument.Core Snippet 2: Calling a non-
voidmethod and using its return value// Assume a 'calculator' object of type Calculator exists // and has a method: public int add(int a, int b) int sum = calculator.add(15, 7);This code calls the
addmethod on thecalculatorobject and assigns the integer value it returns (22) to thesumvariable.
Core Skill Check
Code Tracing: What is the final value of
yafter this Java code runs? (AssumeCounter c = new Counter();starts its internal count at 0, andincrement()adds 1 to it).Counter c = new Counter(); c.increment(); c.increment(); int y = c.getValue();Answer: 2
Debugging: Identify the compile-time error in this Java code, assuming
printer.printMessage("Hi")is avoidmethod.String result = printer.printMessage("Hi");Answer: The error is trying to assign the result of a
voidmethod to a variable.voidmethods do not return a value.Application: Given a
Rectangleobject namedboxwith a methodpublic double getArea(), write a single line of Java code to declare adoublevariable namedareaand initialize it with the area ofbox.Answer:
double area = box.getArea();
Common Misconceptions & Errors
Ignoring a Return Value: Calling a non-
voidmethod without storing or using its result (e.g.,myBot.getBatteryLevel();). The code will compile and run, but the value is computed and immediately discarded, which is usually not the intended behavior.Mismatched Argument Types: Calling a method with an argument whose type does not match the method's parameter type (e.g.,
myBot.move("twenty");whenmoveexpects anint). This will cause a compile-time error.Incorrect Number of Arguments: Calling a method with too few or too many arguments (e.g.,
myBot.speak();when thespeakmethod requires aStringparameter). This is also a compile-time error.Assigning a
voidCall to a Variable: Attempting to store the "result" of avoidmethod call (e.g.,int status = myBot.move(50);). This is a compile-time error because avoidmethod has nothing to return.
Summary
Calling methods is the fundamental mechanism for interacting with objects in Java. We use the dot operator (.) to invoke a specific method on a specific object instance. This allows us to trigger an object's behaviors and query its state. It is crucial to distinguish between void methods, which are commands that perform an action, and non-void methods, which are queries that return a value. The arguments provided in a method call must match the parameters in the method's definition in both type and order. Properly using method calls is essential for making objects work together to create a functional program.