Android studio suggests a simplify If statement syntax - java

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.

Related

Leaving the code in an else if() blank in order to escape the if statement

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.

Why is the conditional (ternary) operator evaluated in a logical AND when the lhs is 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-else condition: AND evaluation mystery

I'm working on an app for Android. In my code I have the following lines:
if (shape != null && !created && isTap(touchDown, event)) {
DrawPrimitive newShape = listener.onTouch(event, shape);
if (newShape != shape)
canvas.onDrawingChanged(true);
}
created is a boolean member. I'm wondering because created is true but the runtime steps into my if even without calling the isTap method. If I change the ! to the false comparsion, everything works fine.
if (shape != null && created == false && isTap(touchDown, event)) {
DrawPrimitive newShape = listener.onTouch(event, shape);
if (newShape != shape)
canvas.onDrawingChanged(true);
}
So I'm wondering if the ! is not allowed. But even if so, why is my isTap method (in version one) not called and why is the inner code executed without evaluating all AND conditions.
Why isTap() isn't called: && conjunctions (and || disjunctions for that matter) are evaluated with short-circuiting from left to right: when the left hand side operand of the expression evaluates to false (true for ||), the right hand side operand does not need to be evaluated: the value of the expression is already known.
!created and created == false are the same in Java if created is boolean. If it's Boolean, you will have problems with autoboxing/unboxing:
!created autounboxes the Boolean to boolean and complements the result with !.
created == false autoboxes false boolean literal to Boolean and compares the object references. They aren't necessarily the same Boolean objects.
To avoid such problems and as a rule of thumb, don't use true or false directly in boolean expressions.
!created and created == false are equivalent. The first version should behave in exactly the same way as the second.

servlet request.getParameterValues(fieldName) returns null and throw exception

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)

Getting NullPointerException with equals

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

Categories

Resources