Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Static Variable

Posted By: Luz Hayes     Category: Java     Views: 2330

This article explains about static variable in java with example.

Static variable is a class variable not an object variable. When a number of objects are created from the same class, each instance has its own copy of class variables. But this is not the case when it is declared as static. static  method or a variable is not attached to a particular object, but rather to the class as a whole. You can also say that static variables are not an instance variable

Syntax of Static Variable

static type varName = value; 

type is any data type in java.
varName is any valid identifier in java. It is a variable name.
value is an optional. You can initialize variable by assigning its value. 

Example of Static Variable

Example 1 : Program that illustrates static variable use in java

class Employee
public class StaticVariable
{
  static int noOfObjects = 0;

  StaticVariable()
  {
    noOfObjects++;
  }

  public static void main(String[] args)
  {

    StaticVariable sObj1 = new StaticVariable();
    System.out.println("Number of objects for sObj1 : " + sObj1.noOfObjects);

    StaticVariable sObj2 = new StaticVariable();
    System.out.println("");
    System.out.println("Number of objects for sObj1 : " + sObj1.noOfObjects);
    System.out.println("Number of objects for sObj2 : " + sObj2.noOfObjects);

    StaticVariable sv3 = new StaticVariable();
    System.out.println("");
    System.out.println("Number of objects for sObj1 : " + sObj1.noOfObjects);
    System.out.println("Number of objects for sObj2 : " + sObj2.noOfObjects);
    System.out.println("Number of objects for sObj3 : " + sObj3.noOfObjects);

  }
}


Output

Number of objects for sObj1 : 1

Number of objects for sObj1 : 2
Number of objects for sObj2 : 2

Number of objects for sObj1 : 3
Number of objects for sObj2 : 3
Number of objects for sObj3 : 3

As you can note that noOfObjects variable is shared among all objects of class StaticVariable. 
  
Share: 

 
 
 

Didn't find what you were looking for? Find more on Static Variable Or get search suggestion and latest updates.

Luz Hayes
Luz Hayes author of Static Variable is from Chicago, United States.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!