Tuesday, January 21, 2014

What is the Static Keyword in Java

In this post, we'll see the use of static keyword in various locations including what can be marked static or not in Java and how static creation  differ from normal object creation.

The static modifier is used to create variables and methods that will exist independently of any instances created for the class.

All static members exist before you ever make a new instance of a class, and there will be only one copy of a static member regardless of the number of instances of that class.

In other words, all instances of a given class share the same value for any given static variable.

Things you can mark as static:
  • Methods
  • Variables
  • A class nested within another class, but not within a method.
  • Initialization blocks

Things you can't mark as static:
  • Constructors (makes no sense; a constructor is used only to create instances)
  • Classes (unless they are nested)
  • Interfaces
  • Method local inner classes
  • Inner class methods and instance variables
  • Local variables

The way a static member works
Imagine you've got a utility class with a method that always runs the same way; its sole function is to return, say, a random number.
It wouldn't matter which instance of the class performed the method—it would always behave exactly the same way. In other words, the method's behavior has no dependency on the state (instance variable values) of an object.
So why, then, do you need an object when the method will never be instance-specific?
Why not just ask the class itself to run the method?

Suppose you want to keep a running count of all instances instantiated from a particular class. Where do you actually keep that variable? 
It won't work to keep it as an instance variable within the class whose instances you're tracking, because the count will just be initialized back to a default value with each new instance.

Static variable
Static variables belong to a class. They are common to all instances of a class and aren’t unique to any instance of a class. static attributes exist independently of any instances of a class and may be accessed even when no instances of the class have been created. You can compare a static variable with a shared variable. A static variable is shared by all of the objects of a class.

Think of a static variable as being like a common bank vault that’s shared by the employees of an organization. Each of the employees accesses the same bank vault, so any change made by one employee is visible to all the other employees

Variables and methods marked static belong to the class, rather than to any particular instance. In fact, you can use a static method or variable without having any instances of that class at all.
You need only have the class available to be able to invoke a static method or access a static variable. static variables, too, can be accessed without having an instance of a class. 
But if there are instances, a static variable of a class will be shared by all instances of that class; there is only one copy.

Sample Output:
counter : 3

A static method can't access a nonstatic (instance) variable, because there is no instance!
That's not to say there aren't instances of the class alive on the heap, but rather that even if there are, the static method doesn't know anything about them. The same applies to instance methods; a static method can't directly invoke a nonstatic method

Think static = class, nonstatic = instance.

Making the method called by the JVM (main()) a static method means the JVM doesn't have to create an instance of your class just to start running code.

One of the mistakes most often made by new Java programmers is attempting to access an instance variable (which means nonstatic variable) from the static main() method.

Example of this:

How to access Static Methods and Variables
  • Static variables have the longest scope; they are created when the class is loaded, and they survive as long as the class stays loaded in the Java Virtual Machine

We know that with a regular old instance method, you use the dot operator on a reference to an instance. For instance,

In this code, we instantiated a StaticAccess and assign it to the reference varialble sa and then use that sa to invoke method on the StaticAccess instance. 
In other words, the getSize() method is invoked on a specific StaticAccess object on the heap.

But this approach (using a reference to an object) isn't appropriate for accessing a static method, because there might not be any instances of the class at all.
That's the reason main method is always static.

So, the way we access a static method (or static variable) is to use the dot operator on the class name, as opposed to using it on a reference to an instance. For example,

The Java language also allows you to use an object reference variable to access a static member but later this is discouraged.

This is merely a syntax trick to let you use an object reference variable (but not the object it refers to) to get to a static method or variable, but the static member is still unaware of the particular instance used to invoke the static member. 

In the StaticVariableAccess example, the compiler knows that the reference variable sva is of type StaticVariableAccess, and so the StaticVariableAccess class static method is run with no awareness or concern for the StaticVariableAccess instance at the other end of the sva reference. 
In other words, the compiler cares only that reference variable sva is declared as type StaticVariableAccess.

Finally, remember that static methods can't be overridden! This doesn't mean they can't be redefined in a subclass, but redefining and overriding aren't the same thing.

The distinction between hiding a static method and overriding an instance method has important implications:

  • The version of the overridden instance method that gets invoked is the one in the subclass.
  • The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.

