Android AL-Khatib Android AL-Khatib - 13 days ago 7
Java Question

Explain the order OR priority of executing the java code?

I have these two classes

public class B {
int mB = 5;

public int getBValue(){
return mB;
}
}

public class A {
int mA = b.getBValue();

public static void main(String [] args){
B b = new B();
System.out.println(mA);
}
}


The compiler says "can't find symbol b". I understand that code first executing from the main method and line after line in order. So when the compiler reads code it first goes to "
B b = new B();
" then b becomes defined. Is it true? Is wrong from scope?

Second state that I understand:

public class B {
static int mB = 5;

public static int getBValue(){
return mB;
}
}

public class A {
static int mA = B.getBValue();

public static void main(String [] args){
System.out.println(mA);
}
}


This state works correctly. Static belong to the class itself, not to any object. So all static loaded and initialized when program run.

So where the key point between these two states?

Answer

I understand that code first executing from the main method and line after line in order.

That is entirely correct. However, variables from main (or from any other method, for that matter) do not become available for use in field initializers of class A, which are executed in their own context as part of class constructor.

when complier read code goes first to B b = new B(); then b become defined it's true

Yes, b becomes defined for the rest of its scope, i.e. up until the closing brace of main.

so where the key point between these two state?

Take-away lesson from this exercise is that field initializers can freely access static fields and methods; they cannot access anything else, including constructor parameters and local variables of any method. Moreover, parameters and locals are off-limits to everything outside their own methods.

Comments