Summary: in this tutorial, you will learn how to use Java static methods to define behaviors at the class level.
Introduction to Java static methods
In Java, static methods are methods that belong to the class, rather than a specific instance of the class.
In practice, static methods are often used for creating utility functions, any operations that don’t depend on the object-specific state.
Defining static methods
To define a static method, you use the static
keyword before the return type of the method:
public class MyClass {
public static returnType methodName(parameters) {
// Method body
}
}
Code language: Java (java)
Invoking static methods
To call a static method, you use a class name, followed by a dot, and the method name:
MyClass.staticMethod();
Code language: Java (java)
Java static method example
The following example shows how to define a class called TemperatureConverter
that contains two static methods:
public class TemperatureConverter {
public static double CToF(double value) {
return value * 9 / 5 + 32;
}
public static double FToC(double value) {
return (value - 32) * 5 / 9;
}
}
Code language: Java (java)
The CToF
method converts a temperature from C to F and the FToC
converts a temperature from F to C.
The following program shows how to use the TemperatureConverter
class:
public class App {
public static void main(String[] args) {
var c = 38;
var f = TemperatureConverter.CToF(c);
System.out.println(f);
}
}
Code language: Java (java)
Output:
100.4
Code language: Java (java)
Summary
- Java static methods are bound to the class, not the instances of the class.
- Use static methods for defining classes with utility functions.