• 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

jquest

 
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what is the output of the following
public class Test
{
private int i = givemej();
private j = 10;
private int givemej(){
return j;
}
public static void main (String args[])
{
System.out.println((new Test().i));
}
}
output is 0
can someone explain how
shouldn't the output be 10
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
when class is instantiated, the first thing happens is the initialization of class members in the order they declared. here 'i' will be initialized first which causes call to givemej() which returns j with '0' cuz the statement 'int j=10;'hasnt been executed yet. this causes value of 'i' to be printed zero.
 
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by reehan ishaque:
when class is instantiated, the first thing happens is the initialization of class members in the order they declared. here 'i' will be initialized first which causes call to givemej() which returns j with '0' cuz the statement 'int j=10;'hasnt been executed yet. this causes value of 'i' to be printed zero.


if what reehan has explained above is the reason for the output, then that means that all the variables are first of all initialized to their default values when a class is instantiated.Irrespective of their declaration and initialization at the same line as in the code.Which means when i is later initialized with the result of givemej()method, j was not a undefined variable for the class.instead j was having the initial value 0(which later got changed to 10).
this is what i think.can some1 tell me if my reasoning is correct or not?
rajashree.
reply
    Bookmark Topic Watch Topic
  • New Topic