In Java, some methods belong to the class instead of an object. These methods are called class methods, also known as static methods.
Example you already know:
System.out.println("Hello");
println() is being called using the class name System.out.
Class methods contain the word static in the method header:
public static int abs(int x)
We call a class method using:
ClassName.methodName()
Examples:
Math.sqrt(25); // returns 5.0
Math.random(); // returns a random double 0.0-1.0
Integer.parseInt("42"); // returns 42
Notice: We do NOT create an object of Math.
Students must NOT do this:
Math m = new Math();
double r = m.random(); // WRONG - NOT ALLOWED
The correct call:
double r = Math.random();
| Concept | Meaning |
|---|---|
| class method | method that belongs to the class |
| keyword used | static |
| called using | ClassName.method() |
| creates an object? | No |