I have encountered a peculiar effect when initializing fields in Java. My code:
import java.util.Locale;
public class Vehicle {
String name;
static Locale locale;
String localeString = locale.toString();
static int number;
int numberVehicle;
String localSign = localeString + numberVehicle;
public Vehicle(String name) {
this.name = name;
}
static{
locale = Locale.getDefault();
}
{
numberVehicle = ++number;
}
@Override
public String toString() {
return "Vehicle{" +
", name=" + name +
", numberOfVehicle=" + numberVehicle +
", localSign='" + localSign +'\'' +
'}';
}
}
When I initialize 3 cars and print it, I get:
Vehicle{, name=citroen, numberOfVehicle=1, localSign='pl_PL0'}
Vehicle{, name=opel, numberOfVehicle=2, localSign='pl_PL0'}
Vehicle{, name=zyguli, numberOfVehicle=3, localSign='pl_PL0'}
The numberVehicle is increased as intended however the localSign, which should contain numberVehicle: String localSign = localeString + numberVehicle;
is always with "0' as the numberVehicle
would not be increased. When I debug it with breakpoints it shows the value to localSign is assigned when numberVehicle is initialized withh 0. That seems to me strange, because I did assign the correct value in the instance initializiation block
{
numberVehicle = ++number;
}
As far as I know (also found here: https://stackoverflow.com/a/15413629/13612259 ) initialization blocks are executed prior to constructor, so I do not understand why String localSign = localeString + numberVehicle;
is executed when numberVehicle is not assigned with proper value. I would be grateful if someone could help me by indicating what I have missed.