File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initialization blocks in java

 
dileep keely
Ranch Hand
Posts: 108
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3908
9
Chrome Fedora Hibernate
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Firstly, please UseCodeTags when posting the code... You are defining "a" inside the static block hence not accessible from outside the block.
 
dileep keely
Ranch Hand
Posts: 108
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<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
Posts: 3908
9
Chrome Fedora Hibernate
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 215
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
During compilation, it requires variable declarations before definitions.
 
Rob Spoor
Sheriff
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your "a" is a local variable of the static block. I think you want to swap two lines:
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look on this
 
dileep keely
Ranch Hand
Posts: 108
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then make it static.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or: why have you got a static block in the first place?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic