aspose file tools*
The moose likes Java in General and the fly likes Initialization blocks in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Initialization blocks in java" Watch "Initialization blocks in java" New topic
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: 3775

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: 3775

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: 206
During compilation, it requires variable declarations before definitions.


www.cs-repository.info
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19544
    
  16

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 - OCEEJBD 6
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: 19544
    
  16

Then make it static.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36514
    
  16
Or: why have you got a static block in the first place?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Initialization blocks in java
 
Similar Threads
Object constructor and initialization
Initialization
questions about several File methods.
Error while executing the program
Initialization Blocks