Sobes.tech
Junior — Middle

Can you explain what a static method in Java is and how it is used?

sobes.tech AI

Answer from AI

In Java, a static method is a method that belongs to the class itself rather than to a specific instance of the class. It can be called without creating an instance of the class.

Static methods are usually used for operations that do not depend on the state of an object, such as utility functions.

Example:

public class MathUtils {
    public static int sum(int a, int b) {
        return a + b;
    }
}

// Calling a static method
int result = MathUtils.sum(3, 5); // result = 8

It is important to remember that inside a static method, you cannot access non-static fields or methods of the class, as they are associated with a specific object.

Can you explain what a static method in Java is and… - sobes.tech