In this tutorial, we will learn about static keyword in Java. The main motive of the static keyword in Java is memory management. We can use static keyword with variable, method and block. An important thing to know that a static method, variable and block can be used without creating an object of the class.
Page Contents
Static Variable:
To make a variable static just add the static keyword while declaring variable for e.g. static int var=10; The main motive of the static variable is to refer the common property to all the object. Suppose you are creating a class called Student and in this class, you can make college name variable static. Because this property for multiple students would be the same. It is important to note the static variable take memory only once. It doesn’t matter how many objects you are creating for particular class.
Example Program:
class Student{
int studentRollno; //instance variable
String studentName; //instance variable
static String collegeName ="ABC"; //static variable
//class constructor
public Student(int rollno, String name){
studentRollno = rollno;
studentRollno = name;
}
//show method
void show(){
System.out.println(studentRollno+" "+studentName+" "+collegeName);
}
}
public class StaticExample{
public static void main(String args[]){
Student obj1 = new Student(101,"Rahul");
Student obj2 = new Student(102,"Puneet");
obj1.show();
obj2.show();
}
}
Static Method:
We can create a static method just by adding the static keyword in starting while defining a method. The Static methods can be called without creating an object of class because static methods belong to the class rather than an instance of the class. Static method class easily use and change static variables in a class and if you will write any variable inside the static method it would be automatically considered as a static variable.
Important to note that, static method cannot use non static global variables directly.
Example program:
class MyClass{
static void show(){
System.out.println("This is show method in MyClass.");
}
}
class StaticExample{
public static void main(String args[]){
MyClass.show();
MyClass.show();
}
}