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

101 comments:

  1. 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
  2. "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
  3. 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
  4. 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
  5. 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
  6. 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
  7. Ver good explanation for Java static keyword
    Oracle training in chennai

    ReplyDelete
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. This comment has been removed by the author.

    ReplyDelete
  15. 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
  16. 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
  17. 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
  18. 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

  19. 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
  20. Thanks for providing wonderful information with us. Thank you so much.
    Data Science Course in Chennai

    ReplyDelete
  21. 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
  22. 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
  23. 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
  24. 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
  25. Other than Java there are many other easy option to go for like- Python, R etc are very in trend languages.

    href=” https://www.excelr.com/data-science-course-training-in-pune Data Science Course in Pune has it all.

    ReplyDelete
  26. Very informative blog post! I would like to thank for the efforts you have made in writing this great article. Thanks for sharing.


    ExcelR Data Science in Bangalore

    ReplyDelete
  27. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
    data analytics certification courses in Bangalore
    ExcelR Data science courses in Bangalore

    ReplyDelete
  28. Thanks for detailed Blog on Java, Very helpful in any field.

    Data Science Course In Pune

    ReplyDelete

  29. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!


    DATA SCIENCE COURSE MALAYSIA

    ReplyDelete
  30. I just found this blog and have high hopes for it to continue. Keep up the great work, its hard to find good ones. I have added to my favorites. Thank You.
    AI learning course malaysia

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

    ReplyDelete
  32. Thanks for the information shared.
    Please check this Data Science Certification

    ReplyDelete
  33. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
    Please check this Data Science Certification in Pune

    ReplyDelete
  34. Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live.
    javascript training in chennai | javascript training institute in chennai

    ReplyDelete
  35. cool stuff you have and you keep overhaul every one of us.
    Data Science Course in Pune

    ReplyDelete
  36. I am impressed by the information that you have on this blog. It shows how well you understand this subject.
    data analytics course malaysia

    ReplyDelete
  37. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    data science course malaysia

    ReplyDelete
  38. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!

    Please check this Data Science Course in Pune

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

    ReplyDelete
  40. I am impressed by the information that you have on this blog. It shows how well you understand this subject.
    Please check this Data Science Course

    ReplyDelete
  41. https://www.excelr.com/data-science-course-training-in-pune/

    Excelr provides Data Science Course. Data Science Course is Very Important Course in the Market. Now a Days Data Science Is Needed For Everyone. ExcelR offers the best Data Science certification online training in Pune along with classroom and self-paced e-learning certification courses. The complete Data Science course details can be found in our course agenda on this page.

    ReplyDelete
  42. Really very nice blog information for this one and more technical skills are improve,i like that kind of post.
    salesforce Training in Bangalore
    uipath Training in Bangalore
    blueprism Training in Bangalore

    ReplyDelete
  43. Salesforce training
    We at ikxbay are committed to provide industry ready and relevant skill set training to freshers and professionals. Attend 1st 2 live classes for FREE!!

    ReplyDelete
  44. Your blog has very useful information about this topic which i am looking now, i am eagerly waiting to see your next post as soon

    salesforce Training in Bangalore
    uipath Training in Bangalore
    blueprism Training in Bangalore

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

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

    ReplyDelete
  47. Thank you for this post. Thats all I are able to say. You most absolutely have built this blog website into something speciel. You clearly know what you are working on, youve insured so many corners. Thanks

    AI Training in Hyderabad

    ReplyDelete
  48. I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.
    a href="https://www.excelr.com/data-analytics-certification-training-course-in-pune/"> Data Analytics Course in Pune/">Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also.
    I have express a few of the articles on your website now, and I really like your style of blogging. I added it to my favorite’s blog site list and will be checking back soon…

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

    ReplyDelete
  50. IC Market Is The World's First Exchange That Allows You To Trade digital Currencies In Real-Time Using The Power Of Artificial Intelligence.

    ReplyDelete
  51. Do You Know Unexpected Things Happen When You Use Aximtrade Reviews Metatrader Platform For Trade? Know The Details

    ReplyDelete
  52. Great post I would like to thank you for the efforts you have made in writing this interesting and knowledgeable article.
    data science training institute in hyderabad

    ReplyDelete
  53. One of the most important tasks a data scientist performs on an almost daily basis is to collect, manipulate, and analyze data.

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

    ReplyDelete
  55. Superb Post.Thanks for sharing such an informative blog.
    Java Classes in Nagpur

    ReplyDelete
  56. Great Post. it is useful article, Thanks for sharing such an informative blog.
    reactjs training in hyderabad

    ReplyDelete