Java-Static Methods

Static Methods

Like static member variable, we can also have static methods. Static methods do not operate on objects. Static method can access static data member and can change the value of it. A static methods can be accessed directly by the class name and doesn’t need any object. Static methods can only access static variables and static methods.

Program

final

Program Source

class Data {
    
    static int staticData = 20;
    int nonStaticData = 40;
    
    static void staticMethod()
    {
        System.out.println("staticData : "+staticData);
        staticData+=20;
        System.out.println("staticData : "+staticData);
    }
    
    void nonStaticMethod()
    {
        System.out.println("nonStaticMethod");
    }
}


public class Javaapp {

    public static void main(String[] args) {
        
        Data.staticMethod();
        
        Data obj = new Data();
        obj.nonStaticMethod();
    }
}

Leave a Comment