Checking if an object is null before converting to String - java

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)))

Related

Handle Nullpointerexception after SQL query has no result

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.

Null Pointer Exception in If condition

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.

Format a Date, allowing null

I'm trying to print a Date, just the way DateFormat.getDateTimeInstance() does it.
format throws a NullPointerException when passing null, so I've been wondering if there is a different approach that would return null (or "null") instead?
Something I'd call instead of
Date d = null;
System.out.println(d==null ? null : DateFormat.getDateTimeInstance().format(d));
You could just wrap the call inside a utility method :
public class DateUtils {
public static String formatDateTime(Date dateOrNull) {
return (dateOrNull == null ? null : DateFormat.getDateTimeInstance().format(dateOrNull));
}
}
private constructor and javadoc omitted for brevity.
What's the problem with your existing code?
null is kind of a special case, and you've decided that you want one particular behaviour in this case (returning "null") instead of another particular behaviour (throwing an NPE). It's arguably cleaner to express this via switching at the top level rather than burying this logic within the formatting method.
It might be a little cleaner to use a full if-else rather than a tertiary operator, though, to make it clearer that there are two distinct branches (normal, and special-cased null):
if (d == null) {
return "null"; // or whatever special case
}
else {
return DateFormat.getDateTimeInstance().format(d);
}
The return value in the null case should be made clear in your method's javadocs, too.

java.lang.NullPointerException [duplicate]

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;
}

String says its not null but then later throw NullPointerException

OMG. I have a little project to do and the Strings are killing me!
Now, I have a String which is null (is taken the value from invoking getParameter() from a servlet).
The problem is that, I'm trying to see if it's null, and, even if it's null, in the program is telling me that is not null, but later in program, when I'm using the variable, I receive a exception saying the variable is null.
System.out.println("In " + ID); // in console: In null
if ((ID == null) || (ID == "null") || ID.equals(null) || **ID.equals("null")**)
{
// after I put the 4th condition, the if is working right (WHAT IS THE PROBLEM?)
System.out.println("==null");
this.ID = "";
}
else
{
System.out.println("!=null");
this.ID = ID;
}
System.out.println("After " + ID);
What I'm doing wrong?
Only the forth condition is working! What about the rest(except second one, because that condition i put it because I was desperate)
I taught ID == null or ID.equals(null) will be ok, but no.
Edit:
The problem is that, I'm getting the value of the ID from a form(form 1 let's say- usually). But in this case, I'm using form 2 which doesn't have any ID inputs, so ID must be null and not "null"
ID.equals("null")
Clearly, ID contains the four-letter string "null". So it's not null (the value for "nothing").
See the Java glossary for more on the null constant. Basically a variable has the value null if it does not reference any object. The string "null" is an object however, namely an instance of the class String, and in this case the variable ID references this object.
(Note that by convention Java variables start with a lower case letter, and acronyms like ID are written completely lower case, so write id instead of ID.)
Here are the four tests you've tried. The first and the fourth are the only ones that you should need.
ID == null : is the field 'ID' null?
ID == "null": is the ref for the field 'ID' the same as the newly allocated String "null"? This should generally return false.
ID.equals(null): this should always return false - conceptually were this ever true you should throw a NullPointerException.
ID.equals("null"): is the value of the String 'ID' the same as the value of the String "null"?
Since you get the string from a servlet i can say that this is normal.
Java converts a null string to a "null" string on some conditions.
Obviously the string you retrieve is not a null value, but it is a 4 char string "null"
Why don't you try debugging? Or just see what does this return:
System.out.println("Length of ID: " + ID.Length);
Edit: If you don't get exception here, this means that the string is not null and also output "Length of ID: 4" will mean that the string is really ID = "null"
EDIT2: Alright it seems that some guys do not understand what is going on here and they say how can a null string be "null" in some conditions in Java? They find it riddiculus. I prefer them to try this on java:
String abc = null;
String xyz = "hello";
System.out.println(xyz + abc);
The output will be "hellonull" Nothing else...
Also here we have a servlet. There is a null data. Servlet sends the null data as "null" what should it do? An empty string? Come on!!! "
Looks like it is return the String "null" and not a Null Object.
If the result was actually a null then
ID == null
would suffice, but as is mentioned the string value of ID is obviously "null" rather than the null object.
You should use .equals when comparing strings rather than using ==
This blog explains more about his:
http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
So, "null" does not equal null, in Java.
If the value is coming from a Servlet then the container is most likely converting an empty form field to a blank string. You should do a check against null and blank ("").
if (value==null || value.equals(""))
Alternatively you can use String's isEmpty() method:
if (value==null || value.isEmpty())
If the value of your variable ID is the string literal "null", then I would guess that there is a bug earlier in the code when you retrieve it using the getParameter() method. According to the docs, the getParameter() method is supposed to return null (the null reference) if there is no value for the specified name. This indicates that somewhere you are doing an operation that converts the result to the string literal, perhaps concatinating with the empty string (i.e. ID + "" ; )

Categories