top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Static Keyword In Java

Introduction

The Java programming language has a powerful feature referred to as the static keyword. This plays an essential part in defining class-level entities that are shared by all instances of a class. This in-depth write-up dives into the ins and outs of the static keyword in Java, helping the enthusiasts of this programming language study its properties, applications, and advantages. By understanding the intricacies of the static keyword, including its relationship with the public static void main in Java, individuals can unlock its full potential and optimize their programs.

Overview

The static keyword in Java serves as a crucial element when it comes to defining class-level members such as variables, methods, and nested classes. By marking a member as static, it becomes associated with the class itself rather than any specific instance of it. As a result, all objects of that particular class share the same copy of the static member, regardless of the number of instances created.

Static Keyword in Java

As a beginner, you may wonder why we use static keyword in Java. The main reason is that it helps save memory.  Java’s static keyword possesses distinct characteristics that set it apart, and they are mentioned below.

1. Class Association: Static members can be accessed by using the class name because they are linked to the class. This suggests that modifications to one are applied to all instances of the class and that the class name can be used to access static members rather than an object reference.

2. Lifetime: Static members are present from the point at which the class is loaded into memory to the instance at which the program ends.

3. Direct Access: Static members can be accessed directly without the need to construct a class object, making them easily usable. Thanks to this feature, they can then offer constants and useful functions that can be utilized throughout the program.

4. Shared memory allocation: During program execution, memory is only allocated once for static variables and methods. Since all instances of a class share this memory space, static members are necessary for maintaining the global state or shared functionality.

5. Accessibility: The availability of non-static members is restricted because static methods and variables are not connected to a particular instance of the class.

6. Static methods can be overloaded, allowing the development of many methods with the same name but different parameters. These cannot be overridden because they are associated with the class rather than a specific instance of the class.

A member can be accessed without referencing an object and before any objects of its class are created if it is declared static. In the following Java code, for instance, the static method m1() is obtained without creating an instance of the Test class.

// Java program to demonstrate that a static member
// can be accessed before instantiating a class

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

public static void main(String[] args)
{
// calling m1 without creating
// any object of class Test
m1();
}
}


Output
from m1

The Anatomy of the Static Keyword in Java

Static Blocks:

Static blocks are utilized to initialize static variables or perform other static operations. They are executed when the class is loaded into memory, even before the creation of any objects. They are enclosed within a pair of curly braces and preceded by the static keyword. Further, the static keyword is used when one needs to perform one-time initialization. Here's an example:

java
public class MyClass {
    static {
        System.out.println("Static block executed!");
    }

    public static void main(String[] args) {
        System.out.println("Inside the main method");
    }
}


Output:
scss
Static block executed!
Inside the main method

Static Variables:

Static variables, also known as class variables, are shared among all instances of a class. They retain their values throughout the execution of the program. Here's an example:

java
public class MyClass {
    static int count = 0;

    public MyClass() {
        count++;
    }

    public static void main(String[] args) {
        MyClass obj1 = new MyClass();
        MyClass obj2 = new MyClass();
        System.out.println("Count: " + count);
    }
}


Output:
makefile
Count: 2

Static Methods:

Static methods in Java belong to the class itself and can be invoked directly without creating an object. They are commonly used for utility functions or operations that don't require instance-specific data. Here's an example:

java
public class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = MathUtils.add(5, 3);
        System.out.println("Result: " + result);
    }
}


Output:
makefile
Result: 8

When to Use Static Variables and Methods?

Static variables and methods are suitable in various scenarios. Let’s study the use of static variables and static methods in Java with examples.

1. Utility Methods: When a method doesn't rely on any instance-specific data, it can be made static for easy access. For example, consider a MathUtils class that provides mathematical operations:

java
public class Main {
    public static void main(String[] args) {
        int sum = MathUtils.add(5, 3);
        int product = MathUtils.multiply(2, 4);

        System.out.println("Sum: " + sum);
        System.out.println("Product: " + product);
    }
}


Output:
makefile
Sum: 8
Product: 8

In this example, the add method is called with arguments 5 and 3, and the multiply method is called with arguments 2 and 4. The returned values are then printed to the console, resulting in the output shown above.

You can access these static methods directly using the class name, such as MathUtils.add(5, 3) or MathUtils.multiply(2, 4).

2. Counters: Static variables are useful for counting the number of instances created for a class. Let's say you have a Car class, and you want to keep track of the total number of cars created:

public class Car {
    private static int totalCars = 0;

    public Car() {
        totalCars++;
    }

    public static int getTotalCars() {
        return totalCars;
    }
}

public class Main {
    public static void main(String[] args) {
        Car car1 = new Car();
        Car car2 = new Car();
        Car car3 = new Car();

        System.out.println("Total cars created: " + Car.getTotalCars());
    }
}


Output:
mathematica
Total cars created: 3

