Write a Java-program to print static method and static variable

Write a Java-program to print static method and static variable

Program
class Demo
{
    int x=10; //non static variable
    static int y=20; // static variable

    void show()
    {
        System.out.println(x); // You get output
        System.out.println(y); // You get output
    }

    static void disp()
    {
        //System.out.println(x); // You get error
        //because static mentods can not accept non static variables
        System.out.println(y); // You get output
    }
}

public class Main
{
public static void main(String args[])
{
    
    Demo d=new Demo();
    d.show(); // You get output
    d.disp(); // You get output
    System.out.println(d.x); // You get output
    System.out.println(d.y); // You get output


    //Note: By using object we have to call all static and non static variables and methods
    
    //Demo.show(); You Get error
    Demo.disp(); // You get output
    //System.out.println(Demo.x); // You get error
    System.out.println(Demo.y); // You get output


    //Note: By using class we have to call static methods and static variables only
}
}

Output:

10
20
20
10
20
20
20





More Questions


109 . Write a Java-program to print static method
110 . Write a Java-program to print static variable
111 . Write a Java-program to using static block
112 . Write a Java-program to print addition ,substraction ,multiplication,division using oops (using single class)
113 . Write a Java-program to print addition ,substraction ,multiplication,division using oops (using multiple classes)
114 . Write a Java-program to print Max Number program using no parametarized constructor with no return type with no parametarized method
115 . Write a Java-program to print Max Number program using no parametarized constructor with no return type with parametarized method
116 . Write a Java-program to print Max Number program using no parametarized constructor with return type with no parametarized method
117 . Write a Java-program to print Max Number program using no parametarized constructor with return type with parametarized method
118 . Write a Java-program to print Max Number program using no parametarized constructor with no return type with no parametarized method
119 . Write a Java-program to print Max Number program using parametarized constructor with no return type with parametarized method