• 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 Initializer + Variable Declaration

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have one doubt regarding the Static Initiliser block, and the variable declared in that block.

I have 2 different scenario:
1)
static{
static int x = 999;
System.out.println("x:"+x);
}
2)
static int x;
static{
int x = 999;
System.out.println("x:"+x);
}
The Scenario 1 gives the compile time error, while scenario 2 not.

In the first Scenario we are declaring the static variable inside the Static block, while in the second one we are declaring the static variable outside the Static block and using them.

Why we can't declare the static variable inside static block.
What might be the problem?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You cannot declare static variables inside a static initializer block, just like you cannot declare static variables inside a method.

You must declare member variables (static or not) at the class level, not inside a block of code like the static initializer block.
 
Manoj Macwan
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jesper,
Thanks for your reply.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic