• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the use of static block

 
V Aravind
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the use of static block in java.
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One use is to hold code that you want to run immediately when the class is loaded,
before any objects are instantiated. For an inheritance tree, this means that the
order of execution of the static blocks is from subclass on up. (Execution of any
non-static blocks is from superclass on down.) How is this useful? I'd just say,
very special situations.

Jim ... ...
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
V Aravind wrote:What is the use of static block in java.


Mostly used for initialized static variables.
 
Zhiwei Huang
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jim Hoglund wrote:One use is to hold code that you want to run immediately when the class is loaded,
before any objects are instantiated. For an inheritance tree, this means that the
order of execution of the static blocks is from subclass on up. (Execution of any
non-static blocks is from superclass on down.) How is this useful? I'd just say,
very special situations.

Jim ... ...


So if I have

the output would be BA?
 
Vicky Mehta
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the output would be BA?

ouptut is AB
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I thought so, but my bad. Hi Vicky and welcome to JavaRanch.
Below, with output, is a bit different than the example above. Jim ... ...
 
Vicky Mehta
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jim.
I found another good example in JavaRanch Forums.... Glad to be part of this forum
http://www.coderanch.com/t/497400/java-programmer-SCJP/certification/static-instance-initializer-blocks-inheritance
 
akhter wahab
Ranch Hand
Posts: 151
Java MyEclipse IDE Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vicky Mehta wrote:Thanks Jim.
I found another good example in JavaRanch Forums.... Glad to be part of this forum
http://www.coderanch.com/t/497400/java-programmer-SCJP/certification/static-instance-initializer-blocks-inheritance


Good One
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic