Assign variable value inside if-statement [duplicate]
I was wondering whether it is possible to assign a variable a value inside a conditional operator like so:
if((int v = someMethod()) != 0) return v;
Is there some way to do this in Java? Because I know it's possible in while
conditions, but I'm not sure if I'm doing it wrong for the if-statement or if it's just not possible.
Solution 1:
Variables can be assigned but not declared inside the conditional statement:
int v;
if((v = someMethod()) != 0) return true;
Solution 2:
You can assign, but not declare, inside an if
:
Try this:
int v; // separate declaration
if((v = someMethod()) != 0) return true;
Solution 3:
an assignment returns the left-hand side of the assignment. so: yes. it is possible. however, you need to declare the variable outside:
int v = 1;
if((v = someMethod()) != 0) {
System.err.println(v);
}
Solution 4:
Yes, you can assign the value of variable inside if.
I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single =
instead of ==
or ===
.
It will be better if you do something like this:
int v;
if((v = someMethod()) != 0)
return true;
Solution 5:
I believe that your problem is due to the fact that you are defining the variable v inside the test. As explained by @rmalchow, it will work you change it into
int v;
if((v = someMethod()) != 0) return true;
There is also another issue of variable scope. Even if what you tried were to work, what would be the point? Assuming you could define the variable scope inside the test, your variable v would not exist outside that scope. Hence, creating the variable and assigning the value would be pointless, for you would not be able to use it.
Variables exist only in the scope they were created. Since you are assigning the value to use it afterwards, consider the scope where you are creating the varible so that it may be used where needed.