Originally posted by Animesh Shrivastava:
public class CDummy
{
static
{
xx = 9;
}
public static void main(String args[])
{
System.out.println("xx = " + xx);
}
static int xx = 7;
}
I don't know what you're doing wrong, but this piece of code just works fine here (like I expected)
And Kedar Dravid statement is true. First the static variable is created and set to it's default value, so in this case, 0.
After that, the classloader will process the class from top to bottom. It will assign xx to 9 first, after that it will assign xx to 7.
So int xx = 7; isn't executed at the same time.
Also note that as someone already said in the this
thread, you can only set a value of a variable before it is created in the source code. You can't read it:
{int i = j;} //read a variable
int j = 0;
==> it will give an error
{j = 0;} //set a variable
int j;
==> this will work
This is the sequence that the classloader follows:
1. static + instance variables declaration + default value assigment
2. static initializer block execution + static variable value assignment
3. static void main
4. initializer block execution + instance variables value assignment
5. constructor
Anyway, this is what I found after
testing this. If you want, I can place here an code example to show the sequence that the classloader follows.
[ February 14, 2005: Message edited by: Kristof Janssens ]