I need to do something like this,
if (first_var > second_var)
int difference = first_var - second_var;
if (first_var < second_var)
int difference = second_var - first_var;
When I try to compile this, an error comes stating the variable 'difference' may not have been initialized. Making the variable 'difference' global doesn't help either.
The issues that you need to learn are:
{...}
block for if
statementsif-else
instead of if (something) {...} if (!something) {...}
By the way, the idiomatic way to find the difference of two values is:
int difference = Math.abs(firstVar - secondVar);
Do note that Math.abs
has a corner case: when the argument is Integer.MIN_VALUE
, the returned value is Integer.MIN_VALUE
. That's because -Integer.MIN_VALUE == Integer.MIN_VALUE
. The issue here is 32-bit two's complement representation of numbers.
Math.abs(int)
if
Here's one attempt to fix the snippet, by declaring the variable before the if
int difference;
if (first_var > second_var) {
difference = first_var - second_var;
}
if (first_var < second_var) {
difference = second_var - first_var;
}
// note: difference is not definitely assigned here!
// (but at least it's in scope!)
We now have a problem with definite assignment: if first_var == second_var
, the variable difference
is still not assigned a value.
Here's a second attempt:
int difference = 0;
if (first_var > second_var) {
difference = first_var - second_var;
}
if (first_var < second_var) {
difference = second_var - first_var;
}
// note: difference is in scope here, and definitely assigned
Beginners tend to do this, but this precludes the possibility of making difference
a final
local variable, because it's possibly assigned value twice.
if-else
Here's a better attempt:
final int difference;
if (first_var > second_var) {
difference = first_var - second_var;
} else {
difference = second_var - first_var;
}
// note: difference is in scope, and is definitely assigned here,
// (and declared final)
There are still ways to improve on this.
Once you're more comfortable with the language and programming, you may use the following idiom:
final int difference = (first_var > second_var) ? first_var - second_var
: second_var - first_var;
This uses the ?:
ternary/conditional operator. Do be careful with this operator; it has some behaviors that may be surprising, and it definitely can be abused. Use carefully, judiciously, idiomatically.
?:
You have two options:
Do the condition on one line using the ternary operator ?:
int difference = first_var > second_var ? first_var - second_var : second_var - first_var;
Declare the variable up front, then do the condition.
int difference = 0;
if (first_var > second_var)
difference = first_var - second_var;
if (first_var < second_var)
difference = second_var - first_var;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With