I was excepting the value of i: 20, but it is giving me the value 0, Why I am getting value 0 in java 1.7 version?
public class InvalidValue {
private int i = giveMeJ();
private int j = 20;
private int giveMeJ() {
return j;
}
public static void main(String[] args) {
System.out.println("i: " + new InvalidValue().i);
}
}
The instance variables are initialized in the order of appearance. Therefore private int i = giveMeJ() is executed before j is initialized to 20, and therefore i is assigned the default value of j, which is 0.
Java keeps the default constructor if no constructor is present, Hence let us keep the default constructor in the code to understand the code flow and value of i and j at each step:
See Below code:
package com.java;
public class InvalidValue {
private int i = giveMeJ();
private int j = 20;
// Default Constructor
public InvalidValue() {
super();
// Second Print: inside Constructor[i= 0, j= 20]
System.out.println("inside Constructor[i= " + i + ", j= " + j + "]");
}
private int giveMeJ() {
// First Print: inside giveMeJ[i= 0, j= 0]
System.out.println("inside giveMeJ[i= " + i + ", j= " + j + "]");
return j;
}
public static void main(String[] args) {
// Third Print: i: 0
System.out.println("i: " + new InvalidValue().i);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With