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 forifstatementsif-elseinstead ofif (something) {...} if (!something) {...}By the way, the idiomatic way to find the difference of two values is:
Do note that
Math.abshas a corner case: when the argument isInteger.MIN_VALUE, the returned value isInteger.MIN_VALUE. That’s because-Integer.MIN_VALUE == Integer.MIN_VALUE. The issue here is 32-bit two’s complement representation of numbers.References
Math.abs(int)Attempt #1: Declaring before the
ifHere’s one attempt to fix the snippet, by declaring the variable before the
ifWe now have a problem with definite assignment: if
first_var == second_var, the variabledifferenceis still not assigned a value.Attempt #2: Initializing at declaration
Here’s a second attempt:
Beginners tend to do this, but this precludes the possibility of making
differenceafinallocal variable, because it’s possibly assigned value twice.Attempt #3:
if-elseHere’s a better attempt:
There are still ways to improve on this.
Attempt #4: The ternary/conditional operator
Once you’re more comfortable with the language and programming, you may use the following idiom:
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.References
?: