javapropertiesgetproperty

Calling getProperty on a Properties instance is returning null instead of value


Why is the code below returning null, instead of true?

I can see that the property is being set based on the {TEST=true} output.

Java code:

import java.util.Properties;

public class Test {

    public static void main(String[] args) {
        System.out.println("1");
        Properties props = new Properties();
        props.put("TEST", true);
        System.out.println(props);
        System.out.println(props.getProperty("TEST"));
        System.out.println("2");
    }
}

Program output:

1
{TEST=true}
null
2

Solution

  • Use setProperty() instead of put(). getProperty() and setProperty() operate on Strings. See the JavaDoc, here: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#setProperty-java.lang.String-java.lang.String-

    If you look at the source code for the Properties class, you should see that it does an instanceof check on the value of the property that it retrieves in getProperty(). If the property value is not a String, it returns null.