Initialization blocks
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {  
   // whatever code is needed for initialization goes here  

  • A class can have any number of static initialization blocks, and they can appear anywhere in the class body.
  • The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
  • A static initialization block runs once, when the class is first loaded it's means after a considerable amount of time after the class is loaded as Java make a distinction between class loading and class initialization.( thanks of Lew Bloch for making it more clear) It.An instance initialization block runs once every time a new instance is created.

Sample Output:

block 1
block 2
block 3

Static Nested Classes
Static nested classes referred to as static inner classes  but they really aren't inner classes at all, by the standard definition of an inner class.

While an inner class enjoys that special relationship with the outer class (or rather the instances of the two classes share a relationship), a static nested class does not.
It is simply a non-inner (also called "top-level") class scoped within another. So with static classes it's really more about name-space resolution than about an implicit relationship between the two classes.

A static nested class is simply a class that's a static member of the enclosing class:

class BigOuter {  
   static class Nested { }  
The class itself isn't really "static"; there's no such thing as a static class. 
The static modifier in this case says that the nested class is a static member of the outer class. That means it can be accessed, as with other static members, without having an instance of the outer class.

Sample Output
static inner class
static inner class 2

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...


  1. Thanks for your informative article. Java is most popular programming language used for creating rich enterprise, desktop and web applications. Keep on updating your blog with such informative post. J2EE Training in Chennai | JAVA Training in Chennai| JAVA Course in Chennai

  2. Excellent guidance,
    Your article provides step by step guidance about the use of the static keyword. the static keyword is a very important topic in java. we should know how and where to use it. what is the purpose to use the static keyword at different places? the static keyword is used in Java especially for memory management. we can use the static keyword with variables, methods, nested class, blocks.Static variables share the common memory area allocated at the time of class loading. we don't have a need for an object to invoke static methods. static blocks are used to initialize the static data members. static block is executed before the main method. I also visited a blog which provides a complete tutorial on How To Learn Java Programming easy and quick.

  3. Excellent post!!! In this competitive market, customer relationship management plays a significant role in determining a business success. That too, cloud based CRM product offer more flexibility to business owners to main strong relationship with the consumers.
    Best Institute for Cloud Computing in Chennai|Salesforce Training in Chennai|Salesforce Training institutes in Chennai

  4. "I very much enjoyed this article.Nice article thanks for given this information. i hope it useful to many pepole.php jobs in hyderabad.

  5. In near future, big data handling and processing is going to the future of IT industry. Thus taking Hadoop Training in Chennai | Big Data Training in Chennai will prove beneficial for talented professionals.

  6. I am technology Enthusiast. Your blog is really awesome, attractive and impressive. I like the way you think. it is very useful for Java SE & Java EE Learners. Your article adds best knowledge to our Java Online Training in India. or learn thru Java Online Training in India Students. or learn thru JavaScript Online Training in India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.

  7. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    Java Courses in Chennai|J2EE Training in Chennai

  8. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.
    Java Training Institute Bangalore

  9. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    Hadoop Training Institute In chennai


  10. Ciitnoida provides Core and java training institute in

    . We have a team of experienced Java professionals who help our students learn Java with the help of Live Base Projects. The object-

    oriented, java training in noida , class-based build

    of Java has made it one of most popular programming languages and the demand of professionals with certification in Advance Java training is at an

    all-time high not just in India but foreign countries too.

    By helping our students understand the fundamentals and Advance concepts of Java, we prepare them for a successful programming career. With over 13

    years of sound experience, we have successfully trained hundreds of students in Noida and have been able to turn ourselves into an institute for best

    Java training in Noida.

    java training institute in noida
    java training in noida
    best java training institute in noida
    java coaching in noida
    java institute in noida

  11. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    rpa training in chennai

  12. ERP-SAP-SD Training Centre in Noida

    CIIT Noida provides Best SAP Training in Noida based on current industry standards that helps attendees to secure placements in their dream jobs at MNCs. CIIT Provides Best ERP SAP Training in Noida. CIIT is one of the most credible ERP SAP training institutes in Noida offering hands on practical knowledge and full job assistance with basic as well as advanced level ERP SAP training courses. At CIIT ERP SAP training in noida is conducted by subject specialist corporate professionals with 7+ years of experience in managing real-time ERP SAP projects. CIIT implements a blend of aERPemic learning and practical sessions to give the student optimum exposure that aids in the transformation of naïve students into thorough professionals that are easily recruited within the industry.

    At CIIT’s well-equipped ERP SAP training center in Noida aspirants learn the skills for ERP SAP Basis, ERP SAP ABAP, ERP SAP APO, ERP SAP Business Intelligence (BI), ERP SAP FICO, ERP SAP HANA, ERP SAP Production Planning, ERP SAP Supply Chain Management, ERP SAP Supplier Relationship Management, ERP SAP Training on real time projects along with ERP SAP placement training. ERP SAP Training in Noida has been designed as per latest industry trends and keeping in mind the advanced ERP SAP course content and syllabus based on the professional requirement of the student; helping them to get placement in Multinational companies and achieve their career goals.

  13. Best Sap Training Center in Noida

    CIIT is the biggest ERP SAP training institute in Noida with high tech infrastructure and lab facilities and the options of opting for multiple courses at Noida Location. CIIT in Noida prepares thousands of aspirants for ERP SAP at reasonable fees that is customized keeping in mind training and course content requirement of each attendee.

    ERP SAP training course involves "Learning by Doing" using state-of-the-art infrastructure for performing hands-on exercises and real-world simulations. This extensive hands-on experience in ERP SAP training ensures that you absorb the knowledge and skills that you will need to apply at work after your placement in an MNC.

    CIIT Noida is one of the best ERP SAP training institute in Noida with 100% placement support. CIIT has well defined course modules and training sessions for students. At CIIT ERP SAP training is conducted during day time classes, weekend classes, evening batch classes and fast track training classes.

  14. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts, have a nice weekend!

    Hadoop Training in Chennai

  15. The information which you have provided is very good. It is very useful who is looking for Java online training Bangalore