Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training

Static variable in java

Static is a keyword in java used to create static methods, variable inside a class and static class.Static variable is also called class variable which belongs to class not to object.Static variable is declared inside a class but outside the method or Constructor.

Ads

Static variable in java.

  • Static is a keyword in java used to create static methods, variable inside a class and static class.
  • Static variable is also called class variable which belongs to class not to object.
  • Static variable is declared inside a class but outside the method or Constructor.
  • These variable are initialized first before initializing of any instance variable.
  • A single copy is shared by a class, as many objects are created.
  • Static variable is accessed without creating object of class using class name.
  • Static variable are created when the program starts and destroys when the program stop.
  • Visibility of class/static variable is same but mostly it is public. Because it is visible for all user in the class.

Syntax :  Classname.variablename;

Example: Using Static Variable.

public class Staticvariable 
{
  static double salary;	 //static variable
   int age;              //non static variable 
    Staticvariable()
      {
        age=23;
          }
                  public static void main(String args[])
	  {
		  salary=10000;
		 Staticvariable sv= new Staticvariable();     // creating object for accessing non static member.
                                     System.out.println("Salary of Employee is="+Staticvariable.salary);  // accessing static variable through class name.
                                     System.out.println("Age of  of Employee is="+sv.age);	// Accessing non static variable through object.	 
	   }

	}

In the above program , Class has two variable one is class variable as salary and  another one is non-static variable as age , age accesses  by object of the class (sv) and salary  is accessed directly by classname.

Output : After Compiling and Executing of above program.

s

Download SourceCode

Advertisements

Ads
Share on Google+Share on Google+

Static variable in java

Posted on: May 7, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Static variable in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads