Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

static intializers  RSS feed

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.What are static initializers.
2.how is static block different from static method.
3.where is a static block created - heap or satck
4.does the static variable stay even after the method using it dies (as in case of final variables which are created on the heap) soumyaharish@rediffmail.com
 
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

1.What are static initializers.


It is a block of code that is executed only once, when the class is loaded.
For example,

In the above code the static block will be executed when the class loaded thus initializing the variable staticData

2.how is static block different from static method.


Static blocks are not methods actually. Unlike a method, the static blocks doesn't have a name, aruguments, access modifiers and return value. These blocks can never be called in a program. The only time this block is executed is when the class is loaded.

3.where is a static block created - heap or satck


4.does the static variable stay even after the method using it dies (as in case of final variables which are created on the heap)


I can answer these questions, but it will certainly confuse you more!

Any experts out there (Cindy / Jim / ....)
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


3.where is a static block created - heap or satck


They're not created anywhere -- they're code, not data. They live, like all Java code, entirely outside either the heap or stack.

Saying that "final variables are created on the heap" is misleading. Final variables exist, again, in that mysterious native memory area which is outside either the Java stack or the Java heap.
In any event, the lifetime of a static variable is as long as the class it belongs to is loaded. If the class is unloaded, the static variable goes away.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!