Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

What is the static keyword in Java and how to use?

Last Updated on August 3, 2023 by Mayank Dham

The static keyword in Java serves primarily for memory management purposes. It is utilized to enable the sharing of variables or methods among multiple instances of a class. The static keyword can be applied to variables, methods, blocks, and nested classes. It signifies that a member belongs to the class itself, rather than being specific to any particular instance. It is commonly used for defining constant variables or methods that remain the same for every instance of a class.

In Java, the static keyword is a non-access modifier that can be applied to the following

  • Blocks
  • Variables
  • Methods
  • Classes

Characteristic of Static Keyword in Java

The static keyword in Java possesses the following characteristics:

  • Shared Memory: Static members, such as variables and methods, are associated with the class itself rather than individual instances of the class. They are stored in shared memory and can be accessed by all instances of the class.
  • Single Instance: Static members are initialized only once, usually when the class is loaded into memory. This ensures that there is only a single instance of the static member, regardless of how many instances of the class are created.
  • Class-level Access: Since static members belong to the class, they can be accessed using the class name directly, without the need for an instance of the class.
  • Limited Access to Instance Members: Static members have limited access to instance members (non-static members). They cannot directly access instance variables or methods, as they are not associated with any specific instance of the class.
  • Memory Efficiency: By using static members, memory can be optimized as these members are shared among instances. Instead of creating separate copies for each instance, all instances can refer to the same static member.
  • Global Accessibility: Static members can be accessed from any part of the program, provided they have appropriate access modifiers (e.g., public, protected, or private) to determine their visibility.
  • Initialization Order: Static members are initialized in the order they are declared in the class. Static blocks, if present, are executed when the class is loaded, ensuring proper initialization before any other operations are performed.

Example of Static Keyword in Java

By declaring a member as static in Java, it becomes accessible even before any objects of its class are instantiated, and without the need for a reference to any object. To illustrate, consider the following Java program where we access the static method m1() without creating an object of the Test class:’

class Test {
    static void m1() {
        System.out.println("Static method m1() called.");
    }
}

public class Main {
    public static void main(String[] args) {
        Test.m1(); // Accessing static method without object creation
    }
}

Explanation of the above example
In the above example, the static method m1() can be directly accessed using the class name Test followed by the method name m1(), without the need to create an object of the Test class. This feature allows for the invocation of static members independently, without relying on any specific object instance.

What are Static Blocks?

To perform computations for initializing static variables in Java, you can utilize a static block, which executes only once when the class is initially loaded. The following Java program illustrates the usage of static blocks:

class Example {
    static int number;

    static {
        // Computation to initialize static variable
        int sum = 0;
        for (int i = 1; i <= 10; i++) {
            sum += i;
        }
        number = sum;
        System.out.println("Static block executed.");
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Static variable value: " + Example.number);
    }
}

Explanation of the above example:
In the above example, a static block is defined using the static keyword and enclosed in curly braces. Within the static block, computations are performed to initialize the static variable number. In this case, the block calculates the sum of numbers from 1 to 10 and assigns the result to number. The static block also includes a print statement to indicate that it has been executed.

When the Main class is run, the static block is executed once, before the main method, ensuring that the static variable number is initialized with the desired value. The program then prints the value of the static variable, demonstrating the successful initialization through the static block.

What are static variables?

By declaring a variable as static in Java, a single copy of the variable is created and shared among all objects at the class level. In essence, static variables can be considered as global variables within the scope of the class. This means that all instances of the class share the same static variable.

The following Java program showcases that static blocks and static variables are executed in the order they appear in the program:

class Example {
    static int number1 = initializeNumber1();
    static int number2 = initializeNumber2();

    static {
        System.out.println("Static block 1 executed.");
    }

    static {
        System.out.println("Static block 2 executed.");
    }

    static int initializeNumber1() {
        System.out.println("Initializing number1.");
        return 10;
    }

    static int initializeNumber2() {
        System.out.println("Initializing number2.");
        return 20;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Number1: " + Example.number1);
        System.out.println("Number2: " + Example.number2);
    }
}

What are static Methods?

When a method is declared with the static keyword, it is referred to as a static method. The main() method is a commonly encountered example of a static method. As mentioned earlier, any static member can be accessed prior to the creation of any objects of its class and without requiring a reference to an object. However, methods declared as static come with several restrictions:

Here is a Java program that demonstrates the restrictions on static methods:
class Example {
static int number = 10;

    // Static method
    static void staticMethod() {
        System.out.println("Static method called.");
        // Cannot directly access non-static members
        // System.out.println("Number: " + number); // Compilation error
    }

    // Non-static method
    void nonStaticMethod() {
        System.out.println("Non-static method called.");
        // Can access static members directly
        System.out.println("Number: " + number);
    }
}

public class Main {
    public static void main(String[] args) {
        Example.staticMethod(); // Calling static method

        Example obj = new Example();
        obj.nonStaticMethod(); // Calling non-static method
    }
}

Explanation of the above code
In the above example, the class Example contains a static variable number and two methods: staticMethod() and nonStaticMethod().

The staticMethod() is a static method and can be called directly using the class name (Example.staticMethod()). However, within the static method, it is not possible to directly access non-static members (like number in this case) as it results in a compilation error.

On the other hand, the nonStaticMethod() is a non-static method and requires an instance of the class (Example obj = new Example()) to be called. Within the non-static method, both static and non-static members can be accessed directly.

By running the Main class, you can observe the behavior and restrictions of static and non-static methods.

What are Static classes?

A class can only be declared as static if it is a nested class. It is not possible to declare a top-level class with the static modifier, but nested classes can be declared as static. These types of classes are referred to as nested static classes. Unlike regular nested classes, a nested static class does not require a reference to the outer class. However, it is important to note that a static class cannot access non-static members of the outer class.

// A java program to demonstrate use
// of static keyword with Classes

import java.io.*;

public class PB {

private static String str = "PrepBytes";

// Static class
static class MyNestedClass {

    // non-static method
    public void disp(){
    System.out.println(str);
    }
}

public static void main(String args[])
{
    PB.MyNestedClass obj
        = new PB.MyNestedClass();
    obj.disp();
}
}

Advantages of Static Keyword in Java

The static keyword in Java offers several advantages, which include:

  • Shared Memory Efficiency: When a variable or method is declared as static, it is shared among all instances of the class. This results in memory efficiency as only one copy of the static member is created and shared.
  • Global Accessibility: Static members can be accessed from any part of the program, irrespective of whether an object of the class has been instantiated or not. This allows for convenient access to commonly used variables or methods without the need for object references.
  • Utility Methods: Static methods are commonly used for utility operations or functions that do not require any specific instance data. These methods can be called directly using the class name, making them easily accessible and reducing the need for unnecessary object creation.
  • Constants: Static variables can be used to declare constants in Java. By using the final modifier along with the static keyword, a variable can be made constant throughout the program, providing a convenient and centralized way to define and use constants.
  • Initialization Control: Static blocks can be used to perform one-time initialization tasks for static variables or other operations when the class is loaded into memory. This allows for precise control over initialization and ensures consistent behavior across all instances.
  • Namespace Organization: Static members can be used to organize and group related functionality within a class. By placing related methods or variables as static members, it can provide a clear and logical structure to the codebase.
  • Enhanced Performance: In certain scenarios, using static methods or variables can improve performance. Since static members are associated with the class itself, rather than an instance, they can be accessed more quickly, resulting in potential performance optimizations.

Conclusion
The static keyword in Java is a powerful tool for memory management, global accessibility, and organizing code. It allows for the creation of shared variables and methods at the class level, enabling efficient memory usage and easy access without the need for object references. Static members can be used for utility methods, constants, initialization control, and namespace organization. However, it is essential to understand the limitations and considerations of using static members, such as restricted access to non-static members and potential implications on object-oriented principles.

FAQs related to the static keyword in Java:

1. Can a static method access non-static variables?
No, a static method cannot directly access non-static (instance) variables. It can only access other static variables or methods.

2. Can a static method be overridden?
No, static methods cannot be overridden in Java. They are associated with the class itself and not with individual instances, so there is no concept of dynamic method dispatch for static methods.

3. Can a static variable be modified by multiple threads concurrently?
Yes, static variables can be accessed and modified by multiple threads concurrently. Proper synchronization mechanisms should be used to ensure thread safety when accessing or modifying shared static variables.

4. Can a static block throw an exception?
Yes, a static block can throw an exception. However, it is important to handle the exception or propagate it using appropriate exception handling mechanisms.

5. Can a static class be instantiated?
Yes, a static class can be instantiated. However, the static keyword for a class usually applies to nested classes, and it does not restrict instantiation. It mainly indicates that the nested class does not have an implicit reference to the outer class.

Leave a Reply

Your email address will not be published. Required fields are marked *