Java
static methods
Learn static methods and the Math example.
static method
A static method belongs to the class; it can be called without creating an instance. Many Java methods like Math.abs(-5) and Integer.parseInt("10") are static. They are ideal for utility methods.
Example: class MathUtil { static int square(int n) { return n * n; } }. This method is called as MathUtil.square(5); no new MathUtil() is needed. Static methods are called through the class name. this cannot be used inside them; because they do not belong to an instance. They directly access only static fields and other static methods. This makes utility methods quick and easy to use.
No this allowed
Inside static methods, this cannot be used. Because this refers to the calling instance; in a static method there is no instance. Likewise, instance fields and instance methods cannot be directly accessed.
Example: static void print() { System.out.println(this.name); } does not compile; this is invalid in a static context. If name is an instance field, it cannot be accessed from print. Only static fields are accessible. This restriction reflects that static methods operate at the class level. If instance data is needed, it is passed as a parameter or an instance method is used.
Exercise Add static methods to MathUtil
Define a class MathUtil. Add a static int square(int n) method returning n * n. Add a static int cube(int n) method returning n * n * n. In main call MathUtil.square(3) and MathUtil.cube(2), print the results on separate lines.
Show example solution
class MathUtil {
static int square(int n) {
return n * n;
}
static int cube(int n) {
return n * n * n;
}
public static void main(String[] args) {
System.out.println(MathUtil.square(3));
System.out.println(MathUtil.cube(2));
}
}
Test yourself
-
Match the static method parts
- static
- Keyword
- square
- Method name
- MathUtil.square(5)
- Class-name call
- return n * n
- Body
-
Which cannot be accessed inside a static method?
- An instance field
- A static method
- A static field
- A parameter
Show answer
An instance field — An instance field — instance data is not accessible in a static context.
-
Complete the static method definition
class MathUtil {
____ int square(int n) {
return n * n;
}
}
Show answer
class MathUtil {
static int square(int n) {
return n * n;
}
}
Next lesson: static block