Static variable in java

Static data members

Data members declared with static keyword are generally known as static data members. These are primarily used to characterize these properties that are common to each object. On the time of class loading a single copy is created for static data members and it will be shared by all objects.
Memory division in a java program execution.
In a java program execution memory is divided into three parts:

  • Stack: It is used to store local variables of the methods.
  • Heap: It is used to store objects.
  • Class Area: It is used to store static data members.

Static data members are used to represent common properties of each object.
Example

/**
 * This program is used to show that static data members are
 * used to represent those properties which are common to every object. 
 * @author W3spoint
 */
class Student{
	//name and rollNo are not common for all students so keep them as non-static data members.
	String name;
	int rollNo;
	//As course offered is same for all students so keep it as static.
	String courseName = "MCA";
 
	//constructor
	Student(String n, int r){
		name = n;
		rollNo = r;
	}
 
	//display all values
	public void display(){
		System.out.println("Name = " + name);
		System.out.println("RollNo. = " + rollNo);
		System.out.println("Course Name = " + courseName);
		System.out.println("");
	}	
}
 
public class StaticExample {
	public static void main(String args[]){
		//create object of Student class.
		Student stu1 = new Student("Sandy", 19);
		Student stu2 = new Student("Amani", 15);
 
		//method call
		stu1.display();
		stu2.display();
	}
}

Output

Name = Sandy
RollNo. = 6
Course Name = MCA
Name = Amani
RollNo. = 15
Course Name = MCA
Please Share