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


Please Help Members By Posting Answers For Below Questions

Can we have any other return type than void for main method?

638


What is dynamic binding(late binding)?

695


Write a function for palindrome and factorial and explain?

763


What is the best definition for data?

608


What is the main purpose of serialization in java?

638






how we can make a read-only class in java?

638


Which collection is sorted in java?

652


Is 64bit faster than 32 bit?

680


Why isn’t there operator overloading?

692


What do you understand by classes in java?

663


What is a substring of a string?

648


How are variables stored in memory?

691


Can a final variable be initialized in constructor?

581


Is java util regex pattern thread safe?

623


why would you use a synchronized block vs. Synchronized method? : Java thread

614