Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Jul 9, 2024
Easy

Static Keyword In Java

Author
0 upvote
Table of contents
Learn to use AI Tools & ChatGPT to excel as Microsoft SDE
11 Jul, 2024 @ 01:30 PM
Speaker
Pranav Malik
SDE 2 @

Introduction

Keywords are reserved terms in Java that cannot be used as identifiers. Java language has 57 keywords, and the static keyword in Java is one of them. 

In Java, we first make an instance of the class to access its members. However, there will be times when we will need to access class members without using variables. In these cases, the static keyword in Java can be used. We must declare class members static if we need to access them without creating an instance of the class.

What Is A Static Keyword In Java?

What is Static Keyword In Java?

In Java, the static keyword is mainly used for memory management. It is a non-access modifier. It can be used with methods, variables, blocks, and nested classes. It is associated with the class rather than an instance of the class or object of a class.

In Java, the members of the Math class are static. As a result, we can access its members without having to create Math instances.

As an example: 
 

  • Java

Java

public class Main {
public static void main( String[] args ) {

// accessing the methods in java of Math class
System.out.println("The value of pi = " + Math.PI);
System.out.println("3^3 = " + Math.pow(3,3));

}
}

Output:

The value of pi = 3.141592653589793
3^3 = 27.0

In the above example, we haven’t created any instances of the Math class. Still, we can access its variable- PI and method- pow() as the variables and methods of math class are static.

Static Keyword in Java is used in the following ways:

  • Static Variables
  • Static Methods
  • Static Block
  • Static Nested Classes

Let’s look at each of these types in more depth to understand the use of a Static Keyword in Java.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Static Variables

Static Variables in Java are also known as class variables. Any variable declared with the static keyword is referred to as a static variable. The static keyword in java denotes a variable that refers to a common attribute shared by all of the class objects.

For example, the school name is the same for its students, workers, faculty, etc. Hence, only one copy of the static variable is shared by all instances of the class. Static variables can be accessed directly from both static and non-static methods.

Let’s see how to declare static variables in Java through:

class Student{
    // Declaration of static variable
    static int age;
}
class Main {
    // Accessing the static variable
    Student.age = 16;
}

Here, we are accessing the static variable from the other class using its class name.

Example using Static Variable:
 

  • Java

Java

class Result {

// static variable
static int maxvalue = 20;

// non-static variable
int minvalue = 10;
}

public class Main {
public static void main(String[] args) {
Result obj = new Result();

// access the non-static variable
System.out.println("minvalue + 1 = " + (obj.minvalue + 1));

// access the static variable
System.out.println("maxvalue + 1 = " + (Result.maxvalue + 1));
}
}

Output:

minvalue + 1 = 11
maxvalue + 1 = 21

In the above example, a non-static variable named minvalue and a static variable named maxvalue is declared inside the class Result. In the Main class, we call the non-static variable by using the object of the class (obj.minvalue + 1). However, we call the static variable using the class name (Result.maxvalue + 1).

Static Methods

Methods specified with the static keyword are known as static methods.

  • When a method is declared static, we can call or access it without creating an object or instance of the class.
  • A static method can access and alter the value of a static data member.
  • We know that to use non-static methods, we need first to construct the class object and then call the method through the object, but we can call static methods directly with the class name, unlike non-static methods.

Example of Static Methods

class Example {
    // static method inside the class
    public static void method() {...}
}

class Main {
    // invoking the static method
    Example.method();
}

The static function can be accessed directly from other classes using the class name, as seen above.

Note: The main method is always static in Java so that the compiler can call it before creating an object or without creating an object of a given class. As in Java, the compiler starts executing a program by considering the main method as its starting point. 

Example using Static Methods:
 

  • Java

Java

class Test {

// non-static method
int add (int a, int b){
return a + b;
}

// static method
static int multiply(int a, int b){
return a * b;
}
}

public class Main {

public static void main( String[] args ) {

// create an instance of the Test class
Test T = new Test();

// call the nons-tatic method
System.out.println(" 4 + 5 = " + T.add(4,5));

// call the static method
System.out.println(" 4 * 5 = " + Test.multiply(4,5));
}
}

Output:

4 + 5 = 9
 4 * 5 = 20

In the above example, a non-static method named add() and a static method named multiply() is declared inside the class Test. Inside the Main class, we are calling the non-static method by using the object of the class (T.add(4,5)). However, we are calling the static method using the name of the class (Test. multiply(4,5)).

Compelling Reasons to Use static Methods

Static methods in programming languages offer several benefits:

  • Utility and Convenience: Static methods can be called directly on the class without needing to instantiate an object. This is useful for utility classes where object instantiation is unnecessary.
  • Performance: Since static methods belong to the class rather than instances, they can be more efficient in terms of memory and processing overhead.
  • Namespace Organization: Static methods help organize code logically within a class, especially when methods are closely related but don't require instance-specific data.
  • Simplicity: They can simplify code by eliminating the need to manage object states when the method doesn't rely on instance variables.
  • Global Access: They provide a way to create globally accessible methods that are associated with a class, making them accessible from anywhere in the codebase.

