Reputation: 120
I'm working with on a Java program that checks a config
file integrity.
On some point, I need to ensure that some mandatory values are setted up, either give it a default value.
So, I made a HashTable<String, String>
working like a key => value
table. On this table I store all the configuration lines on the file, and then I check it.
The problem comes when a specific value does not exist, for example:
String p = null;
/*...*/
//here I'm trying to get the LOG value
p = this.PAIRS.get("LOG");
if(p.equals(null) || p.equals("")){
//set default value
}
The problem is that I'm getting a NullPointerException, so it would be fine if someone can help me on how to determinate if this.PAIRS.get("LOG");
found a key or not...
Thanks!
EDIT: Solved, the right thing was using ==
and not an equals
.
Thanks again!
Upvotes: 0
Views: 69
Reputation: 2626
p = this.PAIRS.get("LOG");
This code return null if the key is not present and when you are doing below statement it will throw exception
if(p.equals(null) || p.equals("")){
//set default value
}
Instead check null first then do .equals
if(p==null || p.equals("")){
//set default value
}
Upvotes: 0
Reputation: 2534
If p is null, a NullPointerException
will be thrown because it is not an instance of an Object (so the equals method doesn't exist). Checking for null should be done the following way : p == null
Upvotes: 2