Demystifying 'static' Keyword in Java | Interview Questions | Interview Q Point

The static keyword means that something (a field, method or nested class) is related to the type / class rather than any particular instance of the type. In Java, static keyword can be used with variable, method, blocks and nested class. It is mainly used for utilizing memory efficiently (to save memory). 


i.) Static Variable: We use static keywords for properties which are not unique for each object. These properties are common for all objects. 

Example: College name of students, Company name.


These static variable gets memory only once in the class area at the time of class loading.


class Employee {

	long id;
	String name;
	static String companyName; //  static variable

}


ii.) Static Method: static method are those methods which belongs to class rather object of that class. We don't need to create any instance in order to invoke the static method.


class Square{  
  static int area(int side){  
  return side * side;  
  }  
  
  public static void main(String args[]){  
  int result=Square.area(5);  
  System.out.println(result);  
  }  
}

//output:
125


There are few restrictions that we need to remember while using static methods

a) We cannot use non static data member or call non-static method directly from a static mentod.

b) this and super cannot be used in static context.

c) We cannot override static method.



iii.)   Static Block: Static block is a block of code inside Java program which is used for initializing static data members. The code inside the static block is executed only once e.i., the first time the class is loaded into memory. 


class Test {
   
	static int a;
	static int b;
	static {
		a = 10;
		b = 20;
	}
	public static void main(String args[]) {

		System.out.println("Value of a = " + a);
		System.out.println("Value of b = " + b);

 	}
}

// Output
Value of a = 10
Value of b = 20


iv.) Static Class: A class can be declared static only if it is a nested class. The property of the static class is that it does not allows us to access the non-static members of the outer class.


An instance of the static nested class can be created without creating an instance of its outer class.

The static members of the outer class can be accessed only by the static class.


Example:

public class Test { 
  class A { } 
  static class B { }
  
  public static void main(String[] args) { 
    
	/*will fail - compilation error, you need an instance of Test to instantiate A*/
        A a = new A(); 
    
	/*will compile successfully, not instance of Test is needed to instantiate B */
        B b = new B(); 
  }
}


InterviewFlix - Static Keyword in Java



Checkout similar posts:

Demystifying 'final' Keyword in Java 

Top Java Interview Questions - InterviewFlix



Post a Comment

0 Comments