What is static variable and static method?
Answer Posted / kishore rajkumar
When static is used the VARIABLE or PROPERTY in the class is initialised only once. However, that does'nt mean that the value of the VARIABLE will remain unchanged. What i mean to say is, no matter how many instances of the class you create, your VARIABLE will not be re-initialized to its initial value for each new instance as opposed to a non-static variable.
Let us see an example;
public class StaticTest{
int a; // a non-static variable
static int b; // variable declared as static
StaticTest(){
a++;
b++;
}
public void display(){
System.out.println("a="+a);
System.out.println("b="+b)
}
}
class MainTest{
public static void main(String[] args){
StaticTest o1=new StaticTest();
StaticTest o2=new StaticTest();
StaticTest o3=new StaticTest();
o1.display();
}
}
output:
-----------------------------
a=1;
b=3;
EXPLAINATION:
===============
Look in the class " StaticClass ". Here, we have declared two variables 'a' & 'b'. Variable 'a' is a non-static variable whereas 'b' is declared as static.
Also, each time instance of this class(StaticClass) is created 'a' & 'b' are incremented inside the constructor.
Now, in the ' MainTest ' class we have created 3 seperate instances of the class ' StaticClass '.
Here, for each new instance the variable 'a' is re-initialized to its initial value and then incremented by 1.
As a result, its value is always 1 no matter how many instances we create.
But, in case of 'b' the value in not re-initialized everytime a new instance is created. Rather, it is initialized to its initial value only for the first instance and then its value is obtained by all the subsequent instances.
Hence, its value keeps on increasing as more and more instance are created.
| Is This Answer Correct ? | 1 Yes | 0 No |
Post New Answer View All Answers
What are predefined functions?
How do you remove all elements from an arraylist in java?
Explain the importance of finally block in java?
What is hashset in java?
Variable of the boolean type is automatically initialized as?
What is mysql driver class name?
Can we overload run() method in java?
Can a private method be declared as static?
What is the purpose of the system class in java programming?
Explain about the performance aspects of core java?
How do you sort a string in alphabetical order in java?
Tell us something about different types of casting?
Which list is sorted in java?
What is the nested interface?
Why java does not support pointers?