In Java, static methods are methods that belong to a class rather than an instance of the class. They are called on the class itself, rather than on an object created from that class. Static methods have several common use cases:
Utility Methods: Static methods are often used for creating utility functions that don't depend on the state of any particular instance but provide general functionality. These methods are typically placed in utility classes or helper classes.
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
public static double squareRoot(double value) {
return Math.sqrt(value);
}
}
// Usage
int sum = MathUtils.add(5, 3);
double sqrt = MathUtils.squareRoot(16.0);
Factory Methods: Static methods can be used to create and return instances of a class. For example, the getInstance() method in the Singleton pattern.
public class Singleton {
private static Singleton instance;
private Singleton() {
// Private constructor to prevent direct instantiation
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
// Usage
Singleton singleton = Singleton.getInstance();
I'll create a Car class with a static method to calculate the average miles per gallon (MPG) for a group of cars.
public class Car {
private String make;
private String model;
private double fuelEfficiency; // Miles per gallon (MPG)
public Car(String make, String model, double fuelEfficiency) {
this.make = make;
this.model = model;
this.fuelEfficiency = fuelEfficiency;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public double getFuelEfficiency() {
return fuelEfficiency;
}
public double calculateMilesPerGallon(double gallons) {
return gallons * fuelEfficiency;
}
// Static method to calculate the average MPG for a group of cars
public static double calculateAverageMPG(Car[] cars) {
if (cars.length == 0) {
return 0.0;
}
double totalMPG = 0;
for (Car car : cars) {
totalMPG += car.getFuelEfficiency();
}
return totalMPG / cars.length;
}
}
In this Car class, we have a static method called calculateAverageMPG that takes an array of Car objects as a parameter and calculates the average MPG of all the cars in the array. This static method does not depend on any particular instance of the Car class and can be called using the class name, like this:
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Toyota", "Camry", 30.0);
Car car2 = new Car("Honda", "Civic", 35.0);
Car car3 = new Car("Ford", "Focus", 28.0);
Car[] cars = {car1, car2, car3};
double averageMPG = Car.calculateAverageMPG(cars);
System.out.println("Average MPG for the group of cars: " + averageMPG);
}
}
In this example, we create three Car objects and calculate the average MPG for the group of cars using the static calculateAverageMPG method.