Static Block

Static Blocks are used to initialize the static data members or static variables. It is executed only once before the main function when the class is loaded. If the object of the class or the static members of the class is requested in code, the class is loaded.

A class can have multiple numbers of static blocks, and each of the static blocks is executed in the same manner in which they have been coded in the program.

Example of Static Block

class Student{

    // Declaring static variable
    static int age;

    // Declaring static block
    static {
        age = 20;
    }
}

Example using static blocks:
 

  • Java

Java

class Student {

// static variables
static int age = 20;
static int x;
static int maxvalue;

// static blocks
static {
System.out.println("Static block one");
x = age * 2;
}
static {
System.out.println("Static block two");
maxvalue = 50;
}

// static method
static void show() {

System.out.println("age = " + age);
System.out.println("x = " + x);
System.out.println("maxvalue = " + maxvalue);
}

public static void main(String args[]) {
// calling the static method
show();
}
}

Output:

Static block one
Static block two
age =  20
x = 40
maxvalue = 50

In the above example, as soon as the Main class gets loaded, the code runs in the following manner:

  • Firstly, the value of age is set to 20.
  • The static block one is executed. Hence, the string Static block one is printed, and x is set to age * 2.
  • The static block two is executed. Hence, the string Static block two is printed, and maxvalue is set to 50.
  • Finally, the statements inside the method show() are executed.

Compelling Reasons to Use static Block

In Java and similar languages, a static block is a special block of code within a class that runs only once when the class is loaded into memory by the class loader. Here are some reasons why static blocks are useful:

  • Initialization: static blocks are used for initializing static variables of a class. This is particularly useful when initialization requires complex logic or when values need to be computed before the class is used.
  • Exception Handling: They allow handling of exceptions during class initialization. This is crucial because exceptions thrown during static initialization can't be caught in the usual way, so using a static block provides a way to handle such scenarios.
  • Order of Execution: static blocks execute in the order they appear in the code, ensuring predictable initialization of static members.
  • No Object Creation Required: Unlike instance initialization blocks ({ ... }), static blocks do not require an object to be instantiated. This makes them suitable for initializing static members without creating unnecessary objects.
  • Flexibility: They provide flexibility in initializing static variables based on different conditions or configurations.

Static Nested Class

We can define a class as static; however, the class must be a nested class only i.e., the class must be present within another class before we can declare it as static. The object of the outer class is not required by the nested static class. Another limitation of the nested static class is that it cannot access the outer class’s non-static data members. 

Example of Static Nested Class

  • Java

Java

class Car {

// static nested class
static class Tyre{
int tyre1 = 3;
int tyre2 = 4;

int Total_Tyres(){
return tyre1 + tyre2;
}
}

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

// create an object of the nested static class
// using the name of the outer class
,
Car.Tyre T = new Car.Tyre();
System.out.println("Total Tyres = " + T.Total_Tyres());
}
}

Output:

Total Tyres =  7

In the above example, we created a static class named Tyre inside the class Car. In the line,  Car.Tyre T = new Car.Tyre();   we are creating an object T using the name of the outer class.

Compelling Reasons to Use Static Nested Class

Static nested classes in Java and similar languages offer several advantages and use cases:

  • Namespace Control: They allow you to logically group classes that are only used in one place, thereby encapsulating them and preventing them from polluting the namespace.
  • Access Control: Static nested classes can access private members of the outer class, which can be useful for design patterns like the builder pattern, where the nested class needs access to the private state of the outer class.
  • Code Organization: They improve code organization by keeping related classes together and making the code more readable and maintainable.
  • Encapsulation: Static nested classes can be used to logically group classes that have no need to access instance variables of the outer class, promoting encapsulation.
  • Helper Classes: They are often used as helper classes that are closely related to the outer class, providing utility functions or data structures specific to that class.

Frequently Asked Questions

What is a static and non-static keyword in Java?

Static keywords in Java use compile-time binding whereas non-static keywords use run-time or dynamic binding.

What are static methods?

Static methods can access class variables (static variables) without needing a class object (instance), whereas non-static methods and variables can only be accessed via objects.

What is the difference between static and non-static variables?

Static variables are used by all instances of a class, whereas non-static methods are only specific to the particular instance of a class.

Conclusion

In Java, the static keyword serves multiple crucial roles when applied to variables, methods, blocks, and nested classes within a class structure. Primarily, its use is geared towards optimizing memory utilization. A static variable is shared across all instances of its class, ensuring consistency in its value across objects. Static methods leverage this by directly accessing static variables without requiring an object instantiation, thereby streamlining code execution and promoting efficiency. Additionally, static blocks are executed once during the class loading process by the Java Virtual Machine, making them ideal for initializing static variables or handling exceptions early in program execution.