This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes forward referencing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "forward referencing" Watch "forward referencing" New topic
Author

forward referencing

anita dhar
Ranch Hand

Joined: Jul 14, 2007
Posts: 69
can any one explain the flow of this programme

public class Myclass
{
private static int x = getValue();
private static int y = 5;
private static int getValue()
{
return y;
}
public static void main(String[] args)
{
System.out.println(x);
}
}
Ajay Chandravadiya
Greenhorn

Joined: Aug 06, 2007
Posts: 27
stumped to see the output! how is it initializing it?can someone explain to length please?
(good question buddy!)


SCJP Tiger Hunter 91%.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Isnt it obvious?

Step 1.
private static int x = getValue(); This makes a call to the getValue().
Step 2.
The getValue is coded to return the value of y. But at this stage y is yet to be initialized. So the default value of an int i.e. zero is returned. So we have the condition x=0
Step 3.
Now y is initialized with 5 and we have y=5;

Because the way the code is written, the impression is that the o/p will be 5.
[ August 23, 2007: Message edited by: Maneesh Godbole ]

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
anita dhar
Ranch Hand

Joined: Jul 14, 2007
Posts: 69
o/p of this programm is 0
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Originally posted by anita dhar:
o/p of this programm is 0


Of course the output is 0. I have explained in my post how it is 0.

Originally posted by maneesh godbole:
Because the way the code is written, the impression is that the o/p will be 5.
 
Consider Paul's rocket mass heater.
 
subject: forward referencing
 
Similar Threads
Mock question for static method?
illegal Forward Reference...
initialization of static variables
simple prog.
compile time constants