0
0
Javaprogramming~15 mins

Static methods in Java

Choose your learning style8 modes available
menu_bookIntroduction

Static methods let you run code without making a new object. They belong to the class itself, not to any one thing.

When you want a utility function like math calculations that doesn't need object data.
When you want to share a method that works the same for all objects of a class.
When you want to call a method before creating any objects.
When you want to group helper methods inside a class without needing instances.
regular_expressionSyntax
Java
public class ClassName {
    public static returnType methodName(parameters) {
        // method body
    }
}

The keyword static means the method belongs to the class, not an object.

You call static methods using the class name, like ClassName.methodName().

emoji_objectsExamples
line_end_arrow_notchThis static method adds two numbers. You can call it without making a MathUtils object.
Java
public class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }
}
line_end_arrow_notchThis static method prints a greeting. Call it as Greeting.sayHello().
Java
public class Greeting {
    public static void sayHello() {
        System.out.println("Hello!");
    }
}
code_blocksSample Program

This program defines a static method multiply that multiplies two numbers. The main method calls it using the class name without creating an object.

Java
public class Calculator {
    public static int multiply(int x, int y) {
        return x * y;
    }

    public static void main(String[] args) {
        int result = Calculator.multiply(4, 5);
        System.out.println("4 times 5 is " + result);
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Static methods cannot use instance variables or methods directly because they don't belong to an object.

line_end_arrow_notch

You can call static methods from instance methods, but instance methods cannot be called from static methods without an object.

list_alt_checkSummary

Static methods belong to the class, not objects.

Call static methods using the class name.

Use static methods for utility or shared behavior that doesn't need object data.