Static Variables, Methods, Block, and Classes in Java

Pasan Kamburugamuwa
7 min readNov 9, 2021

When you face a Java interview, there most probably interviewer will ask about static keyword and their usages. Not for the interviews, you need to have a better understanding of static variables, methods, blocks, and classes when comes to Java program development as we need to stick to best practices. So in this tutorial, I will go through some examples of using static keywords in Java.

Where do the static members belong to?

The static members belong to the class instead of the object. So if you make an object, you do not need to create an instance of that and call the static method. You can access this without referring to the instance.

In other meaning, this static is a keyword in java that is used to share some variable or method of a given class. Basically, static is used for a constant variable or a method that is the same for every instance of a class. The main method of a class is generally labeled static.

Static Keyword

This is used mainly on memory management. The static keyword belongs to a class rather than an instance of the class.

We can use static keywords in the following instances,

1. As a method

2. As a variable

3. Block

4. Nested classes

To create these static members, you need to precede its declaration with the keyword static. So using this, you can access the member, before the objects of the class are created.

So let’s have a look into these static keyword instance types.

Static Variable

You can define a static variable using the static keyword before the variable. The static variable can be used to refer to an object’s common attribute and this is taking only once of the memory at the time of loading the class.

Static variable example.

package com.example;

public class Main {

// the averangeStudentMarks variable is a private and static variable
private static double averangeStudentMarks;

// Grade is a constant
public static final String GRADE = "Grade A ";

public static void main(String args[]) {
averangeStudentMarks = 75;
System.out.println(GRADE + "average student mark is " + averangeStudentMarks);
}
}

The output of the above program is given below.

By using the static variables, your program will become more memory efficient as this leads to saving the memory.

Summary of static variable

  1. Only a single copy of the static variable is created and shared among all the instances of the class. When the class is loaded into memory, memory allocation for static variables occurs just once.
  2. This variable can also be called class variables.
  3. Static variables can be accessed directly in static and non-static methods.

Static Block

This is also can be named a static initialization block. Inside the static block, there is a set of instructions that run only once when a class is loaded into memory.

You can imagine this static block as a class constructor because this only executes when the class is loaded. Static initialization blocks can be anywhere in the body of a class and can have any number of them. Static initialization blocks are called in the order they appear in the source code, as guaranteed by the runtime system.

Static block example.

package com.example;

public class Main {

//static block
//static block is used to initialize static data member of the class at the time of class loading
//static block is executed before the main
static
{
System.out.println("Welcome to Java - Static Block");
}

public static void main(String[] args) {
System.out.println("Executing this after static block");
}
}

The output of the above program is given below.

As from the above example, the code inside the static block executes before the main method of the program.

usages of the static block

  1. They can be used to set up static resources in other ways, such as making sure other classes have been loaded (such as JDBC drivers or any other SPI implementation class) or reading in a properties file associated with the class.
  2. They can be used to build up any static fields that are too complex to put up with a single-line declaration. For example, where there is a multi-step process to follow, and the value of a static field is determined by something else.
  3. By using static block, you don’t need to worry about which constructor calling first as this static block guarantees which happens first.

Summary of the static block

  • Is used to initialize the static data member.
  • It is executed before the main method at the time of class loading.

Static Methods

By using static methods, you do not need to create objects with the class. You can access the class variables without using objects of the class and it belongs to the class and not to the object. These static methods can access only static data and cannot access non-static data.

Things to remember when using static methods.

  1. You do not need to create an object and you can access the method directly by the class name.
  2. This static method can call only the static methods.

Why is the main method in the java program static?

By defining the main method as static, the compiler can call it without the creation of an object or before the creation of an object of the class.

So let’s have a real-world example of using static methods in a program.

package com.example;

public class Main{
public static void main(String args[]){
//As the static methods belong to class level,
//you can call the static methods with class name.
Student.showData();
}
}

class Student {
//Initializing the static variable to hundred
//This is used only in the class loading and not for each object creating.
static int staticVariable=100;

public static void showData(){
//static methods can only access the static data
System.out.println("Value of b = "+staticVariable);
}
}

The output of the above program is given below.

Things to remember when creating static methods,

  • Instance fields/methods can only be accessed through an instance
  • Static fields/methods can be accessed without an instance
  • Can not override the method definition.
  • Can not use any instance variables and the code also does not depend on instance creation.

Java static nested class

Static classes can be created inside a class and these static classes can not access non-static data members and methods. It only can be accessed from the outer class name.

Example of java static nested class.

package com.example;

public class Main{
static int data=100;
static class InnerStaticClass{
void printData(){System.out.println("Data is "+data);}
}
public static void main(String args[]){
Main.InnerStaticClass obj=new Main.InnerStaticClass();
obj.printData();
}
}

The output of the above program is given below.

In the above example, you need to create the instance of static nested class because it has an instance method printData(). But in here, you do not need to create the object of the Outer class Main as the nested class is static and also it has static methods which only access the static variables.

Usage of Static nested class in java

  • This provides a more readable and maintainable code because we can place the code in one place.
  • The static class(nested class) increases the encapsulation. Suppose we have two classes that are OuterClass and InnerClass. The InnerClass can access the members of OuterClass even they are private members. By hiding InnerClass within OuterClass, In OuterClass We can declared private member and InnerClass can access them.
  • We can achieve a logical grouping of classes by using static nested classes. It simply means that if a class is only helpful for one other class, we can include it in that class and keep the two together.

Summary of Static nested class

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

In this article, we discussed Static Variables, Methods, Block, and Classes in Java with some examples of code and also with their usages. The static keyword is really helpful in java program programming as it helps to write better code with readability and also with efficient memory management. Hope you understand the tutorial well and will see you in the next tutorial. Until then bye.

--

--