This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I do a condition with a value when it is null and when it is not null.
The time where this value is null I got the java.lang.NullPointerException.
How could I deal with this in order to dismiss this exception?
I need the condition when the value is null and when it is not.
You get a NullPointerException when you try to call a method using a variable that is null. Simple example:
String s = null;
int len = s.length(); // NullPointerException because s is null
So you should check if the variable is null before calling any method on it, for example:
int len;
if (s == null) {
len = 0;
}
else {
len = s.length(); // Safe, s is never null when you get here
}
Note that a NullPointerException is usually easy to solve. Carefully look at the stack trace of the exception; it tells you exactly in which line of your code the exception happens. Check what could be null in that line of code, and check if you're calling a method on something that might be null. Add a check (or prevent that the relevant thing can ever be null in another way).
Simply do a proper check for the value being null. A conditional such as
if (value == null)
will never raise a NullRefePointerException. It's only if you try accessing whatever a null reference points to that you get the exception. So calling methods or accessing other instance members of the object is out of the question.
Use an if to check for the variable not being null and then use an else code block for when it is null.
if (variable != null)
{
// Code when object is not null
}
else
{
// Code when object is null
}
The null pointer is only thrown when you try and use the null value.
For example,
variable.method();
But you should always avoid a situation where a null pointer could occur.
As stated by other posters, if you do not expect the s reference to be null here then fix the bug that causes the reference to be null in the first place. However, if it is valid that the reference could be null, you can also do the following using the ternary operator (Java 5 on)
int len = (s == null) ? 0 : s.length;
Note: the brackets are optional, but they make it a bit more readable in my opinion.
It is a really confusing question, but:
boolean isNull = true;
if (value != null) {
isNull = false;
}
Related
Is it possible to do something like this?
dog.setIsBarkingIndicator(mailman.getIsAtDoor() != null && mailman.getIsAtDoor().equals("N") ? false : true);
But for what I researched, this is basically the same as: dog.setIsBarkingIndicator(mailman.getIsAtDoor() == null || !mailman.getIsAtDoor().equals("N"))
So it actually sets it at false if its null or not equals to "N"? Did I understand correctly?
Is there any way to check the null without using the if condition?
Thank you!
So, your logical condition is basically like the following:
mailman.getIsAtDoor() == null || !mailman.getIsAtDoor().equals("N")
You can change the instance which performs equal operation. The one instance here is a constant string literal - that means it is never a null value, so it can always perform an equality operation. The condition you are looking for is here:
!"N".equals(mailman.getIsAtDoor()).
This approach does not require from you to check null value of the mailman.getIsAtDoor().
Perhaps the dog or the mailman variable is null. So please try the following code:
if (dog != null && mailman != null)
{
dog.setIsBarkingIndicator(!mailman.getIsAtDoor().equals("N"));
}
I have code that is throwing a null pointer exception.
Here is my code:
StringBuilder strName = new StringBuilder(100);
strName.append(someClassObject.getFirstName().getContent().get(0));
strName.append(" ");
strName.append(someClassObject.getLastName().getContent().get(0));
name = strName.toString();
It is throwing a null pointer exception when trying to retrieve the last name at someClassObject.getLastName().getContent().get(0).
My question is, how to proceed with best practice in catching the null pointer.
What I was thinking something similar to this:
String lastName = (String) someClassObject.getLastName().getContent().get(0);
if(lastName == null) {
lastName = "";
LOGGER.warn("Last name is null");
}
strName.append(lastName);
Which I am hesitant since I have to convert the lastName object to a String and then create logic to check if it is null or not.
Or
try {
strName.append(someClassObject.getLastName().getContent().get(0));
} catch(NullPointerException e) {
LOGGER.warn("Last name of the conusmer is null");
}
The exception only occurs when you call a method withing an already null object (you can debug to see which object is the root null).
In case your null is the someClassObject.getLastName()
You could check nullity in java with this oneliner:
String lastName = (someClassObject.getLastName() == null) ? "" : someClassObject.getLastName().getContent().get(0);
All the overloads of StringBuilder.append() are null safe. They append the text null if the input is null. Hence, you must be getting the NPE from any one of the methods in the expression someClassObject.getLastName().getContent().get(0).
If these methods are not null safe, then it is better to check for null before chaining the next method than catching NPE. This way you might have to write some boilerplate code, but execution time will be cheaper. Exceptions are costly, even if they are handled.
The other option is, if possible change the methods getLastName(), getContent(), and get(), to make them null safe - return empty value instead of throwing NPE. In this case you have to think how the other users of these methods will react if you make this change.
You can use Java 8 Optional to check if object is not null at each level of someClassObject
, as follows:
StringBuilder strName = new StringBuilder(100);
Optional<List<String>> option = Optional.of(someClassObject)
.map(SomeClassObject::getLastName).map(LastName::getContent);
if (option.isPresent()) {
strName.append(option.get().get(0));
}
I would recommend to use the ifPresent option instead, removing the need for your if statement.
Something like:
option.ifPresent(e -> strName.append(option.get().get(0)))
I have the following piece of code:
map = db_.treeMapCreate(validMapName_)
.keySerializer(Serializer.LONG)
.valueSerializer(Serializer.LONG)
.make(); //mapDB
protected void onTaskCompletion(TaskInfo task)
{
long startBlk = task.blkId;
long count = task.count;
for (int i=0; i < count; ++i)
{
long blk = startBlk + i;
Long oldVal = map.get(blk); //NPE here
...
...
}
}
How is it possible to get an NPE while autoboxing? I can understand getting an NPE on unboxing i.e. if I had:
long oldVal = map.get(blk)
then that can throw an NPE.
Edit: Map isn't null. To be more specific, inside the BTreeMap code of mapDB, this line gets executed:
if(key==null) throw new NullPointerException();
In case someone wants to take a look: BtreeMap of mapDB
Line: 1024
Partial stacktrace:
java.lang.NullPointerException
at org.mapdb.BTreeMap.get(BTreeMap.java:1024)
at org.mapdb.BTreeMap.get(BTreeMap.java:1013)
at com.service.onTaskCompletion(TaskHandler.java:312)
I'm unable to reproduce it so I cannot give a minimal, verifiable example.
I have tried to run it so that I perform a get() for a key that doesn't exist, and it DOESN'T give an NPE.
I think the problem is that you are looking at the wrong version of the BTreeMap code. If you go back to the previous commit of this class, line 1024 is not:
if(key==null) throw new NullPointerException();
but:
while(!A.isLeaf()) {...}
where A is set by:
BNode A = engine.get(current, nodeSerializer);
This makes much more sense. Basically, null is returned from engine.get. How that is possible is beyond my understanding, but this could very well be a bug of mapdb itself.
The NPE could be due to any of the following:
Map being null
Passing a null value to get method (not the case)
Passing a key to get() that does not exist in MapDB
I am more concerned about number 3 in here because, if you pass a key that does not exist then null is returned and trying to store null in Long oldVal cause the exception (I believing that something as follow happens):
Long l = new Long(null); //NPE
To find one whether it is #3 do the following
//if key don't exist MapDB returns null
if(map.get(blk) != null) { //not null } else { //yes null}
To find out if map is null obviously as pointed out by others, you do as follow
//invoking get on a null can cause NPE too, so another reason
if(map != null) { // not null } else { //yes null}
To support the fact that #3 could be causing the NPE, see this post with a similiar issue.
Looking into the docs for BTreeMap the get(Object) below
public V get(Object key)
Specified by:
get in interface Map<K,V>
Overrides:
get in class AbstractMap<K,V>
Looking at Map and AbstractMap the get(Object key) is specified as follow:
Returns the value to which the specified key is mapped, or null if
this map contains no mapping for the key.
get(Object) of Map<K,V> and AbstractMap<K,V> returns null if no mapping is found. It is also capable of throwing NullPointerException. So #3 could still be the case that there is no entry for the key passed to get method in map.
NPE is because map object is null and you are referring to get() method of null,thereby NPE.
Do check of map for null and you will find your solution.
if(map!=null){
long oldVal = map.get(blk);}
else {
System.out.println("Map is null");
}
I see only one possibility: The variable "map" is null.
Your code sample is incomplete, as you didn't show and where "map" is really initialized.
I have this code to bring up a message if my list is empty. The first time it works and I get my JOptionPane. However, if I add an item to the list and then remove it and hit remove if the list is empty again, I get NullPointerException error. Is there a reason for this?
The culprit is :
String selectListValue = selectionList.getSelectedValue().toString();
and also
if(selectListData.size() > 0)
// Null pointer exception will be thrown is selctionData is Null
In this you are not checking if selectionList is null. Ideally you should check if a object is null before performing any operation on it.
Correct Way :
if(selectionList != null)
{
String selectListValue = selectionList.getSelectedValue().toString();
// perform yoour operations
}
Also change :
if(selectListData != null && selectListData.size() > 0)
Product p = dao.checkProduct(pnumber);
ExpensiveProduct ep = dao.checkexpensiveProduct(pnumber);
if ((p.getNumber() == null)&&(ep.getNumber()==null) ){ // java.lang.NullPointerException
//do something
}else{
//do something
}
Why this statement giving java.lang.NullPointerException
Do I have any other way to check this?
The only non-trivial possibility where this code can throw NPE is pnumber being Integer where checkProduct() or checkexpensiveProduct() expects int (or similar).
Other trivial reasons are dao or p being null (easy to check).
Try it like this:
if ((p != null) && (p.getNumber() == null) && (ep != null) && (ep.getNumber()==null) ){
NullPointerExceptions (NPEs) occur when you call a method or access a property of a null object.
To check for nulls, you could print the values of your variables before you try to use them, or step through your program with a debugger and check what the variables' values are when you reach the line where the exception happens.
EDIT:
Regarding your comment
i need to check p.getNumber() and ep.getNumber() both returning null and get ture on that statement
your existing code
if ((p.getNumber() == null)&&(ep.getNumber()==null) )
is already doing that. Since you're getting an NPE on that line, p itself is null, or ep is null, or both. You should examine your checkProduct() and checkexpensiveProduct() methods, where p and ep are set, to see if they're working correctly.
check your p variable and ep variable .One of them is null.check
why
dao.checkProduct(pnumber)
or
dao.checkexpensiveProduct(pnumber); is returning null
What line is giving the NullPointerException? Be sure that p or ep are not null.