top of page
Writer's pictureThe Tech Platform

What is Static in Java?

Java is a versatile programming language that is used to create a wide range of applications. One of the key features of Java is its support for the "static" keyword, which allows programmers to create class members that belong to the class itself rather than individual instances of a class. But what exactly does "static" mean in the context of Java? In this article, we'll explore the concept of static in Java and how it can be used to improve the efficiency and functionality of your Java code.


What is Static in Java?

In Java, "static" is a keyword that can be used to declare a variable, method, or inner class that belongs to a class rather than an instance of the class. When a variable or method is declared static, it can be accessed without the need for an instance of the class to be created.


There are several reasons why the "static" keyword is important in Java:

  1. Memory management: Since static variables and methods are associated with the class rather than an instance of the class, they are loaded into memory when the class is first loaded and remain in memory until the program exits.

  2. Sharing data: Static variables can be used to share data across all instances of a class. For example, a static variable can be used to keep track of the number of objects created from a class.

  3. Utility classes: Static methods can be used to create utility classes that provide common functionality that can be used by other classes without the need to create an instance of the utility class.

  4. Constants: Static final variables can be used to declare constants that can be accessed by all instances of a class.


Static Variables

Static variables (also called Class Variables) are associated with a class rather than a specific instance of the class. This means that the variable's value is shared among all instances of the class, and any changes made to the variable are reflected across all instances.


Here's an example of a static variable in Java:

public class MyClass 
{
    static int count = 0;
    public MyClass() 
    {
        count++;
    }
}

In this example, we have a class called MyClass with a static variable called count. Each time a new instance of MyClass is created, the constructor increments the count variable.


Here's an example of usage of the class 'MyClass':

MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
System.out.println(MyClass.count);

In this example, we create two instances of MyClass and then print the value of the static count variable. The output of this program will be 2 since we created two instances of the class, and each instance incremented the count variable.


Here is an example program in Java that adds two numbers using a static variable:

public class AddTwoNumbers 
{     
    static int result;      
    
    public static void add(int num1, int num2) 
    {         
        result = num1 + num2;     
    }      
    
    public static void main(String[] args) 
    {         
        int num1=5, num2 = 10;         
        add(num1, num2);         
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + result);     
    } 
}

Output:

The sum of 5 and 10 is: 15

Static variables are useful in counting the number of instances of a class, storing global configuration values, or caching frequently used data. For example, MyClass.count can be accessed without creating an instance of MyClass.


Static Method

A static method is also associated with a class. The method can be called directly on the class, without the need to create an instance of the class.

Here's an example of a static method in Java:

public class AddNumbers 
{     
    public static void main(String[] args) 
    {         
        int a = 5;         
        int b = 10;         
        int sum = add(a, b);         
        System.out.println("The sum of " + a + " and " + b + " is " + sum);     
    }          
    public static int add(int num1, int num2) 
    {         
        return num1 + num2;     
    } 
}

Output:

The sum of 5 and 10 is 15

In this program, we define a class called AddNumbers that contains a static method called add. The add method takes two integer arguments, adds them together, and returns the sum.


In the main method of the class, we declare two integer variables a and b, and initialize them to the values 5 and 10, respectively. We then call the add method, passing in a and b as arguments, and assign the result to a variable called sum. Finally, we use System.out.println to print a message that displays the values of a, b, and sum.

Static methods are useful for providing utility methods that can be used across an entire application or defining methods that don't require access to instance variables. Static methods are associated with a class so they cannot access non-static variables or methods of the class unless they are passed in as parameters.


Static Blocks

A static block is a block of code that is executed when a class is loaded into memory. Static blocks are typically used to perform one-time initialization tasks or to set up static variables.


Here's an example of a static block in Java:

public class AddTwoNumbers 
{     
    static int num1;     
    static int num2;     
    static int sum;      
    
    static {         
        num1 = 10;         
        num2 = 20;         
        sum = num1 + num2;     
    }      
    
    public static void main(String[] args) 
    {         
        System.out.println("Number 1: " + num1);         
        System.out.println("Number 2: " + num2);         
        System.out.println("Sum: " + sum);     
    } 
}

Output:

Number 1: 10
Number 2: 20
Sum: 30

In this program, we have declared three static variables: num1, num2, and sum. We have also defined a static block that initializes these variables by adding num1 and num2 and storing the result in sum.


In the main method, we simply print out the values of num1, num2, and sum.


Static blocks can be useful for initializing static variables that depend on complex or time-consuming computations. For example, a static block could be used to load a configuration file or to establish a database connection that will be used throughout the lifetime of the application.


Static Inner Class

A static inner class is a nested class that is declared with the static modifier. Unlike non-static inner classes, static inner classes do not have access to the instance variables and methods of the outer class. This means that they can be instantiated without an instance of the outer class.


Here's an example of a static inner class:

public class OuterClass 
{
    private static int outerData = 10;

    public static class InnerClass 
    {
        private int innerData;

        public void setInnerData(int data) 
        {
            this.innerData = data;
        }

        public int getInnerData() 
        {
            return this.innerData;
        }

        public int getOuterData() 
        {
            return outerData;
        }
    }
}

In this example, OuterClass has a static inner class called InnerClass. InnerClass has its member variable innerData and two methods setInnerData() and getInnerData() to set and get the value of innerData. It also has a method getOuterData() that can access the static variable outerData of the outer class OuterClass.


Here's how you can create an instance of the InnerClass:

OuterClass.InnerClass innerObj = new OuterClass.InnerClass();

As you can see, you can create an instance of the static inner class without creating an instance of the outer class.


Static inner classes can be useful in situations where you need to group related classes, but the inner classes do not need to access the instance variables and methods of the outer class. They can also be used to improve code organization and encapsulation.


Difference between Static and Non-Static in Java

Factors

Static

Non-Static

Memory Allocation

Variables are allocated memory only once when the class is loaded. They share the same space among all instances of the class.

Variables are allocated memory each time when an object is created. They have separate memory spaces for each object.

Accessing methods and members

Only access static members and methods of the same or another class but they cannot access non-static members and methods.

Can access both static and non-static members and methods of the same or another class.

Calling Process

Variables can be accessed without creating an instance of the class, by using the class name followed by the variable name.

Variables can be accessed only by creating an instance of the class, by using an object reference followed by the variable name.

Binding Process

It uses compile-time: memory location is fixed at compile time

It uses runtime: memory location is determined at runtime.

Value sharing

It has a single value that is shared among all instances of the class: changes to a static variable are reflected in all objects of the class.

It has different values for each object of the class: changes to non-static variables are not reflected in other objects of the class.



Advantages and Disadvantages of using Static in Java


Advantages of Static in Java:

  • They are allocated memory only once and can be accessed without creating an instance of the class. This makes them memory efficient and useful for providing utility functions and constants.

  • They can be accessed by other classes using the class name, which can make the code more readable and organized.

  • Static blocks can be used to initialize static variables that require some computation or logic.

Disadvantages of Static in Java:

  • They cannot access non-static members of the class, as they are not associated with any particular instance of the class. This can limit their functionality and flexibility.

  • Static variables are shared among all instances of the class, which means that changes to a static variable are reflected in all objects of the class. This can cause unexpected behavior and concurrency issues if not handled properly.

  • Static methods cannot be overridden by subclasses, as they are associated with the class rather than with a particular instance of the class. This can reduce the benefits of polymorphism and inheritance.


Conclusion

Static is a powerful and versatile keyword in Java that can be used to improve the efficiency and functionality of your code. It allows you to create methods and variables that belong to the class, rather than an instance of the class, which can be useful in a variety of situations. By understanding the concepts and techniques of using static in Java, you can take your programming skills to the next level and create code that is more efficient, effective, and maintainable.

0 comments

Recent Posts

See All

Comments


bottom of page