Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this code giving me 0 as value of i, instead of 20? [duplicate]

Tags:

java

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);
    }
}
like image 450
Technical Activity Avatar asked Jun 12 '16 13:06

Technical Activity


2 Answers

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.

like image 124
Eran Avatar answered Oct 10 '22 01:10

Eran


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);
    }
}
  1. Step 1: void main initiate the call by new InvalidValue().i,
  2. Step 2: i and j will be initiated by default value 0 then InvalidValue() constructor will be invoked and then super(); will be called,
  3. Step 3: Now the constructor (assign value to instance attributes) invokes private int i = giveMeJ(),
  4. Step 4: giveMeJ() method will be invoked and here value of i is 0 also value of j is 0, hence this method will return 0,
  5. step 5: i initialize by 0, now flow will go to private int j = 20,
  6. step 6: 20 value will be assigned to j,
  7. step 7: now the compiler will return to constructor (Step 3) and then it will print sysout statement (inside Constructor[i= 0, j= 20]),
  8. step 8: now compiler will return to void main() (Step 1) and it will print sysout statement (i: 0)
like image 42
Sanjay Madnani Avatar answered Oct 09 '22 23:10

Sanjay Madnani