Big Data and Hadoop Training @$80 or Rs. 6,000 only - valid till Oct 17th Apply Now!

Static variable in java

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.

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

Ads

Ads