• 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

Variable Initialization

 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I thought the answer should be 10 but the given answer is 0.
Can anyone explain if this is the correct flow of sequence when a class is loaded??
1. All static initializers are called
2. All static variables are initialized
3. All intance variables are initialized
4. Constructor is called

TIA
[ June 17, 2004: Message edited by: Sudhakar Krishnamurthy ]
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Instance initializers are executed from top to bottom. That means that this line:



Executes prior to this line:



Therefore, i is being assigned the value of j before j has been assigned a value. By default, j is 0 prior to its initialization so that, 0, is what is assigned to i.

You can find complete details about object initialization in the JLS, §12.5 Creation of New Class Instances.
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If the code is changed to

int i=j;
int j=10;

the code will not compile. The compiler will complain abt forward referencing.. because java always try to avoid usage of uninitialized variables..

- Harish
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic