Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of the initialization in Java

Tags:

java

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.

like image 483
John Doe Avatar asked Mar 25 '12 23:03

John Doe


People also ask

How do you initialize in Java?

You can initialize the variable by specifying an equal sign and a value. Keep in mind. You can initialize the variable by specifying an equal sign and a value. Keep in mind that the initialization expression must result in a value of the same (or compatible) type as that specified for the variable.

What is object initialization in Java?

Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

How do you initialize a class variable in Java?

To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.


Video Answer


1 Answers

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.

like image 102
twain249 Avatar answered Oct 03 '22 06:10

twain249