static methods
- Java course
- Intermediate
- Lesson 31/116
- 5 min
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.
Practice 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.
Starter code
// Define the MathUtil class
// Add static square and cube methods
// Call and print in mainSample 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));
}
}Expected output
9 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the static method parts
| Term | Meaning |
|---|---|
static |
Keyword |
square |
Method name |
MathUtil.square(5) |
Class-name call |
return n * n |
Body |
2 Which cannot be accessed inside a static method?
- An instance field Correct answer
- A static method
- A static field
- A parameter
Explanation: An instance field — instance data is not accessible in a static context.
3 Complete the static method definition
class MathUtil {
____ int square(int n) {
return n * n;
}
}
class MathUtil {
static int square(int n) {
return n * n;
}
}
Explanation: A static method is called without an instance.