Ask Question
22 January, 00:39

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?

+3
Answers (1)
  1. 22 January, 00:56
    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 & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers