107k views
0 votes
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?

1 Answer

2 votes

Answer:

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()

Step-by-step 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

*/

}

User Alex Coroza
by
5.1k points