Ask Question
17 August, 05:33

How are static variables and methods created in Java? What happens if a non-static method of a class tries to access a static variable of that class? What happens to the static variables of a class once the class has no instances?

+5
Answers (1)
  1. 17 August, 08:31
    0
    Static variables are the variables decaraed with keyword static, static variables must be deacraled inside the class body, means we can not declare a static variable inside a method or consttructor, static variable belongs to class, for a class only one copy is created for static variable and used by all the objects/instances.

    Static variable can access with class name like

    X. i

    Static method are the methods defined with static keyword, static method are also part of a class, we can access static meethod using class name like

    X. printI ()

    Explanation:

    class X

    {

    //to create a static variable we need use static keyword with variable name like

    public static int i;

    / / to create a static method we need to use static keyword while defining a method like

    public static void printHello () {

    System. out. println ("Hello");

    }

    /*

    * A non static method can access static variable of a class there is no issue

    * with that we can use a static variable in a non static method like

    */

    public void printI () {

    System. out. println (i);

    }

    /*

    * As long as the class exist in JVM static variables will be there, as static

    * variable belong to class not with the instance,

    * it does not matters if there are instance exist or not

    */

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “How are static variables and methods created in Java? What happens if a non-static method of a class tries to access a static variable of ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers