• 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

static initializer question from khalid mughal

 
Ranch Hand
Posts: 445
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a question from Khalid Mughal's Book pg.268 about static initializers.
public class MyClass{
public static void main(String args[]){
MyClass ki=new MyClass(l);//l is 0 here,how??
}
static int i=5;
static int l;
int j=7;
int k;
public MyClass(int m){
System.out.println(i+","+j+","+k+","+l+","+m);
}
{j=70;l=20;}// Instance Initializer (initializing l)
static { i=50;} //static Initializer
}
My question is are not the static & instance initializers first run before the constructor body is executed?If so, the value of l sholud be 20 not 0.Please explain.
Also is the Sarga site shifted anywhere else?Coz I simply could not open www.sarga.com/java/jac.htm. IS there any mirror site for this?
Do let me know.
Thanks all,
Vedhas.

 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Vedhas,
The output is <code>50,70,0,20,0</code> so 'l' is '20'.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, Vedhas, remember that order of code execution are as follows:

In our case, we use the value "l" before step 3, which means "l" still not initialized at that moment, and thus default value 0 is used for the parameter of the constructor. After that, "l" is initialized to 20 at step 4.
Hope it helps.
Guoqiao

Originally posted by Vedhas Pitkar:


 
Vedhas Pitkar
Ranch Hand
Posts: 445
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanx Jane @ Sun, u heleped me clear my doubts. I guess reading the question carefully is really important.Thanks,
Vedhas.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic