Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt Reg: initializing Variables with method call

 
Ravi Pinnaboyina
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How the output is printed as Zero.......
How is the value of i being resolved ?


private int i=getData();
private int j=10;

int getData()
{
return j;
}

public static void main(String arg[])
{
System.out.println(""+new ASample().i);
}
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The value of j is read in the method before it has been initialized.
 
Ravi Pinnaboyina
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So it means that i and j will only be declared first only then assignment starts...

i.ie.,

int a=10;
int b=10;

first a nd b will be declared only then they get initialized???
Am I right??
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The instance variables are in scope, but initialization occurs from top to bottom in the class definition. Since the call to the method accesses j before it is initialized, it has its default value.
 
Anton Uwe
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

is the same as
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic