Static keyword in Java
0% completed
Static keyword in java
Locality of Reference
Is Accessible from Static Block?
Locality of Reference II
Static Method
Basics Of Java
Static keyword in java

 

Static Keyword in Java

footer line

Static Keyword

 

The static keyword in Java is mostly used for memory management. Static keywords can be used for variables, methods, blocks, and nested classes.

 

Static fields or class variables are fields that have the static modifier in their declaration. They are associated with the class rather than any specific object. Every instance of the class has the same class variable, which is stored in a single fixed location in memory. A class variable's value can be changed by any object, but class variables can also be modified without making an instance of the class. 

 

 

Static Block in Java

 

There might be a situation where we need to compute something to initialize our static variables. For this, we can declare a static block that is executed only once when the class is first loaded.

 

Example:

 

public class StaticBlockExample
{ 
	// Static variables
	static int a = 10; 
	static int b; 

	// Static block 
	static { 
		System.out.println("Static Block Initialized"); 
		b = a * 4; 
	} 

	public static void main(String[] args) 
	{
		       System.out.println("Inside Main Method"); 
		       System.out.println("Value of a : "+a); 
		       System.out.println("Value of b : "+b); 
	} 
	
} 


Output:

 

Static Block Initialized
Inside Main Method
Value of a : 10
Value of b : 40

 

 

Static Variable in Java

 

When a variable is declared static, a single copy of the variable is created and shared by all objects at the class level. Static variables can only be created at the class level. Memory allocation for such variables occurs only once when the class is loaded into memory. 

 

Example:

 

public class StaticVariableExample 
{ 
	// Static variable 
	static int a = fun(); 

	// Static block 
	static { 
		System.out.println("Inside Static Block"); 
	} 

	// Static Method 
	static int fun() { 
		System.out.println("Inside fun() Function"); 
		return 10; 
	} 

	public static void main(String args[]) 
	{ 
		System.out.println("Value of a : "+a); 
		System.out.println("Inside Main"); 
	}
	
} 


 Output:

 

Inside fun() Function
Inside Static Block
Value of a : 10
Inside Main

 

 

Static Method in Java

 

When a method is declared with the static keyword, it is referred to as a static method. A static method is a class member rather than a class object. A static method can be called without first creating a class instance. The static method cannot refer to 'this' or 'super' in any way.

 

Example:

 

public class StaticMethodExample 
{ 
    // Static method
	public static void add(int a, int b) {
		int sum = a + b;
		System.out.println(sum);
	}

	public static void main(String args[]) 
	{  
  		// Calling static method without creating an object
  		add(10, 20);
	} 
	
} 

 

Output:

 

30