To understand why it works like you saw, you have to get acquinted with
initializators. Also, you have to be aware there is a difference between
declaration and
definition.
Let's start with the latter. Declaration is when you tell the compiler what variables (or fields) you want to use. Example for this is
Definition is when the space is allocated for the object.
There is one small problem with the above: these are terms in the C language, and while it works well there, it does not really apply for
Java; I am pretty sure, that even in the first case, at least the space for the reference is allocated. Also there may be a problem with primitives and the String class. However, I will use these terms in this post.
Now for the initializators. Besides constructors, Java also has a place to put initializator code to: they are called initializators. There are two types of them: static and non-static. The example class below has one of both (also a contructor).
The static initializator runs when the class is loaded into memory. The non-static initializator runs when the class is instantiated,
just before the constructor.
There is only one static and one non-static initializator for a class. You can write more, but the compiler will just group them. Also it does not matter where you write them in your class; the commands will run according to the last paragraph. The order of the commands will be based on their order in the file, however. So,
will be changed to
compile time.
Now, we are almost there! One last thing you have to know, is that the compiler also separates declaration from definition. So, even if you write
, it will be changed to
If you put the above together, I guess you see now what happens in your program. So, the answers to your questions are:
1. Declarations are always "known" before ANY instructions (including definitions). So of course name is known to your program.
2. You know now that in the initializator, instructions are placed in the order they are written in the source. So here, test = new Test() runs first (calling the constructor!), then name = "abc";. If you swap the two lines, "abcxyz" will be written. But keep in mind this scenario is a bit tricky, as your static initializator instantiates the class in the first line, thereby running the non-static initializator and calling the constructor
before going to the second line of the static ini.
(Also, it writes "nullxyz", because a null String is written as "null" and not "")
[ November 18, 2006: Message edited by: David Nemeskey ]