Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

JAVA Static Variable

  • • The variable declared by the keyword static is known as static variable.
  • • We know that once a class is declared, we can declare any no. of objects belonging to that class. When all objects want to access a particular variable, then we can declare that variable as static, that means static variable can be used to refer the common property of all objects.
  • • The static variable gets memory only once in class area at the time of class loading.
  • • It makes your program memory efficient, that means it saves memory.

Suppose there are 1000 students in SILAN Engineering College, now all instance data members will get memory each time when object is created. All student have its unique regdno and name so instance data member is good. Here, the property cname(college name) refers to the common property of all objects. If we make it static, this field will get memory only once.

Example

package com.silan;
class Student
{
	int regdno;
	String name;
	static String cname="SILAN";
	 
	Student(int regdno, String name)
	  	{
			this.regdno=regdno;
			this.name=name;
	  	}
	 
	void show()
	{
		System.out.println(regdno+""+name);
		System.out.println(cname);
	}
}

public class StaticExample1 {

	public static void main(String[] args) {
		   
		Student s1=new Student(101,"Sidhant");
		Student s2=new Student(102,"Sonali");
		s1.show();
		s2.show();
	}

}

Output:


static variable

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc







 PreviousNext