Difference between static and instance member variables in Java? Answer Example

Hello Java Programmers, In the last article, I had explained some key differences between static and nonstatic methods in Java, and in this part, I'll explain the difference between static and nonstatic member variables in Java. The concept of static remains the same, that doesn't change with method or member variables but there are still some subtle details, which every Java programmer should know and understand. As with static methods, a static member variable belongs to a class and a non-static member variable belongs to an instance. 

This means, the value of a static variable will be the same for all instances, but the value of a non-static variable will be different for different objects. That is also referred to as the state of objects. The value of the non-static member variable actually defines the state of objects.

Once you know this key difference between the static and non-static member variables, you can decide yourself when to make a member variable static in Java. Obviously, if you have a variable, whose value needs to be the same across all instances like a constant, or a class-wide counter, then you can make that member static.

More often than not and it is also a best practice to use the final keyword with static variables in Java. It's better to declare a variable static final to make it a compile-time constant, especially if it is public. Making it final ensures that the value cannot be changed once initialized.

You will rarely need a static member variable that is not final, but if you do, take special care while dealing with it, as incorrect sharing of that variable among multiple threads in Java can cause subtle logical thread-safety bugs.

These bugs are nasty as they appear rarely and mostly in production than in a test environment. We'll take a look at different properties of static variables in this article to empower you with all the knowledge you need to make a correct decision of when to use a static variable in Java.




Important properties of static and non-static variables

Here are some important points about static and instance, also known as a class and instance variables in Java:

1. Value

 First and most important, the value of a static variable is the same for all instances. This is demonstrated by following the Java program, where we have a static variable, a company that is static, and a non-static variable brand

This program then creates three different instances and you can see the value of the static variable remains the same for all of them, but the value of the non-static member variable is different for each of them.

/**
 * Java Program to demonstrate difference between static
 * vs non-static member variables.
 * 
 * @author Javin Paul
 *
 */
public class StaticMemberTest{

    public static void main(String[] args) {
        
        Product p1 = new Product("Vivo");
        Product p2 = new Product("Bravia");
        Product p3 = new Product("Xperia");
        
        System.out.printf("Company: %s, Brand: %s %n",
                              Product.getCompany(), p1.getBrand());
        System.out.printf("Company: %s, Brand: %s %n", 
                              Product.getCompany(), p2.getBrand());
        System.out.printf("Company: %s, Brand: %s %n", 
                              Product.getCompany(), p3.getBrand());
    }
     
    
    
}


class Product{
    private static String company = "Sony";
    private String brand;
    
    public Product(String brand){
        this.brand = brand;
    }

    public static String getCompany() {
        return company;
    }

    public String getBrand() {
        return brand;
    }
    
    
}

Output
Company: Sony, Brand: Vivo 
Company: Sony, Brand: Bravia 
Company: Sony, Brand: Xperia 


2) Access and Scope

The second difference between a static variable and a nonstatic variable in Java is that you can access a static member by classname, i.e. you don't need to create an instance of a class to access the static variable, but you definitely need an instance to access the non-static variable in Java.

Here is an example which demonstrates this difference between static and instance member variable in Java.

Difference between static and instance variable in Java



3. Usage

Static variables are commonly employed for constants or shared data, while instance variables are utilized to encapsulate the state of individual objects. Static variables can access other static members directly but cannot access instance members without an object reference. 

In contrast, instance variables can access both static and instance members directly. The choice between static and instance variables depends on the specific requirements and design considerations of the class in question.

4. Initialization and Memory Allocation

Also static variables are initialized when class is loaded while instance variables are initialized when an object is created. Yes, Memory for static variables is allocated once, at the time the class is loaded, and they persist throughout the program's lifetime. Static variables are typically used for constants or values that are shared by all instances.

On the other, Memory for instance variables is allocated when an object is created and released when the object is garbage collected. Instance variables are initialized each time a new object is created and may have different values for different instances.

5. Context

When considering the usage in static and instance contexts, static member variables in Java exhibit the capability to access other static members directly. This means that static variables can interact seamlessly with other static elements within the same class. However, static member variables encounter limitations when attempting to access instance members directly, necessitating an object reference for such access.

In contrast, instance member variables possess a more versatile nature. They can access both static and instance members directly, affording them the flexibility to interact with various elements within their class without requiring a specific object reference. 

This makes instance member variables more versatile in their ability to communicate with both static and instance components, contributing to their broader utility in the context of Java classes.

Here is another example of static and instance variable in Java:

public class Example {
    // Static member variable
    static int staticVariable;

    // Instance member variable
    int instanceVariable;

    public static void main(String[] args) {
        // Accessing static variable directly
        Example.staticVariable = 10;

        // Creating an instance
        Example obj = new Example();
        
        // Accessing instance variable using an object reference
        obj.instanceVariable = 20;
    }
}

And, here is a nice diagram in tabular format to remember the difference between static and instance member variable in Java:

Difference between static and instance member variables in Java? Answer



That's all about the difference between static and non-static member variables in Java. Just remember the key difference that the value of a static variable will be the same for ALL instances, but the value of a nonstatic variable will be different for different instances. You can only make a member variable static in Java, a local variable cannot be static.

Regarding when to make a variable static in Java, instance wide constants are a good candidate for making static. You should also try to make a variable final along with static if possible, this eliminates risk. Last, but not least, always be careful while dealing with a non-final static variable in Java.

It's a bad practice to make collection classes like ArrayList or HashMap static if they are not read-only. You might think that a static final HashMap cannot be changed but that's not true, you can still add more remove mappings from that Map, which may cause confusion and subtle bugs. If you need a really static Map, use static final along with unmodifiable read-only Maps.

3 comments:

  1. What is the use of exception handling in java and why should we use it?

    ReplyDelete
    Replies
    1. Hello @fayyaz, Exception handling enable you to write robust application, program which doesn't crash on bad user input, or multiple button press etc. Exception handling allow your program handle bad scenarios gracefully.

      Delete
  2. Great breakdown! Static variables belong to the class itself and are shared among all instances, while instance variables are specific to each object. Nice explanation of their differences

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.