What is static in Java? Example Tutorial

What is static in Java
Static in Java is related to class if a field is static means it belongs to the class, similarly static method belongs to classes and you can access both static method and field using the class name, for example,  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 like private fields are only accessible in class on which they are declared, protected fields are accessible to all classes in the same package but only accessible in subclass outside the package, you can further 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 then you can call it Counter. increment(). There is no need to create an object of Counter class to access either static method or static field, this is the main difference between static and non-static members.

Another key thing to note about static members like static variable and static method is that they belong to class instead of an object, I mean, the value of the static variable would be the same for all objects of Counter class.

In this Java static keyword tutorial, you will learn what is static keyword in Java, what is a static variable, and static method, and some important features of static in Java, which will not only help to understand key programming concepts in Java but also helps in various Java questions up to 2 to 4 years experience.

By the way, if you are new to the Java Programming world then I also recommend you to join a comprehensive Java course like The Complete Java Masterclass to learn Java in a more structured way. This 80-hour long Java course is also the most up-to-date and comprehensive course but you can get in just $9.9 on Udemy sales which happens every now and then. 




What Every Programmer Should Know about Static in Java

In this section, we will learn some key things about static keywords in Java, including their usage on variables, methods, and classes. This is what every Java developer should know about static before going into real-world programming. So let's start with static variables in Java.

1.  Static Context

You can not access non-static members inside a static context like a static method or static block. The following code will result in a 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 mistakes made by Java programmers especially one who just started programming in Java. Since the main method in Java is static and the count variable is non-static in this case, the print statement inside the main method will throw a compile-time error. 

Here is another example, where Eclipse IDE is showing an error when you try to call a  non-static method from a static method (main ) in Java:



If you want to learn more then you can further see why non-static members are not accessible inside a static context to know more about this issue.


2. Thread Safety

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 applications. Since every object of a class has the same copy of the static variable, it needs to be guarded by a 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. 

Though, if you are interested in mastering the multi-threading and Concurrency in Java then I highly recommend you check out Java Multithreading, Concurrency & Performance Optimization course by Michael Pogrebinsky on Udemy. It's one of the best courses to master this important skill for Java developers. 

static method and thread safety issues




3.  Class method

Static methods have an 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 the Type of the class, which contains them, I mean you can call them like the ClassName.method() that's why they are also known as class methods in Java. 

Because of that they are also 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. Overriding

Another important point about the static method is that you can not override the static method in Java. If you declare the same method in subclass i.e. static method with the same name and method signature it will only hide the superclass 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 superclass and sub-class, the method is always resolved at compile time by using the Type of reference variable. 

Unlike the case of method overriding they will not be resolved during runtime, as shown in the 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, instead of the object being of Car, a static method from Vehicle is introduced, because the method is resolved at compile time. Also, there is no compile timer error.


5. Static Class

You can also make a class static in Java, except for top-level classes. Those classes are known as nested static classes in Java. a nested static class is particularly useful to provide improved cohesion, one example of a nested static class is HashMap.Entry, which represents a data structure, used to hold HashMap entries, you also see How the get method of HashMap works in Java for more details on the working of HashMap in Java. 

By the way like any inner class, a nested static class also results in a separate .class file. This 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. 

Here is another example of a nested static class in Java:


nested static class in Java



One more use case of the nested static class is defining custom Comparator s like AgeComparator in Employee class. See how to sort the list of Objects using Comparator in Java for step by step guide of defining Comparator.

6. Static Block

static keyword can also be used to declare static block which is executed during class loading. This is known as a 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 executes them during class loading. 

Though static block can not throw checked exception, they can still throw an 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 reasons for NoClassDefFoundError in Java because the class in question was not present in memory when its client needed them.


7. Static Binding

One more thing to know about static methods is that they are bonded during compile time using static binding. This is different than the binding of virtual or non-static methods which are bonded during run-time based upon a real object. This means the static method can not be overridden in Java as run-time polymorphism doesn't apply to them. 

This is an important restriction, you should consider while making a method static in Java. You should only make a method static if there is no possibility or need of redefining its behavior for the subclass is required. 

Usually, factory methods and utility methods are good candidates for being static. The great Joshua Bloch has highlighted several benefits of using the static factory method alongside the constructor in his classic book Effective Java, a must-read for every Java developer.

best java book for experienced developers



8. Initialization

One of the important properties of a static field is initialization. Static fields or variables are initialized when the class is loaded into memory. They are initialized from top to bottom in the order they are declared in the Java source file. See When class is loaded in Java for more details. 

Since static fields are initialized in a thread-safe manner, this property is also used to implement the Singleton pattern in Java and if you are not using Enum as Singleton due to whatever reason, this is a good alternative. 

The only thing to consider is that it's not a lazy initialization, which means the static field will be initialized even before anyone asked for it. If it's an expensive object, which is rarely used then initializing them in a static manner will not yield good results.


9. Serialization

During Serialization, like transient variables, static variables are also not serialized. It means, if you store any data in a static field then after deserialization, the new object will contain its default value like if the 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 questions in Java interviews. Make sure not to store key state data of an object in a static field.

10. Static import

Another feature related to the static keyword is called static import. This is similar to standard import statements in Java, but it allows to import of one or all static members of a class. 

By importing static methods, you can call them like they are defined in the same class, similarly by static importing fields, we can access them without specifying the class name.

This feature was introduced in Java 1.5, Tiger release and if used properly, improves the readability of Java application. 

One of the places, where you frequently see the use of static import is JUnit test cases because almost all test writers static import those assert methods like assertEquals() and their overloaded counterparts. Check what is static import in Java with Example for complete details.

static import example in Java


That's all on what is Static in Java and what every Java developer should know about static fields, methods, classes, and keywords themselves. You have seen the basics of static variables or static fields, static methods, static initializer block, and static import in Java. 

You have also learned some important properties of static keywords, which is critical to write and understand Java programs. I suggest getting every Java developer of all experience to master static concepts in Java, it's absolutely important for serious programming in Java.



Thanks for reading this article so far. If you this Java static keyword tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are serious about learning object-oriented programming and looking for a free online course to start with then you can also check this FREE Object Oriented Programming (OOPs) for the JAVA Interviews course on Udemy. It's completely free and you just need a free Udemy account to join this course

And now one question for you, can you override static method in Java? If not why not, can you explain in comments? 

6 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
  3. If i remove the static keyword from both kmToMiles() method, the output is "Inside Child class' static method".

    Why is that? Please explain.
    I am new to Java, Thanks

    ReplyDelete
    Replies
    1. @Anonymous, because then they become virtual methods i.e. they are resolved at run-time, hence they can be overridden. Since kmToMiles() in sub class override same method of parent class you see output from child class, which is "Inside Child class"

      Delete
  4. Of course static methods are thread safe. The data you pass in may not be.

    ReplyDelete
  5. Can we create static block inside static block in Java??if no then what is the reason behind it..

    ReplyDelete

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