Search code examples
javapreferences

What is the purpose of the "GET" methods second parameter?


I was reading the documentation . It looks not very intuitive to me that all get methods have two arguments . E.g.

abstract String get(String key, String def)
Returns the value associated with the specified key in this preference node.

It doesn't make sense. Why do we need the second argument?

I know when we feed the second argument with a value, that value gets assigned unless it's null. So okay one purpose would be to initialize a key-value pair. But I can also initialize the key value pair with put .

Here is a sample code

preferences.put("testKey", "testValue"); 
System.out.println(preferences.get("testKey", null)); // returns testValue 
System.out.println(preferences.get("testKey", "NOT NULL")); // returns testValue 
System.out.println(preferences.get("testKey", "WHATEVER")); // returns testValue 

So I just don't see a good use of the second parameter. I'm sure there are uses. So, why do we have that second parameter in Preferences?


Solution

  • The second argument is a default value (for when the preference isn't set at all). Without that argument, you would get null for an undefined property.