• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

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
 
expectation is the root of all heartache - shakespeare. tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic