Static methods let you run code without making a new object. They belong to the class itself, not to any one thing.
0
0
Static methods in Java
Introduction
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.
Syntax
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().
Examples
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!"); } }
Sample 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
Important 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.
Summary
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.
