AP® Computer Science A · Unit 1 · Topic 1.10
Calling Class Methods
A class method belongs to the class itself, not to any object, so you call it directly through the class name, like Math.abs(-9). The call jumps to the method, runs it with your arguments, and hands back a value where the call used to be.
Math.abs is a class method, sometimes called a static method. It's written once inside the Math class and marked static, which means no Math object needs to exist for it to run. You call it with the class name instead of an object name: Math.abs(-9), not some Math object's abs(-9). Contrast this with instance methods, which belong to a specific object and need one built with new before you can call them.
When you call Math.abs(-9), the program jumps into the method's code, substitutes -9 for whatever parameter name the method header uses, runs the method body, and then returns a value back to the exact spot where the call was written. That returned value replaces the call itself, as if you had typed the value there by hand. Arguments line up with parameters strictly by position and type: the first argument fills the first parameter slot, the second fills the second, and so on.
This lets you build expressions out of nested calls, evaluated inside out. Math.max(Math.abs(-9), 4) first runs Math.abs(-9), which becomes 9, then runs Math.max(9, 4), which becomes 9. That final 9 sits where the whole expression was, ready to be stored, printed, or used in more math. If you just write Math.√x; on its own line and never store or print it, the computed value still gets returned, but nothing captures it, so it's thrown away instantly. The method call connects directly to the next topic, writing expressions and assignment, since every returned value needs somewhere to go to actually matter.
Key terms
- class method
- A method marked static that belongs to the class itself and is called through the class name, with no object needed.
- argument
- The actual value you put inside the parentheses of a method call.
- parameter
- The placeholder variable in a method's header that receives an argument's value when the method runs.
- return value
- The value a method sends back to replace the method call in the expression where it was written.
Watch it explained
- How it worksHow does a method call jump into the method, run it, and come back carrying a value?
- Worked exampleTrace the call Math.max(Math.abs(-9), 4) from the inside out to its final value.
- How it worksHow do the arguments in a call line up with the parameters in the method header?
- Common mistakeWhy doesn't a method that returns a value change anything unless you store or print it?
Check yourself
End of topic.