This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in static initialization and instance initialization blocks Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in static initialization and instance initialization blocks" Watch "Doubt in static initialization and instance initialization blocks" New topic
Author

Doubt in static initialization and instance initialization blocks

Satish K Patil
Greenhorn

Joined: Jun 24, 2007
Posts: 4
Hi All,
can anybody tell me the scope of the variables declared in static initializer.

Thanks,
Satish Patil
Deepak Jain
Ranch Hand

Joined: Aug 05, 2006
Posts: 637
The varaibles declared in static or instance initialization blocks will cease to exists once the block completes execution.
Thanks
Deepak


SCJP, SCWCD, SCBCD
Satish K Patil
Greenhorn

Joined: Jun 24, 2007
Posts: 4
But, Instance init blocks are used as a place to put code that all constructors in a class share. can you just please give eg for it.
Here,
when i try to print 'x'. it prints 0. why not 999 ?
[ August 05, 2007: Message edited by: Satish K Patil ]
Deepak Jain
Ranch Hand

Joined: Aug 05, 2006
Posts: 637
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18538
    
  40

when i try to print 'x'. it prints 0. why not 999 ?


That is because you have two different 'x' variables in your class. The first is the static variable that didn't get initialized, and hence, has the value of zero. And the second is the local variable declared in your initializer, which has already been mentioned, went out of scope, after it has been set to 999.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Doubt in static initialization and instance initialization blocks
 
Similar Threads
problem with accessing object in static block
compilation
STATIC INITAILIZATION
code called before constructor
STATIC INITAILIZATION