0

I have a value in Java that is always null but I don't understand why, because I am setting the value of the variable using the class constructor.

I have code like such:

Driver driverClass = new Driver("<file path redacted>");

And then the below:

String cfgFilePath;

public Driver(String cfgFile) {
    this.cfgFilePath = cfgFile;
}

private ArrayList<String> keys = getKeys(cfgFilePath);
private String a1 = keys.get(0);
private String b1 = keys.get(1);

For some reason, IntelliJ IDEA says that cfgFilePath is always null. I am initializing it with the Driver class constructor, so why is it null? When I run the program I get a null pointer exception.

Emily
  • 82
  • 1
  • 10

1 Answers1

1

Move the initialization of keys, a1 and b1 to your constructor like:

public Driver(String cfgFile) {
    this.cfgFilePath = cfgFile;
    this.keys = getKeys(cfgFilePath);
    this.a1 = keys.get(0);
    this.b1 = keys.get(1);
}

private ArrayList<String> keys = new ArrayList<>();
private String a1;
private String b1;
rieckpil
  • 10,470
  • 3
  • 32
  • 56
  • This worked, thanks! But I'd like to know how. I read the other post's explanation of the order of initialization but I am still confused as to why that means that those variables are always null at all times. – Emily Aug 27 '18 at 03:45
  • These attributes are null because your attribute `keys` does need `cfgFilePath` to work properly. You set `cfgFilePath` within your constructor but the `keys` attribute tries to initialize its attribute **before** you call the constructor and at this time the `cfgFilePath` is not set (the String attribute is `null` per default if it's not initialized). You have a predefined order of execution you want to achieve -> 1. set `cfgFilePath` and 2. initialize the other attributes. – rieckpil Aug 27 '18 at 07:06