Monday, November 7, 2011

What is Static Variable Class method and keyword in Java - Example Tutorial

What is Static in Java
Static in Java is an important keyword and used to create static method, static class and static variable in Java. Correct understanding of static keyword is required to understand and write sophisticated Java programs. Java 5 also introduced static imports along with Autoboxing, Generics, Enum and varargs method, which allows to import static members of one class or package into another using import keyword and then using them like they are member of that class. In this Java tutorial we will learn about What is is static in Java, What does it mean to be a static field, static class or method in Java and various points and issues involved around How to use static members in Java. This Java tutorial is also about how to use static keyword in Java and where not to use static keyword. Common rule is anything which you want to share between all object can be made static e.g. singleton instance of a  Singleton Class in Java.

What is static keyword in Java

static keyword is like any other keyword a simple keyword which can be applied to Java method , nested class or member variable inside a class. static variable in Java belong to whole Class than individual Object. Which means if Class A has a static int variable counter and A has two instance a1 and a2 both will have a static variable counter whose value would be always same except race conditions. Remember class is a blueprint while objects are real instances. So a static variable no matter whether its int, char or String will always hold same value for all instances of that class. In other words there is only one copy of static variable will be present in Java Heap memory, which can be accessed or altered by any object. When we make a method static means that method belongs to class and you can call it without creating any instance of that class. Mostly utility methods are declared as static method, so that program can call them directly by using class name and not to wait for object to be ready. One of the most popular example of static method in Java is main method and this is the reason Why main is static in Java

What is difference between static and non-static variable in Java


What is static variable method and Class in Java - static keyword exampleJava member variable can be static or non-static. static variable belongs to Java class while non-static variable belongs to object. static variable will keep same value for every object while value of non static variable varies from object to object. In other word one static variable is shared between all object in Java, which means in a multi-threading environment access to static variable must be synchronized other wise you will get unexpected behavior. Its not suggest to use static variable in multi-threading and concurrent application because some time it create subtle bugs which is hard to find and debug. In short main difference between static and non static variable is that former belongs to class and later belongs to object.

10 points about static keyword in Java

In this section we will see some important properties of static variable, static method and static class in Java. We will also some Java coding best practices related to static variables in Java.

1) static keyword can be applied with variable, method or nested class. static keyword can not be applied on top level class. Making a top level class static in Java will result in compile time error.

2) static variables are associated with class instead of object.

3) static variables in java keeps same value for every single object.

4) you can not use non-static variable inside a static method , it will result in compilation error as shown below. See Why static variable can not be called from static method for more details.

public class TradingSystem {

    String description = "electronic trading system";
  
    public static void main(String[] args) {
        description = "commodity trading system";
    }
}

Cannot make a static reference to the non-static field description

    at TradingSystem.main(TradingSystem.java:8)
  
  
5) Static variables are bonded using static binding at compile time so they are comparatively faster than there non-static counter part which were bonded during runtime.

6) Static fields are initialized at the time of class loading in Java, opposite to instance variable which is initialised when you create instance of a particular class.

7) Static keyword can also be used to create static block in Java which holds piece of code to executed when class is loaded in Java. This is also known as static initialize block as shown in below example.

    static {
        String category = "electronic trading system";
        System.out.println("example of static block in java");
    }

Beware that if your static initialize block throws Exception than you may get java.lang.NoClassDefFoundError when you try to access the class which failed to load.

8) Static method can not be overridden in Java as they belong to class and not to object. so if you have same static  method in subclass and super class , method will be invoked based on declared type of object instead of runtime for example. Can we override static method in Java is also a popular Java question asked in interviews.

public class TradingSystem {

    public static void main(String[] args) {
        TradingSystem system = new DirectMarketAccess();
        DirectMarketAccess dma = new DirectMarketAccess();
        
        // static method of Instrument class will be called,
        // even though object is of sub-class DirectMarketAccess
        system.printCategory();
        
        //static method of EquityInstrument class will be called
        dma.printCategory();
    }
  
    public static void printCategory(){
        System.out.println("inside super class static method");
    }
}
  
class DirectMarketAccess extends TradingSystem{
    public static void printCategory(){
        System.out.println("inside sub class static method");
    }
}

Output:
inside super class static method
inside sub class static method

This shows that static method can not be overridden in Java and concept of method overloading doesn't apply to static methods. Instead declaring same static method on Child class is known as method hiding in Java.

9. If you try to override a static method with a non-static method in sub class you will get compilation error.

10. Be careful while using static keyword in multi-threading or concurrent programming because most of the issue arise of concurrently modifying a static variable by different threads resulting in working with stale or incorrect value if not properly synchronized. most common issue is race condition which occurs due to poor synchronization or no synchronization of static variable.



Best practices - static variable and static method in Java
Here are some of the best practices you can follow while using static variable and method in Java.

1. Consider making a static variable final in Java to make it constant and avoid changing it from anywhere in the code. Also remember that if  you change value of static final variable in Java like in enum String pattern, you need to recompile all classes which use those variable, because static final variables are cached on client side.

2) Do not use static and non static synchronized method to protect a shared resource because both method locked on different object, which means they can be executed concurrently. See my post Java Mistake 2 - Mixing non static and static method in Java for more details.

 

What is nested static class in Java

Nested static class in Java is a static member of any top level class. Though you can make any class static in Java, but you can only make nested classes i.e. class inside another class as static, you can not make any top level class static. Those classes are called nested static classes. Since to create instance of any nested class you require instance of outer class but that is not required in case of static nested class in Java. You can have an instance of nested static class without any instance of outer class. Here is an example of static nested class in Java
    
public class StaticClass{

    public static void main(String args[]){
        StaticClass.NestedStaticClass ns = new StaticClass.NestedStaticClass();
        System.out.println(ns.getDescription());
    }
  
    static class NestedStaticClass{
        public String NestedStaticDescription =" Example of Nested Static Class in Java";
      
        public String getDescription(){
            return NestedStaticDescription;
        }
    }


Output:
Example of Nested Static Class in Java
  
 

When to use nested static class in Java

Normally we make a class static in Java when we want a single resource to be shared between all instances and normally we do this for utility classes which are required by all components and which itself doesn't have any state. Sometime interviewer ask  when to use Singleton vs Static Class in Java for those purpose,answer is that if its completely stateless and it work on provided data then you can go for static class otherwise Singleton pattern is a better choice.
    

When to make a method static in Java

We can make a method static in Java in following scenario:
      1) Method doesn't depends on object's state, in other words doesn't depend on any member variable and everything they need is passes as parameter to them.
      2) Method belongs to class naturally can be made static in Java.
      3) Utility methods are good candidate of making static in Java because then they can directly be accessed using class name without even creating any instance. Classic example is java.lang.Math
      4) In various designs pattern which need a global access e.g. Singleton pattern, Factory Pattern.
    

Disadvantage of static method in Java

There are certain disadvantages also if you make any method static in Java for example you can not override any static method in Java so it makes testing harder you can not replace that method with mock. Since static method maintains global state they can create subtle bug in concurrent environment which is hard to detect and fix.    
 

Example of static class and method in Java

Static method in Java is very popular to implement Factory design pattern. Since Generics also provides type inference during method invocation, use of static factory method to create object is popular Java idiom. JDK itself is a good example of  several static factory methods like String.valueOf().  Core Java library is also a great place to learn how to use static keyword in java with methods, variables and classes. Another popular example of static method is main method in Java.

1. java.util.Collections has some static utility method which operates on provided collection.
2. java.lang.Math class has static method for maths operations.
3. BorderFactory has static method to control creation of object.
4. Singleton Classes like java.lang.Runtime.

Caution : Static methods should not manage or alter any state. and now a funny question what would happen if you execute following code

public class TradingSystem {

    private static String category = "electronic trading system";
    public static void main(String[] args) {
        TradingSystem system = null;
        System.out.println(system.category);
    }

will it throw NullPointerException in Java or print "electronic trading system"

That's all on What is static variable, method and nested static class in Java. knowledge of static keyword in Java is must for any Java programmer and skill to find out when to use static variable or static method is an important skill. Incorrect and careless use of static variable and static method in Java will result in serious concurrency issues like deadlock and race condition in Java.

Java Tutorial and fundamentals from Javarevisted

17 comments :

Anonymous said...

One important point you may want to add is loading and unloading of static fields. Static fields or variables are initialized when Class is first loaded by ClassLoader while they are unloaded from memory if there is no live reference of field from any Thread static is present and they are eligible for Garbage Collection.

Anonymous said...

You mean to say the static fields will be unloaded once the class object is garbage collected?

Peter Lawrey said...

I would add a note that static blocks are implicitly thread safe. There is no issue with multiple threads trying to load the same class at once. This also means the simplest thread safe, lazy loading singleton is just

enum Singleton {
INSTANCE;
}

Javin @ Date To String in Java said...

Thanks for your Comment Peter, That's indeed a clever way to define Singleton.

Rashmi said...

Can we make a Class static in Java, What are differences between a static class and non static class in Java, does static class load faster than non static class in Java ?

Anonymous said...

@Rashmi, Difference between static nested class and non static nested class (inner) class is that static doesn't associated with any outer class instance and its instance can be created even before creating any instance of outer class while in case of inner class you first need to create outer class instance and than inner class.static keyword can only be applied to nested class and not on top level class. I don't think static keyword affect loading speed of classes though it affect loading time. static variable, classes etc initialize when class containing them get loaded while non static stuff initialized when instance gets created.

Anonymous said...

This post was really helpful to understand about static keyword in java..
thnks for u and keep provide this kind of post..

sujata said...

my question is what does the keyword static mean in Java ? I see we can use static keyword with fields, methods, nested class, initialize block etc but what does static mean, does static mean something which is not dynamic or same for all ?

Anonymous said...

Can we override static method in Java?
When to use static method in Java?
What is the benefit of using Static method in Java?
How to write unit test for testing static method

pavan kumar said...

class A
{

static int a = 30;

void msg()
{
a= 20;// here by default fach int value why?
System.out.println(a);
}
public static void main(String []args)
{


A c = new A();
c.msg();

}
}

manikandan alagar said...

Hi,

Here a small correction needs to be done at the 4th point in this page.

Non-static variables cant be called from a static method. I was confused by this, that is why i wanted to point this.

URL:
http://javarevisited.blogspot.com/2011/11/static-keyword-method-variable-java.html

Thanks,
Mani

Anonymous said...

Hi Mani,

Point 4 is absolutely correct.
Please write a program and u will see it yourself.

Thanks

Anonymous said...

regarding the Static keyword code please look at the following
public class TradingSystem {

private static String category = "electronic trading system";
public static void main(String[] args) {
TradingSystem system = null;
System.out.println(system.category);
}

I just wanted to share that during runtime static block has precedence in calling over constructors or methods therefore the output of "electronic trading system" remains a normal expected response of the JVM :)

Anonymous said...

Hi,
I think Mani pointed this typo regarding point 4,
which says "Why static variable can not be called from static method for more details."
and the link says: "Why non-static variable cannot be referenced from a static context?"
Thanks, Att

vel said...

Is static variable live in java heap memory?

Naga said...

HI javin, I find it very informative regarding your blog, and I have a doubt regarding the below statement in the above blog.

"In other words there is only one copy of static variable will be present in Java Heap memory, which can be accessed or altered by any object."

But when i am learning java, i believe that static variables will get stored in method area not in heap memory, let me know if I am wrong, i will correct myself. Thanks.

Arun said...

Definitely in most of the programming languages static variables are stored in heap memory only.

Post a Comment