im having trouble with null pointer errors in java, im trying to make a breakout game and i know what the problem is its this.
GObject collider = getElementAt( ballX, ballspeed);
if(collider.equals(paddle) && collider){
ballspeed = -ballspeed;
}
When the if statement it null the program gets the error.
Ive try this too but no luck
GObject collider = getElementAt( ballX, ballspeed);
if(collider.equals(paddle) && collider != null){
ballspeed = -ballspeed;
}
Try other way:
if(collider != null && collider.equals(paddle) ){
ballspeed = -ballspeed;
}
Read more about operators in java
Like others said :
if(collider != null && collider.equals(paddle) ) {
should do the trick. so an expression of this form:
if (condition1 && condition2)
Condition2 will be evaluation only if condition1 is true. In this case, if condition 1 is null, condition2 will not be evaluated and this would prevent null pointer exception.
You must do the null-check before you try to call equals(..).
The conditions are evaluated from left to right: if the first one is false, the others are not evaluated at all, because the && cannot be true anymore independent what the other conditions are.
if(collider != null && collider.equals(paddle)){
ballspeed = -ballspeed;
}
If you feel insecure about the evaluation order, you can also do the following:
if(collider != null){
if(collider.equals(paddle)){
ballspeed = -ballspeed;
}
}
Try this
if(collider != null && collider.equals(paddle) )
This should work.
Try changing the order of your second if statement to
if(collider != null && collider.equals(paddle))
If statements are evaluated left to right, if collider is null, the first statement will evaluate to false and the second statement won't be executed. Alternatively you could do something like
if(collider == null) {
//do nothing or attempt to get non null collider
}
else if(collider.equals(paddle))
{
ballspeed = -ballspeed;
}
Related
I'm sorry for the strange title, I couldn't find the exact wording that I wanted but I'll do my best to explain my question here. Basically I have some code that goes like this
if(both inputs are not null)
{
Do this
}
else if(both inputs are null)
{
}
else if(one input is null and the other isn't)
{
throw new Exception("Both inputs must have a value or neither should");
}
if I don't use the middle else if the last else if, the program will throw the exception no matter whether one or both inputs are null. I'm wanting it so that the program sees that both inputs are null and does nothing while continuing with it's execution. I'm using this data to pass to a SQl query and if one of the inputs are null it acts up. I might just be messing up the logic but I was wondering if this is considered bad practice. I can't think of a problem because there isn't a way that this could execute code accidentally. If there is a better way or if this is considered bad practice I would like to hear other ways to go about this. Thanks.
EDIT: clarified question
I think I'm missing something here. Your description doesn't seem to match your code.
In the pseudo-code you wrote, if both inputs are null, no exception should be sent, and that's what you want. But you are saying the exception is still sent ? Something is up here. Can you post something closer to your actual code ?
What you describe seems closer to the behavior of a switch case, where an empty "case" would just drop to the next one.
Both diregarding that, you can avoid those empty "else if" by re-ordering your tests :
if(both inputs are not null)
{
Do this
}
else if(one input is null and the other isn't)
{
throw new Exception("Both inputs must have a value or neither should");
}
This way, no need for an additional empty else if.
You can simplify the code if the language you are using has an Exclusive OR operator. For example in C#:
string A = null;
string B = "Hello World";
if ( A != null && B != null)
{
// Do this
}
else if ( A == null ^ B == null )
{
throw new Exception("Both inputs must have a value or neither should");
}
The result of x ^ y is true if x evaluates to true and y evaluates to false, or x evaluates to false and y evaluates to true.
The easiest fix, in my opinion, would be to change your code to below
if(both inputs are not null)
{
Do this
}
else if((input1==null && input2!=null) || (input1!=null && input2==null))
{
throw new Exception("Both inputs must have a value or neither should");
}
Refactor out this logic in its own method, and then write it as following:
private void refactoredMethod(Input i1, Input i2) {
//Do nothing if both inputs are null.
if (i1 == null && i2 == null)
return;
//Throw if either of them is null.
if (input1 == null || input2 == null)
throw ...
//Neither input is null, do the normal processing.
//so, "Do this"
}
Why are you not checking if either one of the inputs is null?
Then you could throw an exception and continue afterwards if no exception was thrown.
So something like this (in java terms):
if(firstInput == null || secondInput == null) {
throw new IllegalArgumentException("Input must not be null");
}
// do what you want afterwards
How about this:
bool A = (input1 == null), B = (input2 == null);
if (A != B) {
throw new Exception("Both inputs must have a value or neither should");
}
I understand that source code is sometimes better readable with empty blocks for certain conditions. I assume this is what you want to do. Example:
if(street!=null && zip!=null)
{
storeAddress(street,zip);
}
else if(street==null && zip==null)
{
; // Do nothing
}
else // only one of street or zip was provided
{
throw new Exception("Street and zip code must be filled together or both left empty");
}
I use the semicolon here to avoid warnings from SpotBugs. This way I tell Spotbugs (and other developers), that the block is empty on purpose.
The last condition of your example is redundant, so I turned it into a comment.
Using this snippet code in an android project
if (null == f_Panel_2) {
mTowPan = false;
} else {
mTowPan = true;
}
Android studio suggests a simplify if which
mTowPan = null != f_Panel_2;
and it works fine like the above one.
Can anyone explain How this works?
null != f_panel_2 works because it evaluates to true or false depending upon if f_panel_2 is null. Since you're assigning to mTowPan the value if the if statement is true or false, the syntax tree can be reduced to mTowPan = f_panel_2 != null
So, mTowPan is true if f_panel_2 is not null else it is assigned value of false.
return super.isAvailable() && expander != null
&& rightNotLeft ? !expander.isExpandedRight() : expander.isExpandedRight();
My problem was that when expander was null I was getting a null pointer exception. But I didn't think that this should happen since expander!=null is being evaluated to false and since ANDs are being used the entire expression should short circuit and return false.
return super.isAvailable() && expander != null
&& (rightNotLeft ? !expander.isExpandedRight() : expander.isExpandedRight());
The above code (adding the parentheses) solved the problem. However this does not make sense to me as no matter what happens in the conditional operator there is no way to return true so shouldn't it short circuit?
Thank you for your responses.
This is due to operator precedence. Your condition without explicit parentheses is actually evaluated like
return (super.isAvailable() && expander != null
&& rightNotLeft) ? !expander.isExpandedRight() : expander.isExpandedRight();
if (first != null && second != null && !first.equals(second)) {
// not null & not equal
} else if (first == null ^ second == null) {
// not both null and not both not null
// (first == null && second != null) || (first != null && second == null)
} else {
// both null or equal
}
FindBugs is complaining about else if (first == null ^ second == null) {...}
Since you wrote in the comment: not both null it's a good thing that FindBugs showed you your (potential) mistake since you should have used && (AND) not ^ (XOR):
first != null && second != null
or alternatively:
!(first == null || second == null)
UPDATE:
The OP change the comment to: "not both null and not both not null" this condition requires a different if:
(first == null && second != null) || (first != null && second == null)
which is equivalent to:
first == null ^ second == null
only that the former version is more readable.
Probably because it is only software.
The ^ operator is a bitwise operator as opposed to a logical operator. While technically correct the precedence of the operators makes the expression confusing should the logical expressions grow. I don't use FindBugs but I would call the 3rd line suspect - Wrap it in parentheses or rewrite it.
...
} else if ((first == null) ^ (second == null)) {
...
^ can behave like a logical operation as long as the operands are boolean values. Because the precedence is different for each logical and bitwise operator, you should always group with parentheses since the order of evaluation will not be left to right but will be based on the table here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Your expression "not both null" and "not both not null" comes out like this:
(first == null) || second == null) && !((first == null && second == null))
Which is pretty confusing but it is what you are asking for.
I am not sure what you are doing in the blocks but it might be easier to write the entire block like this:
if(first!=null && !first.equals(second)) {
// first is not null and the first and second are not equal
} else if (second!=null && !second.equals(first)) {
// second is not null and first and second are not equal
} else {
// all that is left is that first and second are both null OR neither one is null but they are equal
}
The warning says: redundant null check. Thus, FindBugs thinks that you are redundantly checking the nullity of the variables. Try if this code also triggers the warning:
Boolean firstNull = (first == null);
Boolean secondNull = (second == null);
Boolean equalFirstSecond = first.equals(second);
if (!firstNull && !secondNull && !equalFirstSecond) {
// not null & not equal
} else if (firstNull ^ secondNull){
// not both null and not both not null
} else {
// both null or equal
}
if (first != null && second != null && !first.equals(second)) {
You don't need to test second != null here. The equals() call does that.
} else if (first == null ^ second == null) {
You should return false in this case, assuming this is an equals() method itself.
If FindBugs doesn't like it with this change I would ignore it, it doesn't know what it's talking about. It's not perfect. Put in an exception rule.
i want to get parameters values and sometimes i do not send them and it return me null
and its ok . but when i preform check on the return string array the servlet throws a java.lang.NullPointerException
and i just what to do nothing when its null. ( continue the flow )
String[] values = null;
if(request.getParameterValues(fieldName).length>0)
{
values = request.getParameterValues(fieldName);
if(null!=values || values.length>0) // HERE IT throws NullPointerException
{
Collections.addAll(strlist, values);
}
}
It should be
if(null!=values && values.length>0)
because, if your values is null(evaluating to false), the OR condition in your statement, executes the other part of the OR, which throws the NPE.
If you give an && there, it'll SHORT-CIRCUIT the statement evaluation when it encounters a false at null!=values.
It's the AND && operator that should be used to test if both conditions are met, which is what you need in you instance.
if (null != values && values.length > 0)
in and unlike or if values is null it wont go for next check.
if(null!=values && values.length>0) // change to and
{
Collections.addAll(strlist, values);
}
also refer && (AND) and || (OR) in IF statements
&& and || follow short-circuit evaluation.
That is these operators wont execute right side expressions if not needed.
for && operator if false at LHS, then it wont execute next expressions
for || operator if true at LHS, then it wont execute next expressions
so for your condition check it needs && operation for avoiding NullPointerException
if(null!=values && values.length>0)