Static Function or Method and Its Usage in Java Example Program

Static Function Overview

  • Static method or variable belongs to the class and not to object.
  • Static method or variable can be used to all Objects created from the same class.
  • Static variables initialized only once in the time of class loading.
  • It Can use Static method or variable without instance creation.
  • Static methods can be overloaded.But can not be overridden.

Syntax

class ClassName{
    public <ReturnType> static methodName() {
        //Do Something
    }
}

Static Function or Method and Its Usage in Java Example Program

public class StaticMethodAndUsages {
    public static int staticMethod(){
        int num1 = 100, num2 = 200,result;
        result = num1+num2;
        return result;
    }
    
    public static void main(String[] args) {
        System.out.println("Result from static method is : "+staticMethod());
    }
}

Sample Output

Result from static method is : 300