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

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

    ReplyDelete
  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

    ReplyDelete
  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

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

    amazon-web-services-training-in-bangalore

    ReplyDelete
  10. Ciitnoida provides Core and java training institute in

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

    ReplyDelete
  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

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

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

    ReplyDelete
  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

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

    ReplyDelete
  16. Very good brief and this post helped me alot. Say thank you I searching for your facts. Thanks for sharing with us!
    Click here:
    Angularjs training in chennai

    Click here:
    angularjs training in bangalore

    Click here:
    angularjs training in online

    Click here:
    angularjs training in Annanagar

    ReplyDelete
  17. This is such a great post, and was thinking much the same myself. Another great update.
    Click here:
    Microsoft azure training in chennai
    Click here:
    Microsoft azure training in online
    Click here:
    Microsoft azure training in tambaram
    Click here:
    Microsoft azure training in chennai

    ReplyDelete
  18. 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.
    Devops Training in Chennai

    Devops Training in Bangalore

    Devops Training in pune

    ReplyDelete
  19. I always enjoy reading quality articles by an individual who is obviously knowledgeable on their chosen subject. Ill be watching this post with much interest. Keep up the great work, I will be back
    python training in tambaram
    python training in chennai
    python training in annanagar
    python training in chennai

    ReplyDelete
  20. Well done! Pleasant post! This truly helps me to discover the solutions for my inquiry. Trusting, that you will keep posting articles having heaps of valuable data. You're the best! 
    Blueprism training in tambaram

    Blueprism training in annanagar

    Blueprism training in velachery

    ReplyDelete
  21. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.
    Data science training in tambaram | Data Science training in anna nagar
    Data Science training in chennai | Data science training in Bangalore
    Data Science training in marathahalli | Data Science training in btm

    ReplyDelete
  22. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.

    Data Science course in Chennai
    Data science course in bangalore
    Data science course in pune

    ReplyDelete
  23. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    health and safety courses in chennai

    ReplyDelete
  24. This comment has been removed by the author.

    ReplyDelete
  25. I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.

    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  26. Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
    fire and safety course in chennai

    ReplyDelete
  27. I have been searching for quite some time for information on this topic and no doubt your website saved my time and I got my desired information. Your post has been very helpful. Thanks.

    QlikView Training in Chennai
    Core Java Training
    J2EE Training in Chennai

    ReplyDelete
  28. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.


    AWS Training in BTM Layout |Best AWS Training in BTM Layout

    AWS Training in Marathahalli | Best AWS Training in Marathahalli

    ReplyDelete
  29. Amazon has a simple web services interface that you can use to store and retrieve any amount of data, at any time, from anywhere on the web. Amazon Web Services (AWS) is a secure cloud services platform, offering compute power, database storage, content delivery and other functionality to help businesses scale and grow.For more information visit.
    aws online training
    aws training in hyderabad
    amazon web services(AWS) online training
    amazon web services(AWS) training online

    ReplyDelete
  30. Thanks for sharing this valuable information to our vision. You have posted a worthy blog keep sharing.

    Guest posting sites
    Technology

    ReplyDelete
  31. Amazing blog you have given and you made a great work.surely i would look into this insight and i hope it will help me to clear my points.please share more information's.
    AngularJS Training Institutes in Vadapalani
    Angular JS Training courses near me
    Angularjs courses in Bangalore
    Angular Training in Bangalore

    ReplyDelete
  32. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.

    rpa training in chennai
    rpa training in bangalore | best rpa training in bangalore | rpa course in bangalore | rpa training institute in bangalore | rpa training in bangalore | rpa online training

    ReplyDelete
  33. I always enjoy reading quality articles by an individual who is obviously knowledgeable on their chosen subject. Ill be watching this post with much interest. Keep up the great work, I will be back
    Java training in Bangalore | Java training in Indira nagar

    Java training in Bangalore | Java training in Rajaji nagar

    Java training in Bangalore | Java training in Marathahalli

    Java training in Bangalore | Java training in Btm layout

    ReplyDelete
  34. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
    Online DevOps Certification Course - Gangboard
    Best Devops Training institute in Chennai

    ReplyDelete
  35. Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up. 
    python training institute in marathahalli
    python training institute in btm
    Python training course in Chennai

    ReplyDelete
  36. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
    python training institute in marathahalli
    python training institute in btm
    Python training course in Chennai

    ReplyDelete
  37. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject

    rpa training in chennai |best rpa training in chennai|
    rpa training in bangalore | best rpa training in bangalore
    rpa online training

    ReplyDelete
  38. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject

    rpa training in chennai |best rpa training in chennai|
    rpa training in bangalore | best rpa training in bangalore
    rpa online training

    ReplyDelete
  39. Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....
    Best Devops Training in pune

    ReplyDelete
  40. I just needed to record a speedy word to express profound gratitude to you for those magnificent tips and clues you are appearing on this site.
    iosh safety course in chennai

    ReplyDelete
  41. Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live. I have bookmarked more article from this website. Such a nice blog you are providing ! Kindly Visit Us @ Best Travels in Madurai | Tours and Travels in Madurai | Madurai Travels

    ReplyDelete

  42. I’m planning to start my blog soon, but I’m a little lost on everything. Would you suggest starting with a free platform like Word Press or go for a paid option? There are so many choices out there that I’m completely confused. Any suggestions? Thanks a lot.
    AWS Training in Bangalore electronic city| AWS Training in Bangalore Cost
    AWS Training in Pune with placements | AWS Training in Pune
    AWS Training Course in Chennai |Best AWS Training in Chennai tnagar
    Best AWS Amazon Web Services Training in Chennai | Best AWS Training centers in Chennai
    AWS Online Training in india | AWS online training cost

    ReplyDelete
  43. I’m planning to start my blog soon, but I’m a little lost on everything. Would you suggest starting with a free platform like Word Press or go for a paid option? There are so many choices out there that I’m completely confused. Any suggestions? Thanks a lot.
    AWS Training in Bangalore electronic city| AWS Training in Bangalore Cost
    AWS Training in Pune with placements | AWS Training in Pune
    AWS Training Course in Chennai |Best AWS Training in Chennai tnagar
    Best AWS Amazon Web Services Training in Chennai | Best AWS Training centers in Chennai
    AWS Online Training in india | AWS online training cost

    ReplyDelete
  44. You are doing a great job. I would like to appreciate your work for good accuracy
    Regards,
    Best Devops Training in Chennai | Best Devops Training Institute in Chennai

    ReplyDelete
  45. Information from this blog is very useful for me, am very happy to read this blog Kindly visit us @ Luxury Watch Box | Shoe Box Manufacturer |  Candle Packaging Boxes

    ReplyDelete
  46. Thanks for providing wonderful information with us. Thank you so much.
    Data Science Course in Chennai

    ReplyDelete
  47. Information from this blog is very useful for me, am very happy to read this blog Kindly visit us @ Luxury Watch Box | Shoe Box Manufacturer |  Candle Packaging Boxes

    ReplyDelete
  48. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information.
    Devops Training in Chennai | Devops Training Institute in Chennai

    ReplyDelete
  49. I prefer to study this kind of material. Nicely written information in this post, the quality of content is fine and the conclusion is lovely. Things are very open and intensely clear explanation of issues

    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training


    ReplyDelete
  50. I love the blog. Great post. It is very true, people must learn how to learn before they can learn. lol i know it sounds funny but its very true. . .

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  51. This is very good content you share on this blog. it's very informative and provide me future related information.
    R Training Institute in Chennai | R Programming Training in Chennai

    ReplyDelete
  52. 1. many peoples want to join random whatsapp groups . On this website you can join unlimited groups . click and get unlimited whatsapp group links

    ReplyDelete
  53. 3. if you want girls mobile numbers then this website is best for you . you can visit on this website and get their information and you also can meet with thrm and go for a date . click here to use our website --- 100% free online dating website

    ReplyDelete
  54. 2. if you are searching for free unlimted tricks then visit now on Uvoffer.com and get unlimited offers and informations.
    film ka naam whatsapp puzzle answer 🐡🐡🐡 +🐘+3+🏹+🏚+πŸ’” =

    ReplyDelete
  55. Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live. I have bookmarked more article from this website. Such a nice blog you are providing ! Kindly Visit Us @ Best Travels in Madurai | Tours and Travels in Madurai | Madurai Travels

    ReplyDelete