• 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

Initilization.

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Sample {
{
//System.out.println("Value of k is "+k);Illegal forward reference.
System.out.println("Value of a is "+getA());
}

//int i=j;Illegal forward reference.
int k=getJ();
int j=10;
public static void main(String[] args) {
System.out.println("Welcome to the real world."+new Sample().k);
}
public int getJ() {
return j;
}
public int getA() {
return a;
}
int a=10;
}
Output of the above program is
Value of a is 0
Welcome to the real world.0
------------------------------------------------
But, I thought it would be 10 for both as shown below.
Value of a is 10
Welcome to the real world.10

I was wrong can somebody explain why ?

Thanks!!
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Instance initializers, and initialization of instance variables, are executed in the order declared in the class. In both cases, they call methods, which accesses other instance variables, which haven't been initialized yet... so hence, they get the default value.

Henry
 
reply
    Bookmark Topic Watch Topic
  • New Topic