[java] Assign variable value inside if-statement

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.

This question is related to java

The answer is


Variables can be assigned but not declared inside the conditional statement:

int v;
if((v = someMethod()) != 0) return true;

Yes, it is possible to assign inside if conditional check. But, your variable should have already been declared to assign something.


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.


You can assign a variable inside of if statement, but you must declare it first


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.

HINT: what type while and if condition should be ??

If it can be done with while, it can be done with if statement as weel, as both of them expect a boolean condition.


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

Yes, it's possible to do. Consider the code below:

public class Test  
{        
    public static void main (String[] args)       
    {       
        int v = 0;          
        if ((v=dostuff())!=0)            
        {          
            System.out.printf("HOWDY\n");          
        }             
    }                
    public static int dostuff()       
    {             
        //dosomething              
        return 1; 
    }       
}          

I hope this will satisfy your question.


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;

You can assign, but not declare, inside an if:

Try this:

int v; // separate declaration
if((v = someMethod()) != 0) return true;