| Author |
Initialization blocks in java
|
dileep keely
Ranch Hand
Joined: Jun 28, 2010
Posts: 91
|
|
In general:
1))static variable is intialized before an instance is created.
2)once a class is loaded the static blocks run
3)initialization blocks run after instance is created
In the above case my understanding is :
a-->is given a default value
a-->is assigned with a value 10
But this is not happening,I get an error as (identifier expected)
I am missing an importantinformation,please help me out.
|
 |
Vijitha Kumara
Bartender
Joined: Mar 24, 2008
Posts: 3670
|
|
|
Firstly, please UseCodeTags when posting the code... You are defining "a" inside the static block hence not accessible from outside the block.
|
SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
|
 |
dileep keely
Ranch Hand
Joined: Jun 28, 2010
Posts: 91
|
|
<updated with code tags>
but,why is that the default value is not assigned for a.
ERROR:java:6: variable a might not have been initialized
system.out.println(a);
|
 |
Vijitha Kumara
Bartender
Joined: Mar 24, 2008
Posts: 3670
|
|
dileep keely wrote:...but,why is that the default value is not assigned for a...
Only instance and class variables are automatically initialized to default values, but not local variables.
|
 |
John Eipe
Ranch Hand
Joined: May 23, 2008
Posts: 205
|
|
|
During compilation, it requires variable declarations before definitions.
|
www.cs-repository.info
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Your "a" is a local variable of the static block. I think you want to swap two lines:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Abimaran Kugathasan
Ranch Hand
Joined: Nov 04, 2009
Posts: 2066
|
|
|
Have a look on this
|
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
|
 |
dileep keely
Ranch Hand
Joined: Jun 28, 2010
Posts: 91
|
|
|
No,I don't want to swap the above two lines.Because a non- static variable can't be referenced from the static .
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
Then make it static.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
|
Or: why have you got a static block in the first place?
|
 |
 |
|
|
subject: Initialization blocks in java
|
|
|