Difference between static and instance member variables in Java? Answer

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.  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) 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



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.

2 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

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