0

Hey Guys i am new to java programming.I tried to experiment with java classes and what i have done is that i have created an instance variable x and then y which copies that values of x. Then I define a constructor which takes the value or x as an argument. Now when i try to print the value of y it gives the value as 0 while or x it gives 5. Why the problem is happening ? When we use new keyword and the Constructor then only all the instance fields are created so i feel like after we use

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package test;
/**
 *
 * @author Mridul
 */
public class Test {
int x;
int y=x;
Test(int a)
{
    x=a;

}
void print()
{
    System.out.println(x); 
}
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Test ob=new Test(5);
        ob.print();
        System.out.println(ob.y);


        // TODO code application logic here
    }

}

Output
5
0

When we use new keyword and the Constructor then only all the instance fields are created so i feel like after we use

Test ob=new Test(5); 

Then only all the codes in the class(x,y=x) should run and it shouldn't have created the problem. Please Help

Mridul Mittal
  • 51
  • 1
  • 6

4 Answers4

0

When you create a new instance of Test, this is happening (in order):

int x; // x = 0
int y=x; // y = 0
Test(int a)
{
    x=a; // x = your a value
}

=> community wiki, feel free to....

0

This here:

int y=x;

happens once, before your constructor is executed.

Thus the ctor changes the value of x; but y stays at its previous value. (x gets initially the default value of 0; that goes into y; and then the ctor is executed and changes x to the value of a).

And please note: this has nothing to do with "dynamic allocation". new causes three things:

  • memory is allocated
  • fields of the new object are init'ed
  • the specified constructor is invoked

(see here for more details). If you want y to have the same value as x; just do

public class Test final int x, y;

Test(int incoming) {
  x = incoming;
  y = incoming;
}
Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

When you call a constructor using new, then Java begins to construct the newly allocated object. The values of the instance fields (in your case of field x and field y) are determined by a set of rules.

  • First, the instance fields are initialized. x has the default value (0); y gets the value of x, which is 0.
  • Then, in the constructor, x is set to the value of a.

y is still 0, because it gets its value before x is set to the value of a.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
0

new operator is for automatic memory allocation, to allocate the needed memory for an object, you must use the new operator.

0xDEADBEEF
  • 590
  • 1
  • 5
  • 16