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