• 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

scope of try() block

 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys..
Please take a look at the following code:

try()
{
int some_var = 1234;
some_class aClass = new some_class();
// some more code.
}
catch (SomeException e) {}

System.out.println(aClass.aVar + some_var); // gives the compiler error that variable some_var and object aClass not found.

1)Does variables or class instances created inside a try has a scope inside the try block only?

2) one more question guys, I have found different explanations about static variables.
I have read that static variables must be initialized and also, in another book that instance and automatic variables are initialized by the default constructor.
But when I don't initialize static variables in my code, it doesn't give a compiler error and defaults to a value of 0 !!

What is true? Since I dont get a error in my code, I beleive that static variables are initialzed to default of 0. But is it right?

Thanks a lot guys..

Regards,
Maduranga.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Maduranga Liyanage:

1)Does variables or class instances created inside a try has a scope inside the try block only?



Yes. This is true of any set of braces ("{}"): try blocks, blocks that form the bodies of loops, etc.


Since I dont get a error in my code, I beleive that static variables are initialzed to default of 0. But is it right?



Static variables are default-initialized just like instance variables.

You might have read about static final variables needing to be initialized. All final variables, by definition, have to be initialized somewhere -- static or otherwise.
 
Maduranga Liyanage
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Ernest..
Cleared the confusion. Thanks a lot..

Regards,
Maduranga.
 
reply
    Bookmark Topic Watch Topic
  • New Topic