Thursday 20 April 2017

Difference between static and nonstatic member variables in Java


Difference between static and nonstatic member variables in Java

The concept of static remains 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 same for all instances, but the value of a non-static variable will be different for different objects. That is also referred as the state of objects. The value of nonstatic 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 about 
when to make a member variable static in Java. Obviously, if you have a variable, whose value needs to be same across all instance e.g. 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 value cannot be changed once initialized.

You will rarely need a static member variable which is not final, but if you do, make 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 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.

You can also see 
Core Java Volume 1 - Fundamentals by Cay S. Horstmann for more details:

static vs non-static member variable in Java



Important properties of static and non-static variables
1) First and most important, the value of a static variable is same for all instance. This is demonstrated by following Java program, where we have a static variable, a company which is static and a non-static variable brand. This program then create three different instances and you can see the value of static variable remains same for all of them, but the value of non-static member variable is different for each of them.


/**
 * Java Program to demonstrate difference between static
 * vs non-static member variables.
 *
 * @author WINDOWS 8
 *
 */
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 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 variable in Java. Just remember the key difference that value of a static variable will be same for ALL instances, but the value of a nonstatic variable will be different for different instance. 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 e.g. 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.


No comments:

Post a Comment