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

Initialization question, pls reply

 
Bing Lu
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, can any1 tell me why the answer is 3? And pls give some
detailed explanation if possible, thanks
public class AQuestion
{
private int i = giveMeJ();
private int j = 10;
private int giveMeJ()
{
return j;
}
public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}
Answers

1.Compiler error complaining about access restriction of private variables of AQuestion.
2.Compiler error complaining about forward referencing.
3.No Compilation error - The output is 0;
4.No Compilation error - The output is 10;
 
Anbooo Sanygao
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. public class AQuestion
2. {
3. private int i = giveMeJ();
4. private int j = 10;
5. private int giveMeJ()
6. {
7. return j;
8. }
9. public static void main(String args[])
10. {
11. System.out.println((new AQuestion()).i);
12. }
13. }
When the above code is executed, the class AQuestion loads. class variable is supposed to get initialised. So it invokes giveMeJ. giveMeJ is supposed to return the j value. But at this point j is not assigned to a value 10. Since j is a class variable it is declared and initialised to '0'. So giveMeJ returns 0 and so i is assigned that value without any error.
hope this helps.

[This message has been edited by Anbooo Sanygao (edited November 02, 2000).]
 
yogesh sood
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But if u write i=j answer will be 2 option i.e compiler error
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic