This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund 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
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Static Initializer + Variable Declaration" Watch "Static Initializer + Variable Declaration" New topic
Author

Static Initializer + Variable Declaration

Manoj Macwan
Greenhorn

Joined: Aug 03, 2007
Posts: 22
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?
Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 12929
    
    3

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 7 API documentation
Scala Notes - My blog about Scala
Manoj Macwan
Greenhorn

Joined: Aug 03, 2007
Posts: 22
Hi Jesper,
Thanks for your reply.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Static Initializer + Variable Declaration
 
Similar Threads
Doubt in static initialization and instance initialization blocks
forward reference question
primitive value
static block understanding
quick question from the book Head First Java