• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

jquest

 
sona gold
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • 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
 
reehan ishaque
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • 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.
 
rajashree ghatak
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic