Task 3 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.5 Static and toString — static methods

Lesson

Methods that don't need an object

A static method belongs to the class, not to any object, so you call it on the class name — no new required. Static methods are handy for utilities that just work on their inputs. You have already used some: Math.max(...) and Integer.parseInt(...) are static.


Worked example

class Calc {
    static int add(int a, int b) {
        return a + b;
    }
}

System.out.println(Calc.add(2, 3));   // 5  — called on the class

No Calc object is created; add is called directly on Calc.


▶ Try it: add is static, so it is called as Calc.add(...). Run this, then change the arguments and re-run.



How do you call a static method add of class Calc?


Calc.add(2, 3) returns a + b. What is it?


Which is true of a static method?


True or false?


Type exactly what this program prints.

class Util {
    static int twice(int n) {
        return n * 2;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Util.twice(6));
    }
}