• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

puzzle

 
Oscar Garcia
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone explain why the ff. code produces this output?
I thought i could get 99 as an output...
class puzzle{
static private int i = getK();
static private int k = 99;

static private int getK(){
return k;
}
public static void main(String[] args){

System.out.println("i-->" + i);

}
}//end class
//output: i-->0
 
R K Singh
Ranch Hand
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
As per JLS The static initializers and class variable initializers are executed in textual order.
so when static int i is get initialized by calling getK(), static int k has NOT been initialized as it comes after var 'i', so it has a default value of '0', which get perinted.
HTH
 
rajiv nair
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The static initializers and class variable initializers are executed in textual order.
If you change the code as
class Puzzle
{
static private int k = 99;
static private int i = getK();

static private int getK()
{
return k;
}
public static void main(String[] args)
{
System.out.println("i-->" + i);
}
}
you will get 99 as output.
 
Anup Engineer
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rajiv, you correctly pointed out the output of the above code, but I am not sure of the explanation as yet.
By "textual order" do we mean that i will be initialized before k, provided both are static? if so, why just putting k=99 above the i=getK() method initialized i to 99?
Could you elaborate a little, Thanks!
 
Mario Levesque
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anup,
The variables will be initialized by order of execution one line at a time, ie. line of code on top first then line of code below after. This must be what others refer to as "textual order" it does not mean alphabetical order.
So when you assign a variable to a literal then call a method after, it works as expected, but when you call the method before the variable has been initialized to a literal you get omething else. That's because the default of zero is substituted in the variable inside the method since it has not been declared and initialized yet.
Does this help?
Ask again if not.
Cheers,
 
Anup Engineer
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That does help Mario..the "textual order" confused me..but now I understand it.
Cheers!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic