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
main()



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!...

6 comments:

  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

    ReplyDelete
  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.

    ReplyDelete
  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

    ReplyDelete
  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.
    "

    ReplyDelete
  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.

    ReplyDelete