If the newWord is null ,it should not go in the loop,but why does it go inside the loop and gives java.lang.NullPointerException
newWord = "abcd";
while(!newWord.equals(null))
{
try {
newWord = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
}
catch(NullPointerException p)
{
}
}
It gives the stacktrace but i have not used printStackTrace() anywhere
newWord itself is null. When an object is null, you can't call any methods on it as the object is not defined. As .equals is a method, you are getting an exception. Try this instead:
newWord != null
This is a problem easily solved by debugger. Learning to use a debugger is frustrating (as is learning any new tool,) but it will save you many hours of pain. It is your friend.
how about simply
while(newWord!=null)
Think about it, If newWorld is null, what happens when you call methods on it ?
It doesn't go into the loop because
newWOrd.equals(null)
will throw an NPE if it is null
What you meant was
newWord != null
You can see this behaviour if you use a debugger, or look at the line in your stack trace where it is triggered.
You only check if "newWord" is null, never if "br" has anything left reading from.
Something like:
while(br.hasNext());
the NullPointerException you are getting is because of while(!newWord.equals(null)) and it is not caught because try , catch were used after this code.
If you want to suppress this exception to then put that while(!newWord.equals(null)) in try-catch block.
!newWord.equals(null)
is your problem.
Use newWord != null
The argument for String.equal should not be null and explicitly null is passed so is the exception. Use compound expression to check for empty string and special null.
It tried to evaluate the expression before entering loop, soon the expression is encountered !newWord.equals(null), because of newWord being null an exception were thrown.
to avoid null exception in most of the cases (inside conditional expressions) I advise you to use Yoda conditions:
if(null != value)
Furthemore, this apply to every condition between a variable and a constant:
if(MY_CONSTANT_STRING.equals(myVariableString))
Related
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
In my code I get the above warning. Here is the part of the code where I get it,
try {
fileFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (URISyntaxException | NullPointerException e) {
}
finally {
if (fileFile.getPath()!= null){
strPathName = fileFile.getPath();
}
if (fileFile.getName() != null){
strFileName = fileFile.getName();
}
}
The line if (fileFile.getPath()!= null){ is the one with the warning.
This code is not part of the Main class. It's in another class in another class file in the same package.
I'm not very experienced with programming but I believe I did nearly everything to prevent or catch a null pointer exception. Why do I still getting it and what can I do to get rid of it? Thanks for your help.
After reading all your hints I solved it. Here is the complete code:
public static ArrayList<String> getCurrentPath() {
File fileFile;
String strPathName, strFileName;
ArrayList<String> arrPathFileName;
strFileName = null;
strPathName = null;
try {
fileFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
if (fileFile.getPath()!= null){
strPathName = fileFile.getPath();
}
if (fileFile.getName() != null){
strFileName = fileFile.getName();
}
} catch (URISyntaxException use) {
}
arrPathFileName = new ArrayList<>();
arrPathFileName.add(strPathName);
arrPathFileName.add(strFileName);
return arrPathFileName;
}
As already mentioned I simply put the if statements into the try block and removed the finally block.
BTW is also tried to combine both if blocks into one that way:
if (fileFile != null){
strPathName = fileFile.getPath();
strFileName = fileFile.getName();
}
But that produced a warning that fileFile will never become null. (what was my point of view from the beginning and so the warning "dereferencing possible null pointer" was really confusing me.)
So if you throw an exception on your first line, your variable will not be assigned to a File, and will retain it's previous value (null if not formerly assigned). Your exception is caught, and then you continue to use that unassigned variable. Hence the warning. See the commented code below.
try {
fileFile = // exception thrown. Variable not assigned
} catch (URISyntaxException | NullPointerException e) {
// exception caught
}
finally {
// unassigned variable used here...
if (fileFile.getPath()!= null){
strPathName = fileFile.getPath();
}
if (fileFile.getName() != null){
strFileName = fileFile.getName();
}
}
I would rather scope and use the variable within the try block, if at all practical. In your finally block, you need to be as careful as you can, since you could have come to it from most anywhere in your try block.
As an aside, this:
Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();
will cause you enormous problems if you do get an NPE. Which of the above resolved to null ? I would perhaps be more explicit, such that you can check for nulls from each invocation and unambiguously determine which invocation gave you a null. Tiresome ? Unfortunately so.
A "null pointer dereference" is computer speak for trying to call a method on a null value. It's a little more complicated, but you said you were a novice, so I wanted to keep it simple.
Let's see an example:
String s = null;
s = s.toUpperCase();
This is a simple example of what a null pointer dereference is. s is a null reference (its value is null), when we derefrence is (get the value of it) we have null, when we call toUpperCase() on null, something goes horribly wrong because null doesn't have any methods, at all! Java throws a NullPointerException to be specific.
Now, back to your code, because fileFile is assigned in the try-block I assume it was set to null before it to avoid Java yelling about an uninitialized variable. (This is all fine and correct.) In this try-block, if any of the exceptions for your catch-block occur it will stop the try-block (meaning fileFile will not get a new value, meaning it will still be null).
Now you'll notice the warning is possible null pointer dereference. That means it won't necessarily be null, but could be! (In my above example, it's always a null pointer dereference for comparison.) Specifically, if the catch catches an exception it will be null.
To be clear, the issue is this: fileFile.getPath(). It's like saying it might be null.getPath(), gross. It looks like you were trying to avoid the null pointer issue, what you should have done was if (fileFile != null) { instead. Then inside of the if do what you want.
Also, because it seems like you included it to avoid this warning, I would seriously remove the NullPointerException from the catch-block. That's not helping you avoid the warning. If you want me to explain more why it's bad you can leave a comment and I will, otherwise just take my word for it, it's not helping you.
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).
I am looking at a code base where the domain model consists of many nested member variables.
Consider this scenario
private static String getSomeStringRepresentation(A input) {
String result = "";
try {
result = input.getTypeA().getTypeAInfo().get(0).getRepresentation();
} catch (NullPointerException e) {
Logger.logDebug(e.getMessage());
}
return result;
}
In this call chain, any method call can result in a NullPointerException. Is it correct to handle it with a catch clause in this case? Is this a case where "it is possible to handle the exception" ?
Edit
The case of checking for null four times is really ugly. Don't you consider catching the NPE is justified in this case?
The problem here is calling some method on a object that possibly could be null.
Why don't you check for null rather than putting a catch block? Catching NullPointerException isn't considered good practice.
If catching null pointer exception is not a good practice, is catching exception a good one?
also
Is Catching a Null Pointer Exception a Code Smell?
Catching a NullPointerException is not a good practice without a serious reason:
Rather check for null object like this:
private static String getSomeStringRepresentation(A input) {
String result = "";
try {
if(input != null && input.getTypeA() != null && input.getTypeA().getTypeAInfo() != null && getTypeAInfo().get(0) != null){
result = input.getTypeA().getTypeAInfo().get(0).getRepresentation();
}
} catch (NullPointerException e) {
Logger.logDebug(e.getMessage());
}
return result;
}
Here is a possible duplicate on the subject.
NPEs are just an error in the code and should therefore not be catched - they should be fixed.
NullPointerException indicates a programming error, catching it is wrong. Instead of catching it fix bugs in your program.
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