Lesson 1.9 · Unit 1 · CED topic 1.10

Calling class methods

Some methods belong to a class as a whole rather than to any one object. You have used several already without creating anything: Math.sqrt(49) does not need a Math object, because Math is a toolbox of methods that stand on their own. This lesson explains what makes those methods different, and how to call and write them.

Required content · LO 1.10.A

Learning objective.

  • 1.10.A. Develop code to call class methods and determine the result of those calls.

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.
  • 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.

What a class method is

Class methods are associated with the class, not with instances of the class. A class method has the keyword static in its header, before the return type.

public static int square(int n)

Because a class method belongs to the class, you do not create an object to call it. The usual call uses the class name with the dot operator.

public class Converter {
    public static double toFahrenheit(double celsius) {
        return celsius * 9.0 / 5.0 + 32.0;
    }

    public static int square(int n) {
        return n * n;
    }
}
double boiling = Converter.toFahrenheit(100);
int area = Converter.square(7);
System.out.println(boiling);
System.out.println(area);
212.0
49

When the call appears in the class that defines the method, the class name is optional: inside Converter you may write square(7) instead of Converter.square(7). From any other class you must name the class.

Calling a method and using its value

Everything from Lesson 1.9 still applies. The arguments must match the parameter types in number and order. A void class method is a statement by itself; a non-void class method returns a value that you store or use in an expression, and a method call can be an argument to another method call.

System.out.println(Converter.square(Converter.square(3)));
81

The inner call runs first and returns 9; that value is the argument for the outer call, which returns 81.

Why call a class method without an object

A class method is the right tool when the work depends only on its arguments. Converting a temperature needs no stored state: give it a number, get a number. Methods that depend on the data stored in a particular object are instance methods (Lesson 1.14), and they are called on an object instead.

Class methodInstance method
Header hasstaticno static
Belongs tothe classone object of the class
Called withClassName.method(args)objectName.method(args)
Needs an object firstnoyes
Worked example · calling class methods from another class

Which statements work, and what do they print?

int a = Converter.square(5);
double f = Converter.toFahrenheit(0);
System.out.println(a + " " + f);
25 32.0

The class name is in front of each call, no object was created, and the int argument 0 was widened to the double the parameter needs. Both results are stored in variables whose types match the return types.

Worked example · the class name is optional inside the class

A main method in the same class as the helper methods.

public class Main {
    public static int cube(int n) {
        return n * n * n;
    }

    public static int sumOfCubes(int a, int b) {
        return cube(a) + cube(b);
    }

    public static void main(String[] args) {
        System.out.println(sumOfCubes(2, 3));
        System.out.println(Main.cube(4));
    }
}
35
64

sumOfCubes calls cube with no class name, which is legal because both methods are in Main. main may use either form. The first line is 8 + 27.

Worked example · why this will not compile

Three common mistakes with class methods.

public class Main {
    public int getFive() {
        return 5;
    }

    public static void main(String[] args) {
        int x = getFive();
    }
}
Main.java:7: error: non-static method getFive() cannot be referenced from a static context
        int x = getFive();
                ^
1 error

getFive has no static in its header, so it is an instance method and needs an object. main is a class method and has no object. The other two mistakes are equally common: a call from another class with no class name (square(7) instead of Converter.square(7)) fails with cannot find symbol, and a wrong argument type (Converter.square("7")) fails with incompatible types: String cannot be converted to int.

Exam focus

Expect code with a mix of class method calls (possibly nested) and a question that asks for the printed value, or one that asks why a call will not compile. For a compile question, check three things in order: is the method static (or is there an object), does the class name appear where it must, and do the arguments match the signature. Inside the defining class the class name is optional.

Practice
  1. What is printed?
    System.out.println(Converter.square(2) + Converter.square(3));
    Show answer

    13. The calls return 4 and 9, and the sum is 13.

  2. What is printed?
    System.out.println(Converter.square(Converter.square(2)));
    Show answer

    16. The inner call returns 4, which becomes the argument of the outer call.

  3. A class Tools declares public static int twice(int n). Write a statement outside Tools that stores twice(8) in int r.
    public class Tools {
        public static int twice(int n) {
            return n * 2;
        }
    }
    int r = Tools.twice(8);
    System.out.println(r);
    Show answer

    int r = Tools.twice(8);. From another class the call needs the class name and the dot operator, and no Tools object is created.

  4. What keyword in a method header marks it as a class method?
    Show answer

    static.

  5. Will this call compile from another class? Why or why not?
    double d = Converter.toFahrenheit("32");
    Show answer

    No. The parameter is a double and the argument is a String, so the compiler reports incompatible types: String cannot be converted to double.

  6. From inside Converter, which of these calls to square are legal?
    A.  square(4);
    B.  Converter.square(4);
    C.  new Converter().square(4);
    Show answer

    A and B. Inside the defining class the class name is optional, so both name the same method. C also compiles in Java, but it is unnecessary for a class method, and the exam writes class-method calls as in A or B.

← 1.8 Method signatures1.10 The Math class →

Keep going in the full AP Computer Science A course

All of U1 (Using Objects and Methods) is free to everyone, with no account. The course has 58 lessons, each with worked examples and practice problems that come with full solutions. A free account can also start a free month of the whole course, with no card.

Open this lesson in the courseSee the whole course