Question

I have written a piece of code :

public class Child{
int y ;
private static final int z = getZ();

static {
    System.out.println("The value of z is "+z);
}

public int getX(){
    System.out.println("get x");
    return 10;
}

public int getY(){
    Child ch = new Child();
    System.out.println("get y");
    ch.y = getX();
    return y;
}

public static int getZ(){
    System.out.println("get z");
    return new Child().getY();
}

public Child(){
    System.out.println("Child constructor");
}


public static void main(String...args){
    Child ch = new Child();
    System.out.println("the value of z in main is "+z);
}
}

And the output is :

get z
Child constructor
Child constructor
get y
get x
The value of z is 0
Child constructor
the value of z in main is 0

Can anyone please explain me why the value of z is 0 and not 10 ?

EDIT:- Thanks everyone , I got the answer to my first question . I still have a doubt , as far as I know the static blocks are executed after the class is loaded and before the first object of the class is instantiated . Well then the SOP("The value of z is "+z) should have been executed before SOP("Child constructor") ! Ain't it ?

Was it helpful?

Solution

Look at getY():

public int getY(){
    Child ch = new Child();
    System.out.println("get y");
    ch.y = getX();
    return y;
}

The first three lines are irrelevant - they don't change the value of y in this instance, which is what gets returned.

You're creating an awful lot of pointless objects in frankly spaghetti code, called while initializing the same class that you're constructing instances of. I suggest you try to keep your code a lot simpler than this. Static initializers should be avoided where possible to start with, let alone ones that go all round the houses to do no useful work.

OTHER TIPS

because getY() sets ch.y to 10, but returns the value of this.y.

In GetY you return this.y which never gets set.

On getY() you returned the uninitialized y variable instead of the Child ch instance.

Its because inside getY() method you are constructing a new CHild object and you are assigning 10 to that instance of variable y and when you return y that will be the current instance variable y. I hope it explains .

To your second point, static fields and static blocks are initialized / executed in textual order.

Eg:

public class StaticTest()
{
  static
  {
    System.out.println("s1 in block 1 :" + s1);
  }

  private static String s1 = "s1";

  static
  {
    System.out.println("s1 in block 2 : " + s1);
  }

  public static void main(String args[])
  {
    new StaticTest();
  }
}

The output of this will be -

s1 in block 1 :

s1 in block 2 : s1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top