posted 18 years ago
hello,
i'll try, anyone pls jump in if my explanation is incorrec
public class Test4 {
static{
x=10;
// x++; To avoid Compile err replace x by Test4.x;
}
static int x=15;
public static void main(String args[]){
System.out.println(x);
}
}
This will result in 15 being outputted. Why?
you are not instantiating any Test4 class. so compiler will read the value you have given to x at line 15.
And what if you replace the main method lik ethis ?
public static void main(String args[]){
Test4 t = new Test4();
System.out.println(t.x);
}
result will still be 15. because when instantiating an object, like i said in my prev post, Static variables and static blocks will be initialized when the class itself is loaded. IIRC they will also be executed in order from top to bottom.
if instead you write followign code,]
public class Test4 {
static int x=15;
static{
x=10;
// x++; To avoid Compile err replace x by Test4.x;
}
public static void main(String args[]){
Test4 t = new Test4();
System.out.println(t.x);
}
}
output will be 10 (the static block is 'executed' after the static variable has been defined.. remeber? top to bottom... )
Now, why uncommenting x++ will result in an error? if i m correct, it is for the same reason i have just explained. the variable x is defined after the static block
it is the same principle if you have a code like this
public class Test4 {
int i = j;
int j = 0;
..
}
if you replace the code with this:
public class Test4 {
static int x=15;
static{
x=10;
x++; //To avoid Compile err replace x by Test4.x;
}
public static void main(String args[]){
Test4 t = new Test4();
System.out.println(t.x);
}
}
code will compile an run fine.
// x++; To avoid Compile err replace x by Test4.x;
i cannot exactly explain this, unfortunately, but x in this cas will be seen as a class variable, (and i guess if you instead use x++, compiler will consider that an instance variable)...
hth, and if some one can clarify better the last issue (the one of the x++) i will appreciate it too
HTH
marco