This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Initializer + Variable Declaration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static Initializer + Variable Declaration" Watch "Static Initializer + Variable Declaration" New topic

Static Initializer + Variable Declaration

Manoj Macwan

Joined: Aug 03, 2007
Posts: 24

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

I have 2 different scenario:
static int x = 999;
static int x;
int x = 999;
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?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14952

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Manoj Macwan

Joined: Aug 03, 2007
Posts: 24
Hi Jesper,
Thanks for your reply.
I agree. Here's the link:
subject: Static Initializer + Variable Declaration
It's not a secret anymore!