static and this Keywords in Java With Examples

Java static keyword

The static keyword in Java is used for the purpose of defining a member to belong to a class rather than an instance. By member we mean

  • Variables
  • Methods
  • Block

Let us look at the significance of the static keyword on each of them.

Static Variable

Declaring a variable as static makes it a static variable. It is used to define the common attribute that is to be shared among all the instances of an object. It is used for saving memory when it is known that all objects are going to share the same value for a specific attribute. To access such a variable, we do not need any instance. We can simply access it using the Class name. Since it is shared, any change made in such a variable gets reflected in every instance.

Example: <ClassName>.<staticVariable>

As a result, the variable gets loaded in memory only once, that too at the time of class loading.

Example:

While creating a Java application for School, we realize that the students will have the same school name attribute. So instead of making the school name attribute, an instance variable, we make it a static variable. There will be only one memory allocation, instead of each copy for every student.

Non-Static Approach: Here school is an instance variable. As a result, every instance is going to have to its own copy resulting in wastage of space

class Students{ 
   //Instance Variable
   String name;
   String clas;
   String sec;
   int rollNo;
   String school;
   //Parameterized Constructor  
   Students(String n,String c, String s, int rn, String sch){  
    name=n;
    clas=c;
    sec=s;
    rollNo=rn;
    school=sch; 
   }  

   //method to print the details 
   void getDetails(){System.out.println(name+" "+clas+" "+sec+" "+rollNo+" "+school);}  
}  
 
public class School{  
 public static void main(String args[]){  
 Students obj1 = new Students("Gourav Gupta","XII","C",7,"Don Bosco High School"); 
 Students obj2 = new Students("Madhurav Prasad","XI","A",25,"Don Bosco High School");  

 
 obj1.getDetails();  
 obj2.getDetails();  
 }  
}  

Output:

Gourav Gupta XII C 7 Don Bosco High School
Madhurav Prasad XI A 25 Don Bosco High School

Static Approach: We can declare the school as static, and it will yield the same performance saving lots of memory.

class Students{ 
   //Instance Variable
   String name;
   String clas;
   String sec;
   int rollNo;
   //Static Variable
   static String school="Don Bosco High School";
   //Parameterized Constructor  
   Students(String n,String c, String s, int rn){  
    name=n;
    clas=c;
    sec=s;
    rollNo=rn;
   }  
   //method to display the values  
   void display (){System.out.println(name+" "+clas+" "+sec+" "+rollNo+" "+school);}  
}  
 
public class School{  
 public static void main(String args[]){  
     
 System.out.println("School is a class member. Can be accessed by Class Name also.\nSchool Name:"+Students.school+"\n");
     
 Students obj1 = new Students("Gourav Gupta","XII","C",7); 
 Students obj2 = new Students("Madhurav Prasad","XI","A",25);

 
 obj1.display();  
 obj2.display();  
 }  
}  

Output:

School is a class member. Can be accessed by Class Name also.
School Name:Don Bosco High School

Gourav Gupta XII C 7 Don Bosco High School
Madhurav Prasad XI A 25 Don Bosco High School

Static Method

Declaring a method as static makes it a static method. As a result, the class belongs to the class rather than the object. To access such a method, we do not need any instance. We can simply access it using the Class name.

Example: <ClassName>.<staticMethod>(<Parameter-list>)

It is for this reason the main method is static in nature. The main serves to be the entry point of the program execution. Making it static allows the JVM to execute using Class only without instantiating and allocating unnecessary memory.

A static method can only access the static variable and not the instance variable.

Example:

class Students{ 
   //Instance Variable
   String name;
   String clas;
   String sec;
   int rollNo;
   //Static Variable
   static String school="Don Bosco High School";
   //Parameterized Constructor  
   Students(String n,String c, String s, int rn){  
    name=n;
    clas=c;
    sec=s;
    rollNo=rn;
   }  
   
   //method to display the values  
   void display (){System.out.println(name+" "+clas+" "+sec+" "+rollNo+" "+school);}  
   
   //Static Method to change the static member
   static void setSchoolName(String newName)
   {
       school = newName;
   }
}  
 
public class School{  
 public static void main(String args[]){  
     
 System.out.println("School is a class member. Can be accessed by Class Name also.\nSchool Name:"+Students.school+"\n");
 
 Students obj1 = new Students("Gourav Gupta","XII","C",7); 
 Students obj2 = new Students("Madhurav Prasad","XI","A",25);
 obj1.display();  
 obj2.display();  
 
 Students.setSchoolName("St. Mary High School");
  System.out.println("\n\nSchool name is changed.\nSchool Name:"+Students.school+"\n");
 obj1.display();  
 obj2.display();  
 }  
}  

Output:

School is a class member. Can be accessed by Class Name also.
School Name:Don Bosco High School

Gourav Gupta XII C 7 Don Bosco High School
Madhurav Prasad XI A 25 Don Bosco High School


School name is changed.
School Name:St. Mary High School

Gourav Gupta XII C 7 St. Mary High School
Madhurav Prasad XI A 25 St. Mary High School

Java Static Block

The static block is an anonymous block enclosed by{} and preceded with the keyword static. It is used to initialize static attributes. In order of execution, the static block is executed before the main method during class loading. Note, that it is simply executed earlier and cannot be an alternative to the main method.

Example:

public class School{  
    static int val;
 static{
     System.out.println("I am inside static block");
     val=25;
 }
 public static void main(String args[]){  
     System.out.println("I am inside main block");
     System.out.println("Static variable val = "+School.val);
}
}  

Output:

I am inside static block
I am inside main block
Static variable val = 25

We can see that the static block has been executed earlier than the main method.


Java this Keyword

this keyword is a reference variable that refers to the current object. Anywhere inside the definition of class, it can be used as an individual, and in association with variables, methods, and constructor. The intent of this is to provide an extra layer of specification and clarity in case the same name is used to avoid any confusion.

this with variables

Here, we have a situation where this was needed but we did not use it. As a result, the output is incorrect

Example: 

class MyClass{
  int param1;
  int param2;
  //Parameterized Constructor
  //Here, both the parameter and instance variable has same name
  MyClass(int param1,int param2)
  {
      param1 = param1;   //compiler doesn't assign, but only evaluate
      param2 = param2;   //compiler doesn't assign, but only evaluate   
  }
}
public class ClassWithMain{  
 public static void main(String args[]){  
   MyClass obj = new MyClass(5,6); //This has no impact on values of param1 and param2
   System.out.println(obj.param1+" "+obj.param2);
}
} 

 Output:

0 0

So we can see that the constructor dint perform initialization. Upon usage of this, let us see what difference does it make.

class MyClass{
  int param1;
  int param2;
  //Parameterized Constructor
  //Here, both the parameter and instance variable has same name
  //Using this.variable name specifies that it is an instance variable, not the input parameter
  MyClass(int param1,int param2)
  {
      this.param1 = param1;   
      this.param2 = param2;      
  }
}
public class ClassWithMain{  
 public static void main(String args[]){  
   MyClass obj = new MyClass(5,6); //This has impact on values of param1 and param2 because of this keyword
   System.out.println(obj.param1+" "+obj.param2);
}
} 

Output:

5 6

Constructor invocation using this

this is used to call one version of the constructor from another. This helps in configuring the chain of constructor calls. It is by convention to use this as the first statement of the constructor. 

Example:

class MyClass{
  int param1;
  int param2;
  //Parameterized Constructor
  //Here, both the parameter and instance variable has same name
  //Using this.variable name specifies that it is an instance variable, not the input parameter
   MyClass(int param1)
  {
      System.out.println("I am inside Constructor 1");
      this.param1 = param1;   
  }
  
  MyClass(int param1,int param2)
  {
      //It signifies that constructor version with only 1 input parameter is to be executed first
      this(param1);  
      System.out.println("I am inside Constructor 2");
      this.param2 = param2;      
  }
  
}
public class ClassWithMain{  
 public static void main(String args[]){  
   MyClass obj = new MyClass(5,6); //This has impact on values of param1 and param2 because of this keyword
   System.out.println(obj.param1+" "+obj.param2);
}
} 

Output:

I am inside Constructor 1
I am inside Constructor 2
5 6

This was an overview of static and this keyword. We will be discussing Java Inheritance in the next lecture.