• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Initialiser

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<code>
class Init
{
System.out.println("Initializer");
}
class Init1
{
public static void main(String args[])
{
Init i=new Init();
}
}
</code>
if I compile the above mentioned class, I get the following compile-time error.

Init1.java:3: <identifier> expected
System.out.println("Initializer");
Init1.java:3: cannot resolve symbol
symbol : class out
location: class java.lang.System
System.out.println("Initializer");

But if I place the initilizer part in braces, I don't any errors and the program works well. Can anyone explain the reason behind it.
<code>
class Init
{
{System.out.println("Initializer");}
}
class Init1
{
public static void main(String args[])
{
Init i=new Init();
}
}
</code>
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Parag,
Yes the explanation is in your first example you are trying to call a method without creating a method. The only thing that you can place into a class but outside of a method are: class variable definitions, methods, and static blocks.
This brings us to your second example. What you have done is provided an unnamed block in the class scope (outside any method) that will be used by Java as an initializer for your class. This is not really useful in your example but it is extremely useful for initializing anonymous inner classes!
Manfred.
 
Parag Mokal
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Manfred,
Thank you for your reply, but I still have a doubt.
If I can declare only static blocks ,then the instance variable i shouldn't be allowed in the initialiser block given below
<code>
class Init
{
int i;
{
System.out.println("Initializer");
i++;
}
}
class Init1
{
public static void main(String args[])
{
Init i=new Init();
}
}
</code>
Does this imply that the blocks decared are not just static, but they can be instance blocks?
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic