There is a possiblity that this may be a dupicate question.
I initialize a String variable to null.I may or may not update it with a value.Now I want to check whether this variable is not equal to null and whatever I try I get a null pointer exception.I can't afford to throw nullpointer exception as it is costly.Is there any workaround that is efficient.TIA
If you use
if (x == null)
you will not get a NullPointerException.
I suspect you're doing:
if (x.y == null)
which is throwing because x is null, not because x.y is null.
If that doesn't explain it, please post the code you're using to test for nullity.
I guess you are doing something like this,
String s = null;
if (s.equals(null))
You either check for null like this
if (s == null)
A better approach is to ignore the null and just check for the expected value like this,
if ("Expected value".equals(s))
In this case, the result is always false when s is null.
String is immutable
#Test(expected = NullPointerException.class)
public void testStringEqualsNull() {
String s = null;
s.equals(null);
}
#Test
public void testStringEqualsNull2() {
String s = null;
TestCase.assertTrue(s == null);
}
I am comparing s==null only
can you show the code snippet that you have written
s==null will never throw a NPE
if you are checking whether "s" is null, then do not apply a dot(.) after "s". Doing that would throw NullPOinterException, as applying dot(.) means that you are trying to access on a pointer location which is basically null at the moment !
Also try to use library functions that check whether a string is null or empty. you may use StringUtils.isEmpty(s) from apache library which checked both
Related
Here's my code:
if (!quizDescs[0].isEmpty()) {
mDescText.setText(quizDescs[0]);
} else {
mDescText.setVisibility(View.INVISIBLE);
}
So, when this code runs, and the if condition returns true, everything is fine and dandy, however, if it returns false, it says there's a NullPointerException, and points me to the line of code containing the if statement.
Am I checking the condition right? Why is it returning a NullPointer?!
ANSWER:
if (quizDescs[0] == null) {
mDescText.setVisibility(View.INVISIBLE);
} else {
mDescText.setText(quizDescs[0]);
}
if quizDesc[0] is String, you can do
if(!StringUtility.isEmptyOrNull(quizDesc[0])){
mDescText.setText(quizDescs[0]);
}else {
mDescText.setVisibility(View.INVISIBLE);
}
By the way,
Null and being empty is not same
Consider
String s; //Initialize to null
String a =""; //A blank string
Its always a good practise to use
try{
//Your code here..
}catch(Exception e){
e.printStacktrace();
}
If either quizDescs or quizDescs[0] are null, you'll get a NullPointerException.
Obviously, if isEmpty() returns false, it means that isEmpty() was executed, so quizDescs[0] is not null when the condition returns true, and that's why it works.
Either make sure that both quizDescs and quizDescs[0] is never null, or change the condition to :
if (quizDescs != null && quizDescs[0] != null && !quizDescs[0].isEmpty()) {
....
} else {
....
}
You have an error because quizDescs is Null so when you try to get quizDescs[0] in the condition, you try to get the first item of null object.
The only possible ways the if-line can cause a NullPointerException, is when quizDescs itself is null or the first element quizDescs[0] is null. Try to extract quizDescs into a local variable for debugging purposes and inspect its content.
You can either initialize your array with empty strings or add a check for null - or better review your logic how null is a possible condition. Usually null values should be avoided (see Bloch, Effective Java 2nd Edition, item 43 for a similar case).
This question already has answers here:
Why do I get a NullPointerException when comparing a String with null?
(4 answers)
Closed 8 years ago.
if(status.equals(null))
{
status="Pass";
}
from above code it throws NullPointerException, please give solution for comparing value with null.
Looks like status itself is null. So when you do:
status.equals("null")
You're actually doing:
null.equals("null")
Which causes NPE. You should do:
if(status == null) //Now you're checking if the reference is null
//So you'll never dereference a null pointer
You might find this link useful.
Related topics:
What is null in Java?
Java null check why use == instead of .equals()
In Java "null" is a string. You want to compare the reference to null. Do the following:
if(status == null){
// code here
}
Keep in mind that String is class in Java.So whenever you call a method with unitialized object (which is a null object) then it will throw NullPointerException.In your case, there is possibility that your String status is not initialized So you need to make it sure.
BTW you should check null without using equals() method because it doesn't make sense that you are checking a null object's method for its null value.
You must do like this
if(status == null)
//Do something
only use equals method when you want to compare a String and at the stage where you are quiet sure that your String is initialized.Let say String status = ""; is a intialized String and now it is not null.Just for the info while using equals() , try to use it like "anyValue".equals(status) instead of status.equals("anyValue") because by using like "anyValue".equals(status), it will be more safe in case of null string and you wont get NullPointerException
if(status.equals("null")) //Just checking if string content/value is same
{
status="Pass";
}
By this you are just checking if value(content) of status variable is "null" String or not. IF you want to do a null check you need to do the following
if(null == status)
{
status="Pass";
}
You are not suppose to make it null as "null"! in your case compiler consider it as string.
if(stringVariable!=null)
{
//ur Code
}
(OR)
if(stringVariable.equals(null))
{
//Ur code
}
In case if ur working with string array you can do it as following
if(stringArray.isEmpty())//checks length of String array
{
//ur code
}
You cannot use .equals with a null . Use :
if(status == null) {
//Do something
}
This is exactly the reason why the HashMap cannot store more than one null values . Because it always compares the key with other valuues and if a null is inputted the second time , it throws NPE .
You are getting this error since status is null.
I have the following code within a for loop to see if a string equals a search string:
if(Data.coord[i].equals(Data.search))
I've tested the code with exact values i.e if 1=1 and the rest of the code works fine. It just doesn't like the string comparison. The consol gives out this error:
Exception in thread "main" java.lang.NullPointerException
at highercoursework.Search.main(Search.java:16)
at highercoursework.Main.main(Main.java:16)
Thanks
You should compare the constant to your parameter since it can be null.
For example if Data.search is a constant which you are searching for you should do this:
if(Data.search.equals(Data.coord[i]))
In this case you won't end up trying to call methods on a null reference and you won't need unnecessary null checks either.
You have an unpopulated element in your array i.e.
Data.coord[i]
is null. Note that Data.search could be null, but the equals() method will handle this. You just need to perform the lement check first.
String[] coord = new String[100];
This will mean you can assign something to coord[0] but until you do that coord[0] is null. Hence the null pointer exception.
You can try.
String data= Data.coord[i];
if(data != null && data.equals(Data.search))
you can avoid your problem in two ways:
In the case coord[i] should not be null
if (Data.coord[i] != null) {
if(Data.coord[i].equals(Data.search)) {
}
} else {
logger.error("Unexpected Behavior: coord[i] should not be null");
}
Note: You can replace the logger message by a more appropriated code that fit to your requirement.
In the case your your coord[i] can be null
comparing in this way won't throw an exception if Data.coord[i] is null. (Assuming Data.search is a constant and can't bu null) So the rules for this case is: use in priority a String object constant to call the method equals.
if (Data.search.equals(Data.coord[i])) {}
Read this to understand What is a Null Pointer Exception?
if coord[] is initialized properly, value of Data.coord[i] may be null. You can check
if(Data.coord[i] != null && Data.coord[i].equals(Data.search)) {}
Try this:
if(DATA != null && Data.coord[i].equals(Data.search))
Here is a simple code snippet and I cannot figure out why does it throw a NullPointerException.
String lastGroup = "";
menuTevekenysegekGrouped = new ArrayList<MenuElem>();
for(MenuElem me : menuA) {
// double checked that me objects are never null
// double checked that menuA is never null
if(me.getGroup() != null && !me.getGroup().equals(lastGroup)) { /* NPE!!! */
lastGroup = me.getGroup();
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
In the first iteration the me.getGroup() returns null. So the first operand of the && is false and second operand should not evaluate according to the JLS, as far as I know. However when I debug the code I get NPE from the marked line. I'd like to know why. (Using JRockit 1.6.0_05 if it matters..)
Are you sure that me itself is not, in fact, null?
From your code (without the stacktrace I have to guess), the following may be null and be the cause: menuA or me or menuTevekenysegekGrouped. And some of the values returned from the methods/or used in the methods may also be null, but it's hard to know...
If me is not null, then the only other object that can be null in the above snippet is menuTevekenysegekGrouped. Add a check before first using it to ensure that it's not null.
The repeated calls to me.getGroup() would bug me enough to pull them out into a local variable:
String lastGroup = "";
for(MenuElem me : menuA) {
String thisGroup = me.getGroup();
if(thisGroup != null && !thisGroup.equals(lastGroup)) {
lastGroup = thisGroup;
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
This is only going to fix your problem if in fact me.getGroup() returns different values (sometimes null) on multiple calls with the same me, but it might make it easier to debug, and certainly makes it easier to read.
There is a possiblity that this may be a dupicate question.
I initialize a String variable to null.I may or may not update it with a value.Now I want to check whether this variable is not equal to null and whatever I try I get a null pointer exception.I can't afford to throw nullpointer exception as it is costly.Is there any workaround that is efficient.TIA
If you use
if (x == null)
you will not get a NullPointerException.
I suspect you're doing:
if (x.y == null)
which is throwing because x is null, not because x.y is null.
If that doesn't explain it, please post the code you're using to test for nullity.
I guess you are doing something like this,
String s = null;
if (s.equals(null))
You either check for null like this
if (s == null)
A better approach is to ignore the null and just check for the expected value like this,
if ("Expected value".equals(s))
In this case, the result is always false when s is null.
String is immutable
#Test(expected = NullPointerException.class)
public void testStringEqualsNull() {
String s = null;
s.equals(null);
}
#Test
public void testStringEqualsNull2() {
String s = null;
TestCase.assertTrue(s == null);
}
I am comparing s==null only
can you show the code snippet that you have written
s==null will never throw a NPE
if you are checking whether "s" is null, then do not apply a dot(.) after "s". Doing that would throw NullPOinterException, as applying dot(.) means that you are trying to access on a pointer location which is basically null at the moment !
Also try to use library functions that check whether a string is null or empty. you may use StringUtils.isEmpty(s) from apache library which checked both