• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Static initialiser

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
what is the practical use of such a block of code?
public class Test {
static {int a = 5; }
public static void main(String args[]) {
System.out.println(a);//illegal as a cannot be accessed out of the static block
}
}
Regards,
Kapil
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Static initializers are useful if you need to do something before class instaces are created. Typical usage is to initialize static members. For example, if your class had a static ConnectionHandle to a databse connection, you can establish the connection and initialize the handle in the static block.
About you error, the variable 'a' is declared within the static block and hence it is a local variable visible only within that block.
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Kapil
There is no use of defining variables inside static initializes as scope of that variable is only inside static block.
Basically static initializes get executed ONLY once when class is first loaded by JVM (before creating any instance of it). There are many use of static initializes�like
(1) To initialize static variables and static final variables. The static block executes only once when class is first loaded by JVM. It can�t pass checked Exception
(2) As Ajith said to establish database Connection
(3) To load libraries for native methods.

 
I need a new interior decorator. This tiny ad just painted every room in my house purple.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic