开发者

How can you assign a variable a value inside a if statement in Java

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 e开发者_如何学Pythonither.


The issues that you need to learn are:

  • The scope of variables
  • Block declaration and how that creates new scopes
  • Why you should prefer to use {...} block for if statements
  • How to guarantee definite assignment
  • When to use if-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.

References

  • JLS 16 Definite Assignment
  • JLS 14.4.2 Scope of Local Variable Declarations
  • JLS 14.9.2 The if-then-else Statement
  • Math.abs(int)
  • Wikipedia/Two's complement (read: the most negative number)

Attempt #1: Declaring before the 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.


Attempt #2: Initializing at declaration

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.


Attempt #3: 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.


Attempt #4: The ternary/conditional operator

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.

References

  • JLS 15.25 Conditional Operator ?:


You have two options:

  1. Do the condition on one line using the ternary operator ?:

    int difference = first_var > second_var ? first_var - second_var : second_var - first_var;
    
  2. 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;
    


It's because the variable might indeed not get initialized. In reality if first_var and second_var are equal to each other, it wouldn't get initialized. In addition to that, the compiler probably isn't smart enough to figure it out even if you added a third if. Move the declaration outside the ifs and initialize it to a value on that line as well.

int difference = 0;
if (first_var > second_var)
    difference = first_var - second_var;
if (first_var < second_var)
    difference = second_var - first_var;

However, I'd just do

int difference = Math.abs(first_var - second_var);


You can only declare a variable in one place.

The basic solution is

int difference;
if (first_var > second_var)
  difference = first_var - second_var;
if (first_var < second_var)
  difference = second_var - first_var;

However in this case you can use inline ?: operator

int difference = (first_var > second_var) ? 
  first_var - second_var : second_var - first_var;


First, you have to define tour variable "difference" outside your ifs statements:

int difference;
if (first_var > second_var)
    difference = first_var - second_var;
if (first_var < second_var)
    difference = second_var - first_var;

Then, the compiler can't be sure that your variable will have a value once both ifs statements are executed. For example, if first_var and second_var have the same value, difference will not be assigned. So, if you try to use your variable, you'll have a compile time error.

To resolve this, you have two solutions:

The first solution is to give your variable a default value, which will be used if no other conditions is completed:

int difference = 0;
if (first_var > second_var)
    difference = first_var - second_var;
if (first_var < second_var)
    difference = second_var - first_var;

The other solution is to use else if statements. When using else if statements, the compiler is able to determine if your variable will be assigned in all cases:

int difference;
if (first_var > second_var) {
    difference = first_var - second_var;
} else if (first_var < second_var) {
    difference = second_var - first_var;
} else {
    difference = 0;
}


You can indeed assign a variable inside an if statement, but you cannot initialize it inside an if statement. In plain English, you can give a variable a value inside an if statement, but you cannot create a variable inside an if statement. The reason for this is because there is a possibility that the code inside the if statement will never run if the if conditions are never met.

Here's how I would have written that code:

int difference = 0;

if (first_var > second_var)
   difference = first_var - second_var;
else if (first_var < second_var)
   difference = second_var - first_var;


The reason why it may not have been initialized is you accounted for A < B, B < A, but not A == B. Account for that:

if (first_var > second_var)
  int difference = first_var - second_var;
if (first_var < second_var)
  int difference = second_var - first_var;
if (first_var == second_var)
  int difference = 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