Home Java Example Java Core Static variable in java

Related Tutorials


 
 

Share on Google+Share on Google+

Static variable in java

Advertisement
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.

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

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 7, 2013

Related Tutorials

Discuss: Static variable in java  

Post your Comment


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