Krivalar Tutorials 
Krivalar Tutorials

Java static variable

<< volatile Keyword

local variable >>

static variables

static variable is a variable marked by a static keyword. static Variables are properties of a class.

  • For a static variable, there will be only one copy of the variable for all instances you create for the class.
  • For example, if you store a value 10 in a static variable say count, all instances will have the same value for the static variable
  • static variable is different from instance variables which are per instance
  • if a static variable is modified, it changes for all the instances or objects created for the class
  • static variable is to store data at the class level. For example, static variable can be used to store:
    • count of employess
    • sum of numbers in all instances
    • List of names contained in all instances

public static variables are global in nature

static variables without public keyword are accessible only within the the package in which it is declared1qqqq

static variable usage - high level example

static int countOfEmployees=1000;
static char flag='C';
static float totalRevenue=0.0;
static List listOfElements;
static Set setOfColors=new HashSet();

Values assigned to static variable can be modified or updated by other parts of the code

static variable inside interfaces

static variables can be used inside interfaces. static interface

public interface Ocean {
	static int t=0;

static variable - detailed example

public class Employee{
 	//countOfEmployees is a static variable
	public static int countOfEmployees=0;
	//following are instance variables
	String name;
	int age;
	float salary;
	String Designation, responsibilities, benefits;
	Vector education;

	public Employee(String name, int age, String Designation){;
	public int getAge(){
		return age;
	public setAge(int age){
	public static void main(String args[]){
		Employee emp1 = new Employee("Jake","28","Business Analyst");
		Employee.countOfEmployees++; //increments count by 1
		Employee emp2 = new Employee("Dev","42","Product Owner");
		Employee emp3 = new Employee("Emma","52","President - Operations");
		Employee emp4 = new Employee("Ivan","43","Engineer - Electronics");
		Employee emp5 = new Employee("Priya","39","Manager - Sales");

		System.out.println( emp1.countOfEmployees);
		System.out.println( emp2.countOfEmployees);
		System.out.println( emp3.countOfEmployees);
		System.out.println( emp4.countOfEmployees);
		System.out.println( emp5.countOfEmployees);
		//static variables can be accessed just by using the class name
		//without creating any instance
		System.out.println( Employee.countOfEmployees);

Static varible - Program Output

The above program prints 5 whenever tried to print the value of countOfEmployees. This is because we always access the same variable regardless of invoking emp1.countOfEmployees or Employee.countOfEmployees


<< volatile Keyword

local variable >>

Searching using Binary Search Tree