• Post Reply Bookmark Topic Watch Topic
  • New Topic

Usage of Block  RSS feed

 
Maganti Suryanarayana Murthy
Greenhorn
Posts: 10
Eclipse IDE Hibernate Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I had one doubt regarding the block which is there in the code. When i remove the block i am getting errors. Why the blocks are used here? I am having doubt regarding it. The block is { states.add("VA"P) ........}
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is an instance initializer block. It's a bit unusual to use this; normally you would initialize member variables in a constructor.

Read more about it here: Initializing Fields
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Statements cannot directly exist in the class body. They should be present inside a method, constructor or the initialization block which you have shown.

Read about initialization block - http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Jespers' Jet fast
 
Manoj Kumar Jain
Ranch Hand
Posts: 198
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First thing you can't put executable code(I am not sure if this is correct word) directly in to the class, I meant that you can declare variables. place static blocks, inner class just inside the class but can't put like below

this is why you are getting error when you remove the curly braces from the code, just put that block inside some method and remove the braces, it will work fine(off course you have to take care of scope of the "states").
Second thing what I can understand is that the block mentioned here just inside the class is working as Initialization block and will initialize the values before the constructor is called. So this is one of the way to initialize the values in the variable. However I am not sure, may be someone else can elucidate it better.
 
Maganti Suryanarayana Murthy
Greenhorn
Posts: 10
Eclipse IDE Hibernate Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jesper.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!