String readwidget(int a, int b){
WidgetChild readwidget = Widgets.get(a,b);
if(readwidget.getText() != null){
Task.sleep(10);
System.out.println(readwidget.getText());
return readwidget.getText();
}
Task.sleep(10);
return GOT_NULL;
}
while(readFirstWidget.equals(GOT_NULL) && t5.isRunning()) {
readFirstWidget = readwidget(1184, 13);
Task.sleep(50,80);
}
This piece of code is crashing with nullpointerexception once in while(1 out of 50 time) and it prints null at that point of time which it should not. Can anyone please help me to find out the causes? Thanks in advance.
You mention in a comment that Widgets.get(a,b) can return null. Given that, you need to guard against that possibility by checking the return value from the method for null prior to actually calling any instance methods on it. You aren't doing that, and so you are crashing in that case.
All you need to do is add the null check and your code should be fine:
WidgetChild readwidget = Widgets.get(a,b);
if(readwidget != null && readwidget.getText() != null) {
Related
I have been working on a HuffmanCode program and I thought I had finished it this morning. However, I have randomly started to get a NullPointerException even though it was working perfectly earlier today. Below is the method that is causing the problems: (port = left side of tree, star = right side of tree)
public void translate(BitInputStream input, PrintStream output) {
HuffmanNode tempRootRef = huffmanRootRef;
while(input.hasNextBit() || (tempRootRef.port == null && tempRootRef.star == null)) {
if(tempRootRef.port == null && tempRootRef.star == null) {
output.write(tempRootRef.charValue);
tempRootRef = huffmanRootRef;
} else if (input.nextBit() == 0){
tempRootRef = tempRootRef.port;
} else {
tempRootRef = tempRootRef.star;
}
}
}
I am getting the NullPointerException on the first if statement:
Exception in thread "main" java.lang.NullPointerException
at HuffmanCode.translate(HuffmanCode.java:118)
at HuffmanCompressor.decompress(HuffmanCompressor.java:115)
at HuffmanCompressor.main(HuffmanCompressor.java:178)
I tried reviewing answers to similar issues but I had trouble understanding them.
Assuming that huffmanRootRef has a non-null value, then a NPE in that line means that input.hasNextBit() returned true, but tmpRootRef is null.
I suggest tracing through your code (either in a debugger or with a couple of print statements) to watch the values as it executes.
I have a problem with the logic expression on my method matches1().
Problem
SonarQube is telling me there is an error:
(expectedGlobalRule == null && actual != null)
SonarQube:
Change this condition so that it does not always evaluate to
"true".
Conditions should not unconditionally evaluate to "TRUE" or to "FALSE"
I'm essentially doing this logic to avoid a NPE on my "Block to be executed".
My code
matches1()
private boolean matches1(GbRule actual, GbRule expected) {
if(actual == null && expected == null) {
return true;
} else if((expected == null && actual != null) || (expected != null && actual == null)) {
return false;
} else {
//Block to be executed
}
}
I inverted the logic in to see what SonarQube would tell me and he doesn't complain about it.
matches2()
private boolean matches2(GbRule actual, GbRule expected) {
if(actual == null && expected == null) {
return true;
} else if(expected != null && actual != null) {
//Block to be executed
} else {
return false;
}
}
Question
Do the problem is in my boolean logic or it's SonarQube that lost
his mind?
If the problem is within sonarQube, how could I resolve it?
The problem is in your logic. Let's take it piece by piece:
if(actual == null && expected == null) {
return true;
At this point if both vars are null then we're no longer in the method. So if we get any further, then at least one of them is non-null.
The viable options at this point are:
actual = null, expected = non-null
actual = non-null, expected = null
actual = non-null, expected = non-null
Now, let's look at the next bit of code:
} else if((expected == null && actual != null)
We already know that both variables can't be null, so as soon as we know expected == null, there's no need to test whether actual != null. That has already been proven by the fact that we got this far. So actual != null is always true, which is why an issue is raised.
Edit
This means that your code could be boiled down to:
private boolean matches1(GbRule actual, GbRule expected) {
if(actual == null && expected == null) {
return true;
} else if(actual == null || expected == null) {
return false;
}
//Block to be executed
}
Note that the else isn't needed & dropping it makes the code easier to read.
Even when the code is correct; seriously, it makes my eyes hurt. Thing is: it is hard to read. Such kind of nested conditions is something that one should not be writing in the first place.
If you can't avoid it; at least refactor it into something like
private boolean areActualAnedExpectedBothNull(args ...) {
return actual == null && expectedGlobalRule == null;
}
And please note; you can dramatically simply your code:
if (areActualAnedExpectedBothNull(actual, expected)) {
return true;
}
if (actual == null) {
return false;
}
if (expected == null) {
return false;
}
do your thing ...
and use such methods in your other code. And of course, you do a lot of unit testing; probably with coverage measurements; just to make sure that your tests really test all possible paths through this maze.
But as said; you better step back and think if there are ways to avoid writing such code in the first place.
The typical answer to booleans, and if/else chains in OO programming is polymorphism. So instead of asking something about its state; you turn to interfaces/abstract classes; and have different implementations of those. And then you have a factory giving you that implementation you need; and then you just call methods on that; without further need for if/else/whatever.
If you don't know what I am talking about - watch these videos; especially the second one!
The problem is with SonarQube.
See this article for more info on ignoring that issue: https://www.bsi-software.com/en/scout-blog/article/ignore-issues-on-multiple-criteria-in-sonarqube.html
You can just set it up to ignore that error within that file.
The gist of it is
Open the Settings (SonarQube General Settings or project Settings) and
select the Exclusions category. Switch to the Issues Exclusions and
scroll down to “Ignore Issues on Multiple Criteria”. Set squid:S00112
as Rule Key Pattern and **/*Activator.java as File Path Pattern.
You will need to change the rule key pattern to the pattern associated with the rule that is being violated for your code and the file pattern as the path of your .java file.
I am checking for null before doing a certain operation but I have run into some issues. Following is the code:
if (c != null && c.size() != null) {
if (c.size() > 0) {
return (Application) c.toArray()[0];
}
I am getting a 'The operator != is undefined for the argument type(s)int, null' at the point
c.size() != null. I understand the return type for the size method is an integer, is that why I am getting this error? Hope someone can advise. Thank you.
int is a primitive type and is not an Object so is not a reference that can be null. Read more in this previous answer
Then in your code just remove that condition.
And also is preferred you use c.isEmpty() rather than c.size()>0
Your code would look like this:
if (c != null && !c.isEmpty()) {
return (Application) c.toArray()[0];
}
First of all, the result of c.size() is an integer. An int is a primitive, and it cannot be null. Only objects can be null.
Second, c.size() will never return null, so the check
c.size() != null
is unnecessary.
Note: There are wrapper classes for each primitive type. For example
Integer i = 4;
i = null; // valid
That assignment will be valid because i is an instance of the class Integer.
I have this method in my superclass, which extends activity:
protected boolean isStopAvailable(BusStop stop) {
if (stop == null) {
stop = new BusStop();
} else if (stop.getName().length() > 0) {
return true;
} else {
return false;
}
return false;
}
I call it in my subclass isStopAvailable(object); How is it even possible to get a null pointer exception while using a method from the object after I've initiated the object?
stop.getName() returns null
else if (stop.getName() != null && stop.getName().length() > 0)
should solve it
If getName() returns null, you will get a NPE. You are trying to do a length function on a null object, hence this exception. You should add another else if check:
...
else if (stop.getName() == null) {
// do something
}
Hope this helps.
I would bet that the name field in stop is null. Your first check is to see if the object is null, not the fields inside of it. Thus, if stop.getName() returns null, you get an NPE when attempting to invoke the length
I suggest that the NPE is thrown in this line: else if (stop.getName().length() > 0)
Thats possible because you've checked if the object BusStop is null but you didn't checked if stop.getName() could be null.
Do something like that:
else if (stop.getName() == null) {
// set stop.setName()
}
Hope this helped, Have Fun!
stop.getName() is returning null ,that is why you are getting NPE.
I have a very simple method:
public int getScore() {
return game.gameWindow.userBestScore;
}
The problem is that it can happens that game object or gameWindow do not exist. I do not want to get the Null Pointer Exception. How can catch it in a correct way? Can I do it in this way:
public int getScore() {
try{
return game.gameWindow.userBestScore;
} catch(NullPointerException e){
return -1;
}
}
Do not catch a NullPointerException.
A NullPointerException is a sign that your code is not adhering to some contract. If it is possible that game can be null, then you need to make an explicit test:
if(game != null) {
...
}
else {
...
}
If game should not be null, then you can ensure the correctness of your code by using assert.
assert game != null;
...
What is more worrying is that game seems to be a private member of your class. In this case game should probably not be null (although there are cases where this can happen). Are you initializing it properly in your constructor? I'd say that the first thing you should is to make sure that game is being initialized properly. Otherwise your code will end up being littered with un-necessary null-checks. For example, what if gameWindow in the Game class wasn't initialized properly? You would need to have another null-check for that:
if(game !== null && game.gameWindow != null) {
...
}
else {
...
}
So you should first make sure that your object's private members are being initialized properly. If they are, and it turns out that there is a valid use-case for game being null, then you would need an explicit null-check. It's always better to test for null than catching a NullPointerException. Other than the fact that exceptions should not be used to control the flow of your business logic, what if a valid NullPointerException (due to a programming error) was generated somewhere up the chain? Now your catch will catch it and you won't know about it; this can lead to some really nasty and hard-to-find bugs.
You can do that. You can also check to see if game and gameWindow are null before trying to access userBestScore.
if(game != null && game.gameWindow != null)
return game.gameWindow.userBestScore
Check whether the variables are null as shown below:
public int getScore() {
if(game == null || game.gameWindow == null){
return -1;
}
return game.gameWindow.userBestScore;
}
public int getScore() {
return ((game == null || game.gameWindow == null) ? -1 : game.gameWindow.userBestScore);
}
You can do that. OR you can check for null before you dereference those objects and take appropriate action without throwing an exception. That'll be more efficient.
The real question you should be asking is: Why on earth would an object have null references for private data members? You aren't constructing your objects properly. An object should be properly initialized and 100% ready to go after you create it. Otherwise, you end up having to be unnecessarily defensive in your code.
Avoid exception throwing as much as possible. Handling the known issues is the better way than throwing exceptions.
In some where you have to do a null check. Probably before calling the getScore() method, because that doesn't make a sense of calling that method if the game or gameWindow is null.
if (game != null && gameWindow != null)
{
int score = getScore();
}
OR
public int getScore()
{
if (game != null && gameWindow != null)
{
return game.gameWindow.userBestScore;
}
else
{
return -1;
}
}
Don't do duplicate null checkings.