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?
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.
You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks.
Java offers two types of initializers, static and instance initializers.
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.
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
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