The totalCars variable is static and increments each time a new Car object is created. 

3. Constants: Static variables can be used to store constants that remain the same across all instances. Let us consider a class representing the mathematical constant pi: 

java
public class MathConstants {
    public static final double PI = 3.14159;
    public static final double E = 2.71828;
    // Other constants...
}

Using the class name MathConstants.PI or MathConstants.E, these ultimate static variables are accessible anywhere in the program.

By utilizing static variables and methods in these circumstances, you can improve Java program code organization, efficiency, and reusability.

Static Nested Classes:

Java allows the creation of static nested classes, which are declared as static within another class. These classes can access only the static members of the enclosing class. Here's an example:

java
public class OuterClass {
    static class NestedClass {
        void display() {
            System.out.println("Nested class display");
        }
    }

    public static void main(String[] args) {
        OuterClass.NestedClass nestedObj = new OuterClass.NestedClass();
        nestedObj.display();
    }
}


Output:
kotlin
Nested class display

The output "Nested class display" is generated because the `display()` method of the `NestedClass, nested within the `OuterClass, is invoked through an instance of the nested class.

Advantages of Using the Static Keyword

The static keyword offers several advantages:

1. Memory Efficacy: You can store static members in a single location in memory, reducing memory consumption.

2. Convenient Access: Static members can be accessed directly using the class name without the need for object creation.

3. Code Reusability: Static methods and variables allow for code reuse across multiple instances of a class.

4. Static members can be accessed more swiftly and effectively than their non-static counterparts because they are associated with the class rather than with individual instances.

5. Utility methods that don't need access to an object's state can be contained in static methods. This can improve the organization of the code and make it easier for utility methods to be reused across different classes.

6. Constants: Static final variables can be used to define program-wide constants.

7. Static methods can be used to implement class-level functionality, such as factory methods and utility functions that don't need access to an object's state.

Static vs Non-Static

Before concluding this Static keyword in Java tutorial,  investigating static blocks and classes, let's discuss a few distinctions between static and non-static variables and methods in Java.

Static Variables

Non-static Variables

They can be accessed using the class names

Objects can be accessed using non-static variables.

They can be accessed using either static or non-static methods

Accessing them is restricted to non-static methods.

They only receive a single memory allocation when the class is launched

Each object is allocated its own memory.

All instances or objects of the class share the same variables

The non-static variables are duplicated for each object.

The scope of static variables is global

The scope of non-static variables is local.

Static Method

Non-static Method

These methods support early or compilation-time binding.

They may facilitate runtime, dynamic, or late binding.

These methods can only access the static variables of their own class and other classes.

They have access to both static and dynamic members.

No static method overrides are allowed.

They can be bypassed.

Since only a single memory allocation is performed when the class is launched, less memory is consumed

Each object has its own memory allocation.

Conclusion

The static keyword in Java provides considerable benefits and is critical in class design and implementation.  By learning its properties and applications, you can use its capabilities to optimize your code and enhance efficiency.

While the static keyword has numerous benefits, it is important to understand its restrictions. Static members cannot directly access non-static variables, and static methods cannot be overridden. However, you can still deal with non-static data within static contexts by supplying the non-static keyword in Java, such as non-static variables as method parameters or using other techniques.

In essence, the Java static keyword enables programmers to create class-level members that are accessible by all class instances. You can improve code reusability, optimize memory usage, and simplify access to class-level entities by exploiting its capabilities. Understanding the subtleties of the static keyword is essential for good Java programming and can have a big impact on the quality and efficiency of your product.

Common Interview Questions Related to the Static Keyword in Java

Q1. In which portion of memory are static variables stored?

All static variables are stored in the heap memory's PermGen space.

Q2. What distinguishes a static variable from an instance variable?

The distinctive features of static and instance variables are the following:

a) Class variables can be accessed within static blocks, instance blocks, static methods, instance methods, and inner class methods, whereas instance variables can only be accessed within instance members and inner class methods.

b) Class variables are always resolved at compile time, while instance variables are fixed at runtime.

c) In Java, static variables cannot be serialized, whereas it is possible with instance variables.

Q3. Why is a static method also known as a class method?

A static method is also referred to as a class method because it is associated with a class rather than a specific instance of a class. Therefore, it is not necessary to construct an instance of the class in order to invoke and execute static methods.

FAQs

Q1: What is the difference between the static and final keywords in Java?

The static keyword is used to define class-level members, while the final keyword is used to declare constants or prevent modification of variables, methods, or classes.

Q2: Why is it important to use the static keyword in the main method?

A Java program's main method serves as its entry point, and the JVM needs to declare it as static in order to access it without first creating an instance of the class.

Q3: Are static variables thread-safe in Java?

Static variables are not inherently thread-safe. If multiple threads modify the same static variable concurrently, synchronization mechanisms need to be implemented to ensure thread safety.

Leave a Reply

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