This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes jquest Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "jquest" Watch "jquest" New topic
Author

jquest

sona gold
Ranch Hand

Joined: Feb 14, 2001
Posts: 234
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


sona<br />SCJP
reehan ishaque
Ranch Hand

Joined: Mar 25, 2001
Posts: 54
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

Joined: Mar 10, 2001
Posts: 151
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: jquest