Initialization Order in Java

I know this is a very simple topic, so if this is a duplicate question, provide a link.

Say there is the following code:

public class Point {

    int x = 42;
    int y = getX();

    int getX() { 
        return x; 
    }

    public static void main (String s[]) {
        Point p = new Point();
        System.out.println(p.x + "," + p.y);
    }
} 

It outputs: 42,42

But if we change the order in which the variables appear:

public class Point {

    int y = getX();
    int x = 42;

    int getX() { 
        return x; 
    }

    public static void main (String s[]) {
        Point p = new Point();
        System.out.println(p.x + "," + p.y);
    }
} 

It outputs: 42,0

I understand that in the second case, the situation can be described as something like: "Well, I do not know what the return value of x is, but there is some value." What I don't quite understand is how x can be seen here without being seen along with its meaning. Is it a matter of compile time and runtime? Thanks in advance.

+5
source share
3 answers

int Java 0. , , ints x y, 0, y x, 0, x 42,

+7

int 0 .

+2

, () x y 0

JVM Point ( ) 0 x y.

y 0, x 42 ( )

+1

All Articles