Static variable, method and block in java

In this post, we will see Static variable, method and block in java. For beginners static keyword is a little confusing, so we will see where we can use static and what will be impact. Also, we will see in real time scenario how static is helpful.  Always remember static variable, method and block will be associated with the class.  So let’s start.

Static variable, method and block in java

Here We will see –

  1. Where we can use static in java.
  2. Static variable in java.
  3. Static block in java.
  4. Static method in java.
  5. Static class(only in case of inner class).
  6. Predefined API using static keyword in java.
  7. How to use static variable, method and block in real time project.

 

Where we can use static keyword in java?

Static keyword can be used with –

  1. variable
  2. method
  3. block
  4. class(Only in case of inner class)

 

Explain Static variable in java ?

  1. When we define any variable as static in class, It is called a static variable.
  2. We can access a static variable using class name directly, no need to create an object.
  3. A static variable can be accessed inside the instance or local context(Since memory allocation happens at class loading time so it will be available for whole application) but we can’t access instance variable in static context.
  4. Memory allocation for the static variable will happen only once at class loading.

 

Example 1 –

public class StaticVariableExample {

	static int a = 10; // static variable

	public static void main(final String[] args) {
		System.out.println(a);
	}
}

The output is – 10

 

Example 2 –

public class StaticVariableExample {

	static int a = 10;

	public static void main(final String[] args) {
		System.out.println(StaticVariableExample.a);// we can access static variable with class name 

	}
}

The output is – 10

 

Example 3 –

public class StaticVariableExample {

	static int a = 10;

	public void test() {
		System.out.println(a); // we can access static variable in instance
		// context
	}

	{
		System.out.println(a); // we can access static variable in instance
		// context
	}

	public static void main(final String[] args) {
		System.out.println(StaticVariableExample.a);// we can access static
		// variable with class name

		StaticVariableExample example = new StaticVariableExample();

		example.test();

	}
}

Output is – 10, 10,10

 

Explain static block in java?

  1. The static block will get executed only once during class loading.
  2. if we want to perform some action only one time for the whole application, we put that logic inside a static block.
  3. It will get invoked before constructor or instance block.
public class StaticBlockExample1 {
	static {
		System.out.println("static block");
	}

	public static void main(final String[] args) {

	}
}

The output is – static block

 

Explain Static method in java?

  1. We define static method with static keyword.
  2. We can call a static method with class name no need to create an object.

Let’s see an example of the static method –

public class StaticMethodExample {

	public static void test() {
		System.out.println("This is a static method");
	}

	public static void main(String[] args) {
		StaticMethodExample.test();
	}
}

The output is – This is a static method

 

Explain Static class(only in case of inner class). 

  1. We can define a class as static in case of the only inner class, if we try to make a normal class as static it will show compile time error.
public class StaticClass {

	static class StaticInnerClassExp {
		public void test() {
			System.out
			.println("this is a satic method inside static inner calss");
		}
	}

	public static void main(String[] args) {
		StaticClass.StaticInnerClassExp inner = new StaticClass.StaticInnerClassExp();
		inner.test();

	}
}

Output is – this is a satic method inside static inner class

 

Tell some predefined API where it has been used static keyword in java?

Here we will see a couple of predefined static variable which is already defined in java –

  1. out – When we do System.out.println(), out is static reference variable defined in System class, type of PrintStream.
  2. public final static PrintStream out = null;
    public final static PrintStream err = null;
    private static volatile SecurityManager security = null;

 

Here we will see couple of predefined static block which has been already defined in java –

In System class we can see use of static block as below.

public final class System {

   
    private static native void registerNatives();

    static {

        registerNatives();

    }
}

The predefined static method which has been already defined in java –

There is a lot of predefined methods which has been defined as static in java.

 //1.  this static method is defined in Runtime class
 public static Runtime getRuntime() {
        return currentRuntime;
 }

 //2. this one is also defined in Runtime class

public static void runFinalizersOnExit(boolean value) {
        SecurityManager security = System.getSecurityManager();
        
    }

 

 

Real time use of static variable , static method and static block. 

Real-time use of static variable  – 

  1. we can use a static variable as constant in java. Suppose you have to compare two String and if both are equal then you want to perform some operation. For example, we have three POJO class Employee.java and ContractEmployee.java and PermanentEmployee.java . There is a variable employeeType defined in Employee.java class, we want if employeeType is Contract then salary should credit 3rd of every month and if employeeType is Permanent, salary should credit 30th of every month.

Let’s see a program without a static variable –

class Employee {
	String employeeType;

	public String getEmployeeType() {
		return employeeType;
	}

	public void setEmployeeType(String employeeType) {
		this.employeeType = employeeType;
	}

}

class ContractEmployee extends Employee {

}

class PermanentEmployee extends Employee {

}

public class StaticVariableExample {

	public static void main(final String[] args) {
		Employee e = new Employee();
		e.setEmployeeType("CNT");// we are doing hard code. It should come from DB.

		if (e.getEmployeeType().equals("CNT")) { // this will always true just for understanding.
			System.out.println("salary should credit 3rd of every month");
		}

		if (e.getEmployeeType().equals("PNT")) { 

			System.out.println("salary should credit 30th of every month");
		}
	}
}

 

Here we have defined CNT and PND in double code. This code will work fine, but this is not a good coding practice.

Let’s see how to use a static variable for the same scenario –

We will have a separate class where we will have all static variables(constants) something like in the below example.

We have YourApplicationConstants.java class where we will have a static variable as constant.

package variablesinjava;

public class YourApplicationConstants {
	public static final String PERMANENT = "PNT";
	public static final String CONTRACT = "CNT";
	// can be n numbers of constants.
}

Observe the modification in Employee.java

package variablesinjava;

class Employee {
	String employeeType;

	public String getEmployeeType() {
		return employeeType;
	}

	public void setEmployeeType(String employeeType) {
		this.employeeType = employeeType;
	}

}

class ContractEmployee extends Employee {

}

class PermanentEmployee extends Employee {

}

public class StaticVariableExample {

	public static void main(final String[] args) {
		Employee e = new Employee();

		// we are doing hard code. It should come from DB.
		e.setEmployeeType(YourApplicationConstants.CONTRACT);

		// this will always true just for understanding.
		if (e.getEmployeeType().equals(YourApplicationConstants.CONTRACT)) {

			System.out.println("salary should credit 3rd of every month");
		}

		if (e.getEmployeeType().equals(YourApplicationConstants.PERMANENT)) {
			System.out.println("salary should credit 30th of every month");
		}
	}
}

[stextbox id=’info’]Sometime people like  define constant in interface. In interface we no need to write public static final explicitly, as we know all variable by default public static final in interface or we can say interface can have only constants.[/stextbox]

 

Real time use of static block- 

Suppose you want to set DateTimeZone for the entire application.

package staticblockexample;

public class StaticBlockRealTimeExample {

	// 1. first scenario
	static {
		// you might want to set timezone to UTC format for whole application
		// here DateTimeZone class is joda api
		DateTimeZone.setDefault(DateTimeZone.UTC);

	}
	
	public static void main(final String[] args) {

	}

}

For more details where to use static block please visit this post.

 

Real time use of static method – 

Suppose we want to define util class, all method we can define static and we can call through class name.

public class StaticMethodExample {

	public static boolean isEmpty(String s1) {
		if (s1 == null || s1.length() == 0) {
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		System.out.println(StaticMethodExample.isEmpty("ram"));
	}

}

The output is – false

That’s all about Static variable, method and block in java.

You may like.

See docs here.