Calling Class Methods
Learn how to invoke methods on objects and classes, pass arguments, and use return values in Java.
What is a Method?
A method is a named block of code that belongs to a class. It performs a specific task and can be called (invoked) whenever you need that task done. Methods help organize code, avoid repetition, and make programs easier to read.
Anatomy of a Method Call
Void vs. Return Methods
Every method has a return type. This tells Java whether the method sends a value back to the caller or simply performs an action.
System.out.println("Hi");
int len = str.length();
How a Method Call Flows
Static vs. Non-Static Methods
A key distinction in Java: some methods belong to the class itself (static), while others belong to an individual object (non-static / instance methods).
| Static Methods | Non-Static Methods | |
|---|---|---|
| Called on | The class name | An object reference |
| Syntax | Math.sqrt(25) | str.length() |
| Keyword | static in header | No static keyword |
| Access to | Only static fields | Instance + static fields |
| Needs object? | No | Yes |
Parameters and Arguments
How to Call a Method
Example 1: Calling an Instance Method
Example 2: Static Method Call
Example 3: Nesting Method Calls
Because non-void methods return values, you can use a method call anywhere a value is expected: as an argument, in a print, or in an expression.
Calling Methods with this
Inside a class, one method can call another method on the same object using the implicit this reference, or simply by name (Java fills in this automatically).
Method Overloading
Java allows multiple methods with the same name in a class, as long as their parameter lists differ. Java picks the right version based on the arguments you pass.
Common Mistakes
Summary of Method Calls
| Concept | Syntax / Rule | Example |
|---|---|---|
| Instance call | object.method(args) | str.length() |
| Static call | ClassName.method(args) | Math.abs(-5) |
| void method | Standalone statement | list.add("x"); |
| Non-void method | Use return value | int n = s.length(); |
| Overloaded | Same name, different params | print("Hi") / print(5) |
| Nested call | Inner evaluates first | println(s.length()) |
Question 1 of 5
Which of the following correctly calls the static method Math.max to find the larger of two integers?
Question 2 of 5
Given the code below, what is printed?
Question 3 of 5
What is the difference between a parameter and an argument?
Question 4 of 5
What does the following code output?
Question 5 of 5
A class has the following overloaded methods:
Which call would cause a compile error?