I was going through the concept of hoisting
in JavaScript where all function and variable declarations are hoisted before any execution takes place and this is the reason why a function is available before its actual declaration part.
Got me wondering how exactly it worked in Java.
Consider the following code:
package declarationOrder;
public class Main {
int num = init();
int init() {
return 5;
}
}
How exactly is the method init()
available for a call before its declaration part is reached?
Consider the other example:
package declarationOrder;
public class Main {
int num1 = num2; // compiler error
int num2 = 5;
}
How is it that the order of declaration of the variables plays a role here?
Why and how is the method treated differently?
The compiler follow an order to load contents(attributes, methods, static blocks, ..) in class in Java :
In your case the method is the first one which are loaded, then the class attributes.
about the attributes it will be loaded in order of initialization, you get an error in the second example because num2
is mentioned before num1
if you inverse the order it will work fine :
int num2 = 5;
int num1 = num2;
For more details take a look at 12.4.2. Detailed Initialization Procedure