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)
Related
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've got a MVC based Java application with three models: Room, Student and StudentRoom.
StudentRoom contains an object of Room and Student.
Now I've got the problem that if my SQL query returns no result and I check the value of student's name like this
if(studentRoom.student.name != null) {
}
I'll get a NullPointerException and I don't know how to handle it.
Should I set Student.name = ""; since my query has no result?
if(studentRoom != null && studentRoom.student != null && studentRoom.student.name != null){
//.. Access student
}
Above solution looks a bit weird. you should better use getter/setter methods instead of directly accessing the objects.
Apart from that you can define methods like isStudentAvailable() in studentRoom to check whether it has Student in it or not.
Should I set Student.name = ""; since my query has no result ?
It completely depends on your use case. But I must say better to keep it null as it will raise the exception instead of passing the null check validations.
You might need a try/catch statement for that. Something like this :
try {
// do process here
} catch (NullPointerException npe) {
//to do if student is null
}
But take note, if there are any object that is inside the try statement, a NullPointerException would still be thrown. Hope this helps.
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
at java.util.LinkedList.get(LinkedList.java:474)
at com.comcast.guide.actionhandlers.MiniGuideActions.checkChannelFocus(MiniGuideActions.java:79)
at com.comcast.guide.functests.MiniGuideTest.checkChannelFocus(MiniGuideTest.java:34)`
I see there is an error here in this line
String currentAiringChannelNumber=moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER)== null ? "" : moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER);
E get method:
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
checkElementIndex method:
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
I am new to Java and I am not able to figure out where exactly should I change the code. Though the test case is executing according
to the flow it's returning this exception at the end and it's giving
the exception message at the end. Can someone help me fix it?
You need to check your LinkedList and make sure it is populated. Below is an example that I broke up into multiple if statements to make it a little more readable.
String currentAiringChannelNumber = "";
if (moduleModel.getGenerators() != null && moduleModel.getGenerators().size() > 0) {
currentAiringChannelNumber = moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER) == null ? "" : moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER);
}
This means you are trying to access the object at index 0 (so the first object), though there is no object in the LinkedList (its size is 0). So you need to add an object before trying to access it.
You can check if there's any object in the LinkedList with list.size() > 0 before trying to access an object in it.
You don't have elements in the "getGenerators()".
You probably will have to validate the existence of the element.
Try something like this
String currentAiringChannelNumber=moduleModel.getGenerators().isElementIndex(0) ? "" : moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER);
It seems getGenerator() is returning an empty list in your code. You need to make sure its size should be more than 0 before using get(0) on this list.
You could use a try-catch as it handles the exception being thrown.
use the following code:
String currentAiringChannelNumber; //Declare String object
try{ // Following block of code is ran, if an exception is thrown it will be caught and the the lines of code in the try block after the line of code that caused the exception to be thrown will not be run instead the code in the catch block will be ran.
currentAiringChannelNumber = moduleModel.getGenerators().get(0).getStringParam(TP_CHANNEL_NUMBER);
}
catch(Exception e){ //Catching any exception thrown, accommodates for NullPointerException, IndexOutOfBoundsException as well as all other exceptions that are thrown.
currentAiringChannelNumber = ""; //Code to handle predicted exceptions being thrown, which are the NullPointerException and IndexOutOfBoundsException.
}
Note: Code after try-catch statement will be run regardless of whether an exception is thrown while executing code in the try block.
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.
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;
}