AP Computer Science A · Study guide

Calling Class Methods

AP® Computer Science A · Using Objects and Methods

Calling Class Methods

What class methods are, how the static keyword marks them, how to call them with the class name and the dot operator, when the class name can be left out, and how library class methods such as Integer.parseInt are used.

Big Picture

Some methods need an object to work on: a String's length depends on which string you ask. Others do not: computing an absolute value or converting "42" to a number does not depend on any particular object. Class methods are associated with the class, not with instances of the class. They include the keyword static in the header before the method name, and they are typically called using the class name along with the dot operator, as in Math.abs(-7). When the call occurs inside the defining class, the class name is optional.

1Methods That Belong to the Class

A class can contain two kinds of methods. Instance methods work with a particular object's data: word.length() reports the length of the string that word refers to, and a different string would give a different answer. Class methods do not depend on any object's data. They take everything they need through their parameters and are shared by the whole class.

The Math class is the clearest example: it contains only class methods. There is no such thing as a particular "math object"; Math.sqrt(49) simply computes a square root from its argument. In a method header, the keyword static marks a class method: public static double sqrt(double x). The main method is also a class method, which is why its header contains static.

A useful test for telling the two kinds apart is to ask whether the answer depends on a particular object. "How long is this word?" depends on the word, so length is an instance method. "What is the square root of 49?" depends only on the number passed in, so sqrt is a class method. When you read documentation, the word static in a method's header tells you which way to call it.

Figure 1. Class methods are associated with the class, not with instances of the class, so they are called using the class name. Instance methods are called on a particular object.
Class method (static)Instance method
Belongs toThe class itselfEach object (instance) of the class
HeaderIncludes the keyword staticNo static
Called withThe class name: Math.sqrt(16)An object: word.length()
Needs an object?NoYes
ExamplesMath.abs, Integer.parseIntsubstring, add
Common Mistake 1 · Creating an Object to Call a Class Method

Class methods are called on the class, not on an object. There is no need to create anything before calling Math.abs or Integer.parseInt; just write the class name, a dot, and the method call.

2The Call Syntax

Class methods are typically called using the class name along with the dot operator: ClassName.methodName(arguments). The class name tells Java where to find the method, the dot operator connects the class to its member, and the parentheses hold the arguments, which must match the method's parameter list in number, order, and type.

Like any method call, a class method call to a non-void method is an expression with a value of the method's return type. That value can be stored, printed, or used in further arithmetic. A call to a void class method is used as a statement on its own.

Figure 2. Class methods are typically called using the class name along with the dot operator. This call converts the text "42" into the int value 42.

3Class Methods in the Library

The Java library provides many class methods. From Math: abs, pow, sqrt, and random. From the wrapper classes: Integer.parseInt converts a String of digits into an int, and Double.parseDouble converts a String into a double. All of these are in java.lang, so they are available without an import.

The parsing methods are essential whenever numbers arrive as text, for example from a file or a form. Text and numbers behave differently: "12" + 1 is "121", while Integer.parseInt("12") + 1 is 13. If the text is not a valid number, such as "12a", the parsing method throws a NumberFormatException at run time.

Figure 3. The class methods Integer.parseInt and Double.parseDouble convert text into numbers so that arithmetic can be done.
Class methodReturnsExampleResult
Math.abs(int)intMath.abs(-9)9
Math.sqrt(double)doubleMath.sqrt(2.25)1.5
Integer.parseInt(String)intInteger.parseInt("305")305
Double.parseDouble(String)doubleDouble.parseDouble("0.5")0.5
Worked Example 1 Library class methods

Calling Class Methods From java.lang

Predict each result and its type.

Code
System.out.println(Math.abs(-7));
System.out.println(Integer.parseInt("42") + 1);
System.out.println(Double.parseDouble("2.5") * 2);
System.out.println(Math.sqrt(49));
Output
7
43
5.0
7.0
  1. 1Math.abs(-7). The int version of abs returns the int 7.
  2. 2Integer.parseInt("42") + 1. The text "42" becomes the int 42, then 1 is added: 43.
  3. 3Double.parseDouble("2.5") * 2. 2.5 × 2 = 5.0, a double.
  4. 4Math.sqrt(49). Returns a double, so 7.0.
  5. 5The pattern. Every call starts with a class name, because these methods belong to the class rather than to any object.
Result: The results are 7, 43, 5.0, and 7.0. Class methods are called with the class name and the dot operator, and their return types determine how results print.
Worked Example 2 Parsing text

Converting Text Before Doing Arithmetic

A form gives every value as text. Predict the output, then explain the last call.

Code
String qtyText = "12";
String priceText = "1.5";
System.out.println(qtyText + 1);
int qty = Integer.parseInt(qtyText);
double price = Double.parseDouble(priceText);
System.out.println(qty + 1);
System.out.println(qty * price);
System.out.println(Integer.parseInt("12a"));
  1. 1Before parsing. qtyText + 1 joins text: "121".
  2. 2After parsing. qty + 1 adds: 13, and qty * price multiplies: 18.0.
  3. 3Text that is not a number. "12a" cannot be converted, so parseInt throws a NumberFormatException and the program stops.
Result: The program prints 121, 13, and 18.0, then stops with a NumberFormatException. Parse text into numbers before doing arithmetic, and only parse text that really is a number.

4Writing and Calling Your Own Class Methods

Any class can define class methods by including static in the header. A class that groups related static methods, such as unit conversions or tax calculations, acts like a toolbox: other code calls the tools through the class name, without creating objects. Class methods are a natural fit for computations whose result depends only on their parameters.

Because a class method is not tied to an object, it cannot use the data of any particular instance of its class; it works only with its parameters, its local variables, and other class-level items. That restriction is exactly what makes class methods simple to understand and test: the same arguments always produce the same result.

Grouping related class methods into one well-named class also helps readers. A call such as Units.kmToMiles(10.0) announces where the method lives and what kind of task it performs, before anyone opens the class. Choose class names that describe the family of tasks, and method names that describe the single task each one performs.

Worked Example 3 Your own class methods

Writing and Calling Static Methods in Another Class

A class Units provides conversion methods. Call them from a separate class.

Code
public class Units
{
    public static double kmToMiles(double km)
    {
        return km * 0.621371;
    }

    public static int minutesToSeconds(int minutes)
    {
        return minutes * 60;
    }
}
Output
6.21371
180
  1. 1The keyword static. Class methods include static in the header before the method name.
  2. 2Calling from another class. Units.kmToMiles(10.0) names the class, then the method. No Units object is created.
  3. 3Results. 10 km is 6.21371 miles; 3 minutes is 180 seconds.
Result: The calls print 6.21371 and 180. A class of related static methods works like a toolbox: you call each tool through the class name.
Worked Example 4 Compile errors

Forgetting the Class Name From Another Class

This call is in class Main, but kmToMiles is defined in Units. Explain the error.

Code that does not compile
public class Units
{
    public static double kmToMiles(double km)
    {
        return km * 0.621371;
    }
}
  1. 1The compiler looks in the current class. Without a class name, Java searches Main for a method named kmToMiles, and there is none.
  2. 2Fix. Write Units.kmToMiles(5.0).
Result: The compiler reports "cannot find symbol." Calls to class methods in another class need the class name and the dot operator.
Common Mistake 2 · Leaving Off the Class Name From Another Class

Calling kmToMiles(5.0) from a class other than the one that defines it does not compile, because Java looks for the method in the current class. From outside the defining class, always write ClassName.methodName(...).

5Calls Within the Defining Class

When the method call occurs in the defining class, the use of the class name is optional. A static method can call another static method in the same class by name alone: inside a class Trip, the method total can call tax(cost) directly. Writing Trip.tax(cost) would also work, but it is unnecessary.

This is why the examples in many guides call helper methods from main without a class name: main and the helpers live in the same class. The rule is about where the call is written, not about which method is called.

Figure 4. When the method call occurs in the defining class, the use of the class name is optional. Calls from any other class must include it.
Where the call is writtenHow to call a static method of class UnitsExample
Inside class UnitsMethod name alone (class name optional)kmToMiles(5.0)
In any other classClass name, dot, method nameUnits.kmToMiles(5.0)
Worked Example 5 Same class

Omitting the Class Name Inside the Class

Inside one class, a static method calls another static method. Predict the output.

Code
public static double tax(double cost)
{
    return cost * 0.1;
}

public static double total(double cost)
{
    return cost + tax(cost);
}
Output
55.0
22.0
  1. 1Inside the class. total calls tax(cost) with no class name, which is allowed because both methods are in the same class.
  2. 2From main. main is in the same class too, so total(50.0) works; writing Main.total(20.0) with the class name is also correct.
  3. 3Results. 50 + 5 = 55.0 and 20 + 2 = 22.0.
Result: The output is 55.0 and 22.0. When the call is in the defining class, the class name is optional.
Common Mistake 3 · Thinking the Class Name Is Always Required

Inside the class that defines a static method, the class name may be omitted. Both tax(cost) and Trip.tax(cost) are correct there. The name becomes required only when the call is written in a different class.

6Combining Calls

Because a call to a non-void class method produces a value, it can be used anywhere a value of its type is allowed, including as an argument to another method call. Math.abs(Integer.parseInt("-15")) first parses the text into −15 and then takes its absolute value. Java evaluates the innermost call first, then uses its result as the argument to the outer call.

Nesting calls keeps code compact, but deeply nested expressions are hard to read and debug. When an expression combines several calls, consider storing intermediate results in well-named variables, which also makes it easy to print and check each step.

Worked Example 6 Combining calls

Using One Class Method's Result in Another

Predict the output.

Code
System.out.println(Math.abs(Integer.parseInt("-15")));
System.out.println(Math.sqrt(Math.abs(-36)));
System.out.println(Math.abs(3 - 10) * 2);
Output
15
6.0
14
  1. 1Innermost first. Integer.parseInt("-15") returns −15; Math.abs of that is 15.
  2. 2Line 2. Math.abs(-36) is 36; Math.sqrt(36) is 6.0.
  3. 3Line 3. 3 - 10 is −7, its absolute value is 7, and 7 × 2 = 14.
Result: The results are 15, 6.0, and 14. A non-void class method call is an expression, so its result can be passed directly as an argument to another call.
Worked Example 7 Class name and dot

The Same Syntax for Class Constants

The class name and dot operator also reach values that belong to a class. Predict the output.

Code
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Math.abs(Integer.MIN_VALUE + 1));
Output
2147483647
-2147483648
2147483647
  1. 1No parentheses. Integer.MAX_VALUE and Integer.MIN_VALUE are values stored in the class, not method calls, so they take no parentheses, but they are reached the same way: class name, dot, member name.
  2. 2Line 3. Integer.MIN_VALUE + 1 is −2147483647, and its absolute value is 2147483647, which fits in an int.
Result: The output is 2147483647, −2147483648, and 2147483647. Members that belong to a class, whether methods or values, are reached through the class name and the dot operator.
Common Mistake 4 · Doing Arithmetic on Unparsed Text

A number that arrives as a String must be converted before arithmetic. "7" + "3" is "73" and "7" * 3 does not compile. Parse first with Integer.parseInt or Double.parseDouble.

Four Habits for Class Methods

1. static Means Class Method

It belongs to the class and needs no object.

2. Class Name, Dot, Method

The standard way to call it from anywhere.

3. Same Class: Name Optional

Inside the defining class, the method name alone works.

4. Parse Before Arithmetic

Integer.parseInt and Double.parseDouble turn text into numbers.

Core Synthesis

Class methods are associated with the class, not instances of the class, and include the keyword static in the header before the method name. 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. Library class methods such as Math.abs, Math.sqrt, Integer.parseInt, and Double.parseDouble are called this way, and the result of a non-void class method can be stored, printed, or passed to another method.