Unit 1.10: Calling Class Methods
AP Computer Science A
Understanding Static Methods and Class-Level Operations
Learning Objective 1.10.A
Develop code to call class methods and determine the result of those calls.
What are Class Methods?
Essential Knowledge 1.10.A.1
Class methods are associated with the class, not instances of the class. Class methods include the keyword static in the header before the method name.
Key Characteristics:
- Belong to the class itself, not to any specific object
- Use the static keyword in their declaration
- Can be called without creating an instance of the class
- Cannot access instance variables or instance methods directly
- Shared across all instances of the class
Class Method Syntax
General Format:
public static returnType methodName(parameters) {
// method body
return value; // if not void
}
Examples:
// Method that returns a value
public static int add(int a, int b) {
return a + b;
}
// Method that performs an action
public static void printWelcome() {
System.out.println("Welcome to our program!");
}
// Method that works with arrays
public static double findAverage(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return (double) sum / numbers.length;
}
How to Call Class Methods
Essential Knowledge 1.10.A.2
Class methods are typically called using the class name along with the dot operator. When the method call occurs in the defining class, the use of the class name is optional in the call.
Calling from Outside the Class:
// ClassName.methodName(arguments);
int result = MathUtils.add(5, 3);
MathUtils.printWelcome();
double avg = MathUtils.findAverage(scores);
Calling from Within the Same Class:
// Can use class name (recommended for clarity)
int result = MathUtils.add(5, 3);
// Or call directly (class name optional)
int result = add(5, 3);
Complete Example: MathUtils Class
public class MathUtils {
// Class method to find maximum of two numbers
public static int max(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
// Class method to calculate factorial
public static int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
// Method calling other methods in same class
public static void demonstrate() {
int maxValue = max(10, 15); // Optional: MathUtils.max(10, 15)
int fact5 = factorial(5); // Optional: MathUtils.factorial(5)
System.out.println("Max: " + maxValue);
System.out.println("5! = " + fact5);
}
}
Using the MathUtils Class
public class TestMathUtils {
public static void main(String[] args) {
// Calling class methods from another class
// MUST use class name and dot operator
int maximum = MathUtils.max(25, 18);
System.out.println("Maximum: " + maximum);
int result = MathUtils.factorial(4);
System.out.println("4! = " + result);
// Call the demonstration method
MathUtils.demonstrate();
// This would cause a compilation error:
// int wrong = max(5, 10); // ERROR: max() not in scope
}
}
Output:
Maximum: 25
4! = 24
Max: 15
5! = 120
Built-in Class Methods You Already Know
Math Class Methods:
// All Math methods are static!
double result1 = Math.sqrt(16); // Returns 4.0
double result2 = Math.pow(2, 3); // Returns 8.0
int result3 = Math.abs(-5); // Returns 5
double result4 = Math.random(); // Returns random 0.0-1.0
int result5 = Math.max(10, 20); // Returns 20
Integer Class Methods:
// Converting strings to numbers
int num1 = Integer.parseInt("123"); // Returns 123
String str1 = Integer.toString(456); // Returns "456"
int max = Integer.MAX_VALUE; // Largest int value
Double Class Methods:
double num2 = Double.parseDouble("12.5"); // Returns 12.5
String str2 = Double.toString(3.14); // Returns "3.14"
Class vs Instance Methods
| Aspect | Class Methods (static) | Instance Methods |
|---|---|---|
| Declaration | Uses static keyword |
No static keyword |
| Belongs to | The class itself | Individual objects |
| How to call | ClassName.methodName() | objectName.methodName() |
| Access to instance variables | No direct access | Full access |
| Memory | One copy per class | One copy per object |
Common Mistakes and How to Avoid Them
Mistake 1: Forgetting the class name
// In a different class - WRONG:
int result = max(5, 10); // Compilation error
// CORRECT:
int result = MathUtils.max(5, 10);
Mistake 2: Trying to access instance variables
public class Student {
private String name; // instance variable
public static void printName() { // static method
System.out.println(name); // ERROR: Can't access instance variable
}
}
Mistake 3: Calling instance methods from static methods
public class Example {
public void instanceMethod() { } // instance method
public static void staticMethod() {
instanceMethod(); // ERROR: Can't call instance method
}
}
Practice Problems
Problem 1: What will this code output?
public class Calculator {
public static int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args) {
int result = Calculator.multiply(4, 7);
System.out.println("Result: " + result);
}
}
Answer: Result: 28
Problem 2: Which line will cause a compilation error?
public class TestClass {
public static void main(String[] args) {
int a = Math.max(10, 15); // Line 1
double b = Math.sqrt(25); // Line 2
int c = max(5, 8); // Line 3
String d = Integer.toString(42); // Line 4
}
}
Answer: Line 3 - 'max' method not found in current scope
Best Practices for Class Methods
When to Use Class Methods:
- Utility functions that don't depend on instance data
- Mathematical calculations and conversions
- Factory methods that create objects
- Helper methods that process parameters only
Naming Conventions:
- Use descriptive names that indicate the method's purpose
- Use camelCase for method names
- Consider using verb-noun combinations (calculateArea, findMaximum)
Documentation:
/**
* Calculates the area of a rectangle
* @param length the length of the rectangle
* @param width the width of the rectangle
* @return the area as length * width
*/
public static double calculateRectangleArea(double length, double width) {
return length * width;
}
Summary: Calling Class Methods
Key Points to Remember:
- Class methods use the static keyword
- They belong to the class, not instances
- Call them using ClassName.methodName()
- Class name is optional within the same class
- Cannot directly access instance variables or methods
Common Examples:
// Math class methods
Math.max(a, b)
Math.sqrt(x)
Math.random()
// String conversion methods
Integer.parseInt(str)
Double.parseDouble(str)
Integer.toString(num)
// Your own utility methods
MathUtils.factorial(n)
StringUtils.reverse(text)
ArrayUtils.findMax(array)
Ready for the AP Exam!
You can now identify, call, and create class methods with confidence.
1 / ?