wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Initialization question, pls reply Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Initialization question, pls reply" Watch "Initialization question, pls reply" New topic
Author

Initialization question, pls reply

Bing Lu
Ranch Hand

Joined: Oct 10, 2000
Posts: 42
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

Joined: Oct 04, 2000
Posts: 45
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

Joined: Aug 31, 2000
Posts: 108
But if u write i=j answer will be 2 option i.e compiler error


If its green its biology if its stinkks its chemistry if it has numbers it is Maths and if it doesn't work its TECHNOLOGY
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Initialization question, pls reply