Tuesday, 5 September 2017

Static, instance blocks in Java

Static and Instance Block

Static and non-static blocks are more of the same in syntax. A block can be static if we write a static keyword before the block.



Static Block:

  • java's static block is a group of statements that gets executed when the class gets loaded by ClassLoader
  • It is generally used to create static resources when the class is loaded.
  • static block code gets only once at the time of class loading
  • static blocks always gets executed first, We can have multiple static blocks, but it doesn't make much sense
  • static block can't access non-static variables and methods.

Non-Static/ Instance Block:
  • Instance block will get executed on each object creation but,  before the constructor. 
  • It can access static as well as non-static variables and methods






No comments:

Post a Comment