I know, it’s a very basic topic, so if it is a duplicate question, please provide a reference.
Say, there is a 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 of the appearance of the variables:
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: “Okay, I don’t know what the returned x value is, but there is some value”. What I don’t completely understand is how x may be seen here without being seen along with its value. Is it a question of compile time and run time? Thanks in advance.
When you create an
intin Java it is automatically initialized to0. So what the second code does is create two intsxandyset them both to0then setyto the value ofxwhich is0then set x to the value42.