5

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.

1
  • 1
    Check JLS Commented Mar 25, 2012 at 23:48

3 Answers 3

7

When you create an int in Java it is automatically initialized to 0. So what the second code does is create two ints x and y set them both to 0 then set y to the value of x which is 0 then set x to the value 42.

Sign up to request clarification or add additional context in comments.

Comments

2

int has 0 as a default value.

Comments

1

So at compile time, the compiler is generating instructions to set aside space (memory) for x and y and to set their values to 0

At runtime, the JVM populates the Point object (assigns it memory) and assigns memory and initial 0 values for x and y.

Then, the runtime initialization code starts executing and sets y to 0 and then x to 42 (in the second case)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.