Saturday, August 4, 2012

static method, static class and static variable in Java


static in Java is an important keyword and used in static method, static class and static variable in Java. Correct understanding of static keyword is required to understand and write sophisticated java programs. In this java static tutorial we will learn about What is is static in Java, What does it mean to be a static field, class or method and various points and issues involved around static keyword 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 method , nested class or member variable inside a class. When we make a variable static it means it belongs to that particular class instead of object, 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 keyword will be present in 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 instance of that class. mostly utility methods are declared as static to call them directly by using class name and not to wait for object to be ready.

10 points on Static keyword in Java

Difference between static and non-static variable

static keyword variable and method in java
Java member variable can be static or non-static. static variable belongs to java class while non-static variable belongs to java 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. main() method in Java is a good example of static method in
java.

Important points about static keyword in Java.

1) static keyword can be applied with variable, method or nested class.It can not be applied on top level class.

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:

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 binded during compile time so they are comparatively faster than there non-static counter part which were binded during work hour.

6) Static fields are initialised at the time of class loading 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 can hold a piece of code which can be executed at the time of class loading as shown in below example.

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

8) Static method can not be overridden as they belong to class and not to object. so if you have same method in subclass and super class , method will be invoked based on declared
type of object instead of runtime for example:

public class TradingSystem {

    public static void main(String[] args) {
        TradingSystem system = new DirectMarketAccess();
        DirectMarketAccess dma = new DirectMarketAccess();
        system.instrumentName();//static method of Instrument
Class will be called , even though object is of sub-class
                                //DirectMarketAccess
        dma.instrumentName();//static method of EquityInstrument
class will be called
    }
  
    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");
    }
}


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.



Static Class in Java

You can make any class Static in Javabut 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 incase of static nested Class. You can have an instance of nested static class without any instance of outer class.

Here is an example of nested static class in Java


    
    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;
        }
    }
  
 

When to make a Class Static 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 whether you should Singleton or 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 ishard to detect and fix.
    

Why main is static in Java.

Another important interview question on static in Java is related to main method in Java. Since main method is static people often asked why main is static in Java. Since static method can be called even without creating instance of class, main is made static.
    

Example of static class in Java

JDK itself is a good example of how to use static keyword in java with methods, variables and classes.

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

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


Read more: http://javarevisited.blogspot.com/2011/11/static-keyword-method-variable-java.html#ixzz22ZmvlfUe

No comments:

Post a Comment