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

Another qstn for you all... Just to enforce the point..

 
maha anna
Ranch Hand
Posts: 1467
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another qstn for you all... Just to enforce the point..
I know, most of MUST be knowing this already. But recently I didn't find any discussions related to this. So I am posting this here.
regds
maha anna.
Which version of class Test compiles and runs successfully?
<pre>
class Test {
static int i = peek();
static int peek() { return j; }
static int j = 1;
public static void main(String[] args) {
}
}
class Test {
static int i = j;
static int peek() { return j; }
static int j = 1;
public static void main(String[] args) {
}
}
</pre>
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Maha,
I tried your code with JVM. The first part compiles and runs fine while the second one gives compilation error,"Can't make forward reference to j".
I don't understand why both of them are behaving this way?
Your help will be much appreciated.
Thanks.
 
maha anna
Ranch Hand
Posts: 1467
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The static/instance floating block initialization and class vars intializations are done in the SAME ORDER as they appear in a java program. The rule for this initialization is ,
1. The initialization expression on the RHS(RightHandSide) of any assignment statement SHOULD NOT DIRECTLY refer to another var which comes afterwards (below). Otherwise the compiler complains that it is a forward reference, which you can not do.
2. But acesses to class variables by methods are not checked in this way. You CAN do forward reference THROUGH methods. In this case the pre-defined value of the forwarded ref , which is the DEFAULT VALUE is used.
So in the foll. code peek() method returns the DEFAULT value of j which is 0 (not 1)is returned. Because the assignment of j comes BELOW the defn. of peek() method.
regds
maha anna
<pre>
class Test {
static int i = peek();
static int peek() {
return j;
}
static int j = 1;
public static void main(String[] args) {
}
}
</pre>
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a bunch Maha for detailed explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic