Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java instance variables initialization with method

I am a little bit confused about the following piece of code:

public class Test{

  int x = giveH();
  int h = 29;

  public int giveH(){
     return h;
  }

  public static void main(String args[])
  {
      Test t = new Test();
      System.out.print(t.x + " ");
      System.out.print(t.h);          
  }
}

The output here is 0 29, but I thought that this has to be a compiler error, because the variable h should have not been initialized when it comes to the method giveH(). So, does the compilation go through the lines from top to bottom? Why is this working? Why is the value of x 0 and not 29?

like image 255
bucky Avatar asked Nov 12 '15 10:11

bucky


People also ask

Can instance variables be initialized in Java?

Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

Which method is used to initialize the instance variable of a class?

You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks.

What are the two ways of initializing variables in Java?

Java offers two types of initializers, static and instance initializers.

How do you initialize a variable in a class in Java?

To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.


1 Answers

The default value of int is 0 (see here). Because you initialize x before h, giveH will return the default value for a int (eg 0).

If you switch the order like this

int h = 29;
int x = giveH();

the output will be

29 29
like image 86
ThomasThiebaud Avatar answered Oct 13 '22 21:10

ThomasThiebaud