This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

code problem!!!!

 
kriti sharma
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think your right Pam and you're example proves it.
 
kapil apshankar
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you are right pam
------------------
Hope this helps. Correct me if I am wrong.
Cheers ,
Kapil
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic