aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes code problem!!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "code problem!!!!" Watch "code problem!!!!" New topic
Author

code problem!!!!

kriti sharma
Ranch Hand

Joined: Feb 16, 2001
Posts: 160
hi all,
can anyone please help me with this code.

class A
{
int i=s();
int j=10;
int s()
{
return j;
}
public static void main(String str[])
{
A a=new A();
System.out.println(a.i);
}
}

ans - 0 is the output but why?
Pam Doucette
Greenhorn

Joined: Mar 13, 2001
Posts: 27
This is an unexpected result, and I'm not sure why it is happening, but you can get the expected result if you initialize and assign a value to j before you run the s() method on i.
class A
{
int j=10;
int i = s();
int s()
{
System.out.println("j is " + j);
return j;
}
public static void main(String str[])
{
A a=new A();
System.out.println("a.j is " + a.j);
System.out.println("a.i is " + a.i);
}
}
Consequently, I think that the instance variables are initialized first (ints to 0s) and then the values are assigned in order of their declaration. Since s() is called to return j before j is assigned a value of 10, it is returning 0. This is just a theory, though - maybe someone has a more definitive answer?
Michael Burke
Ranch Hand

Joined: Jul 29, 2000
Posts: 103
I think your right Pam and you're example proves it.
kapil apshankar
Ranch Hand

Joined: Dec 17, 2000
Posts: 66
I think you are right pam
------------------
Hope this helps. Correct me if I am wrong.
Cheers ,
Kapil


Hope this helps. Correct me if I am wrong.<p>Cheers <img src="smile.gif" border="0"> ,<br />Kapil
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
You are correct. The order of initialization of variables in initializers is described in the JLS here:

12.4.1 When Initialization Occurs
The intent here is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (�8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.


"JavaRanch, where the deer and the Certified play" - David O'Meara
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: code problem!!!!