Friday, November 23, 2012

10 points about Static in Java

What is static in Java
Static in Java is related to class, if a field is static means it belongs to class, similarly static method belongs to classes and you can access both static method and field using class name e.g. if count field is static in Counter class than you can access it as Counter.count, of course subject to restriction applied by access modifier e.g. private fields are only accessible in class on which they are declared, protected fields are accessible to all classes in same package but only accessible in sub class outside package. See private vs protected vs public for complete details on access modifier. Similarly if you have a static method increment() in Counter class which increment counter than you can call it as Counter.increment(). There is no need to create an object of Counter class to access either static method or static field, this is main difference between static and non static members.
Another key thing to note about static members e.g. static variable and static method is that they belong to class instead of object, i.e. value of static variable would be same for all object of Counter class. In this Java tutorial we will learn What is static keyword in Java, What is static variable and static method
and some important features of static in Java, which will not only help to understand key programming concept in Java but also helps in various Java questions up to 2 to 4 years experience.


What Every Programmer Should Know about Static in Java

In this section we will learn some key things about static keyword in Java, including its usage on variable, methods and classes. This is what every Java developer should know about static before going into real world programming. So lets start with static variables in Java.

1) You can not access non static member inside static context e.g. static method or static block. Following code will result in compile time error in Java

public class Counter{

private int count;

public static void main(String args[]){
   System.out.println(count); //compile time error
}

}

This is one of the most common mistake made by Java programmer especially one who just started programming in Java. Since main method in Java is static and count variable is non static in this case, print statement inside main method will throw compile time error. See Why non static members is not accessible inside static context to know more about this issue.


2) Unlike local variables,  Static variables and methods are not thread-safe in Java. They are actually a common cause of various thread-safety issues in Java application. Since every object of a class has same copy of static variable, it needs to be guarded by class lock. That's why if you are using static variables then make sure to properly synchronized its access to avoid thread-safety issues including race conditions.

static variable method class and field in java3) Static methods has advantage in terms of usability as you don't need to create an object while accessing those methods, You can call any static method by using Type of the class, which contains them. That's why they are best suited for creating instances as factory methods,  and  utility methods. java.lang.Math class is a perfect example where almost all methods are static, subsequently utility classes are also declared final in Java.

4) Another important point about static method is that, you can not override static method in Java. If you declare same method in sub class i.e. static method with same name and method signature
it will only hide super class method, instead of overriding it. This is also known as method hiding in Java. What this means is, if you call a static method, which is declared in both super class and sub class, method is always resolved at compile time by using Type of reference variable. Unlike case of method overriding they will not resolved during runtime, as shown in below example :

class Vehicle{
     public static void  kmToMiles(int km){
          System.out.println("Inside parent class' static method");
     } 
}

class Car extends Vehicle{
     public static void  kmToMiles(int km){
          System.out.println("Inside Child class' static method");
     } 
}

public class Demo{
   
   public static void main(String args[]){
      Vehicle v = new Car();
       v.kmToMiles(10);
  }
}

Output:
Inside parent class' static method

As you can see that, instead of object being of Car, static method from Vehicle is introduced, because method is resolved at compile time. Also there is no compile timer error.

5) You can also make a class static in Java, except top level classes. Those classes are known as nested static class in Java. nested static class is particularly useful to provide improved cohesion, one examples of nested static class is HashMap.Entry, which represent data structure, used to hold HashMap entries, See How get method of HashMap works in Java for more details on working of HashMap in Java. By the way like any inner class, nested static class also results in a separate .class file. Which means, if you have defined five nested classes in your top level class, you will end-up with six class files. One for top level class and five for nested static class. One more use case of nested static class is defining custom Comparator s e.g. AgeComparator in Employee class. See how to sort list of Object using Comparator in Java for step by step guide of defining Comparator.

6) static keyword can also be used to declare static block which is executed during class loading. This is known as static initializer block in Java. If you don't declare a static initializer block by yourself then Java combines all static fields into one block and execute them during class loading. Though static block can not throw checked exception, they can still throw unchecked exception, which if occurred may result in ExceptionInitializerError.  Actually any runtime exception thrown during instantiation and initialization of static fields, will be wrapped by Java runtime into this error. This is also one of the most common reason of  NoClassDefFoundError in Java, because the class in question was not present in memory when its client needed them.

7) One more thing to know about static methods is that they are bonded during compile time using static binding. This is different than binding of virtual or non static methods which are bonded during run-time based upon real object. This means static method can not be overridden in Java as  run-time polymorphism doesn't apply on them. This is an important restriction, you should consider while making a method static in Java. You should only make a method static, if their is no possibility or need of redefining its behaviour for subclass is required. Usually factory methods and utility methods are good candidate of being static. The great Joshua Bloch has highlighted several benefits of using static factory method alongside constructor in his classic book Effective Java, a must read for every Java developer.

8) One of the important property of static field is initialization. Static fields or variables are initialized when class is loaded into memory. They are initialized from top to bottom in the order they are declared in Java source file. See When class is loaded in Java for more details. Since static fields are initialized in thread-safe manner, this property is also used to implement Singleton pattern in Java and if you are not using Enum as Singleton due to whatever reason, this is a good alternative. Only thing to consider is that its not a lazy initialization, which means static field will be initialized even before anyone asked for it. If its an expensive object, which is rarely used then initializing them in static manner will not yield good results.

9) During Serialization, like transient variables, static variables are also not serialized. It means, if you store any data in static filed then after de-serialization, new object will contain its default value e.g. if static field was int then it will contain zero, if float then it should contain 0.0 and if object then it will contain null.  In fact this is one of the frequently asked  serialization related question in Java interviews. Make sure not to store key state data of an object in static field.

10) Another feature related to static keyword is called static import. This is similar to standard import statement in Java, but it allows to import one or all static members of a class. By importing static method, you can call them like they are defined in same class, similarly by static importing fields, we can access them without specifying class name. This feature was introduced in Java 1.5, Tiger release and if used properly, improves readability of Java application. One of the place, where you frequently see use of static import is JUnit test cases because almost all test writer static import those assert methods e.g. assertEquals() and their overloaded counterpart. Check what is static import in Java with Example for complete details.


That's all on what is Static in Java  and what every Java developer should know about static fields, methods, classes and keyword itself. We have basics of  static variables or static fields, static methods, static initializer block and static import in Java. We have also learned some important properties of static keyword, which is critical to write and understand Java program. I suggest to get every Java developer of all experience to master static concept in Java, its absolutely important for serious programming in Java.

Other Java programming tutorial for learning
How to write Java program to print Fibonacci series in Java
Difference between Hashtable and HashMap in Java
ArrayList vs Vector in Java
Top 10 Java coding interview questions and answers
How to find palindrome in Java using recursion 

2 comments:

  1. Statics should be used when you don't want to have varying behavior for different objects.

    Statics should be used when data is not instance dependent and for all existing instances of static member you want to apply same state.

    Statics should not be used at all If they are not actually required as they create dependencies and references to other classes and class loader in JVM and stay in memory for long time. So they are not considered for garbage collection once they are done with current work Instead they are de-referenced with their loading classes as they maintain a reference to static classes.
    Read more-
    http://efectivejava.blogspot.in/2013/08/when-to-use-static-members-in-java.html

    ReplyDelete
  2. Static members in java playing key role.
    It should be used when you don't want to have varying behavior for different objects.


    http://efectivejava.blogspot.in/2013/08/when-to-use-static-members-in-java.html

    ReplyDelete

Java67 Headline Animator