• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

forward referencing

 
anita dhar
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
stumped to see the output! how is it initializing it?can someone explain to length please?
(good question buddy!)
 
Maneesh Godbole
Saloon Keeper
Posts: 11061
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
anita dhar
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
o/p of this programm is 0
 
Maneesh Godbole
Saloon Keeper
Posts: 11061
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic