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.
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.
| Class method (static) | Instance method | |
|---|---|---|
| Belongs to | The class itself | Each object (instance) of the class |
| Header | Includes the keyword static | No static |
| Called with | The class name: Math.sqrt(16) | An object: word.length() |
| Needs an object? | No | Yes |
| Examples | Math.abs, Integer.parseInt | substring, add |
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.
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.
Integer.parseInt and Double.parseDouble convert text into numbers so that arithmetic can be done.| Class method | Returns | Example | Result |
|---|---|---|---|
Math.abs(int) | int | Math.abs(-9) | 9 |
Math.sqrt(double) | double | Math.sqrt(2.25) | 1.5 |
Integer.parseInt(String) | int | Integer.parseInt("305") | 305 |
Double.parseDouble(String) | double | Double.parseDouble("0.5") | 0.5 |
Calling Class Methods From java.lang
Predict each result and its type.
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));
7
43
5.0
7.0
- 1
Math.abs(-7). Theintversion ofabsreturns theint7. - 2
Integer.parseInt("42") + 1. The text "42" becomes theint42, then 1 is added: 43. - 3
Double.parseDouble("2.5") * 2. 2.5 × 2 = 5.0, adouble. - 4
Math.sqrt(49). Returns adouble, so 7.0. - 5The pattern. Every call starts with a class name, because these methods belong to the class rather than to any object.
Converting Text Before Doing Arithmetic
A form gives every value as text. Predict the output, then explain the last call.
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"));
- 1Before parsing.
qtyText + 1joins text: "121". - 2After parsing.
qty + 1adds: 13, andqty * pricemultiplies: 18.0. - 3Text that is not a number. "12a" cannot be converted, so
parseIntthrows aNumberFormatExceptionand the program stops.
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.
Writing and Calling Static Methods in Another Class
A class Units provides conversion methods. Call them from a separate class.
public class Units
{
public static double kmToMiles(double km)
{
return km * 0.621371;
}
public static int minutesToSeconds(int minutes)
{
return minutes * 60;
}
}
6.21371
180
- 1The keyword
static. Class methods includestaticin the header before the method name. - 2Calling from another class.
Units.kmToMiles(10.0)names the class, then the method. NoUnitsobject is created. - 3Results. 10 km is 6.21371 miles; 3 minutes is 180 seconds.
Forgetting the Class Name From Another Class
This call is in class Main, but kmToMiles is defined in Units. Explain the error.
public class Units
{
public static double kmToMiles(double km)
{
return km * 0.621371;
}
}
- 1The compiler looks in the current class. Without a class name, Java searches
Mainfor a method namedkmToMiles, and there is none. - 2Fix. Write
Units.kmToMiles(5.0).
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.
| Where the call is written | How to call a static method of class Units | Example |
|---|---|---|
| Inside class Units | Method name alone (class name optional) | kmToMiles(5.0) |
| In any other class | Class name, dot, method name | Units.kmToMiles(5.0) |
Omitting the Class Name Inside the Class
Inside one class, a static method calls another static method. Predict the output.
public static double tax(double cost)
{
return cost * 0.1;
}
public static double total(double cost)
{
return cost + tax(cost);
}
55.0
22.0
- 1Inside the class.
totalcallstax(cost)with no class name, which is allowed because both methods are in the same class. - 2From
main.mainis in the same class too, sototal(50.0)works; writingMain.total(20.0)with the class name is also correct. - 3Results. 50 + 5 = 55.0 and 20 + 2 = 22.0.
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.
Using One Class Method's Result in Another
Predict the output.
System.out.println(Math.abs(Integer.parseInt("-15")));
System.out.println(Math.sqrt(Math.abs(-36)));
System.out.println(Math.abs(3 - 10) * 2);
15
6.0
14
- 1Innermost first.
Integer.parseInt("-15")returns −15;Math.absof that is 15. - 2Line 2.
Math.abs(-36)is 36;Math.sqrt(36)is 6.0. - 3Line 3.
3 - 10is −7, its absolute value is 7, and 7 × 2 = 14.
The Same Syntax for Class Constants
The class name and dot operator also reach values that belong to a class. Predict the output.
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Math.abs(Integer.MIN_VALUE + 1));
2147483647
-2147483648
2147483647
- 1No parentheses.
Integer.MAX_VALUEandInteger.MIN_VALUEare 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. - 2Line 3.
Integer.MIN_VALUE + 1is −2147483647, and its absolute value is 2147483647, which fits in anint.
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.
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.