132

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.

2
  • That'd be nice.
    – Josh M.
    Feb 3, 2022 at 20:57
  • You were so preoccupied with whether you could, you didn’t stop to think if you should... That's some real confusing code right there and it can get even worse. You can have this other abomination: if(v = doSomething()) { /* do stuff */ }. By the time you realise that's a = and not ==, you already interpreted the code wrong for hours trying to understand why it doesn't work Mar 3 at 13:03

9 Answers 9

221

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

int v;
if((v = someMethod()) != 0) return true;
7
  • 3
    So if you need the declaration anyway just place the someMethod() assign in front of the declaration. int v = someMethod()
    – wviana
    Feb 17, 2016 at 19:53
  • 3
    Pitty, no oneliner for me :( Dec 20, 2016 at 9:02
  • 1
    i pitty the oneliner >:D
    – Jason K.
    Apr 6, 2017 at 16:15
  • 14
    I pity the int foo.
    – xdhmoore
    May 9, 2018 at 22:44
  • 1
    @wviana In some situations you may not want to run someMethod() and spend run time until after other checks are made in the conditional. If someMethod() takes a long time, and you don't want to check the result of that until a later "else". With your way, that time would be spent on it whether it is used or not.
    – Michael K
    Oct 21, 2022 at 15:43
29

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

Try this:

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

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);
}
6
  • 3
    As per specification, assignment returns value of the left-hand side (the variable that was assigned to).
    – StenSoft
    Mar 12, 2015 at 15:45
  • 1
    @rmalchow Correction, you don't necessarily have to initialize variable, it depends on what if statement does. If it returns out, for instance, then there is no need for initialization. Jul 30, 2015 at 11:24
  • @StenSoft - true. however ... i wonder if, other than an implit cast - as in long i = (int)2; - this would have any significance?
    – rmalchow
    Jul 23, 2016 at 6:50
  • @randomUser56789 can you elaborate? "if((int v = call()) != 4)" just won't work.
    – rmalchow
    Jul 23, 2016 at 6:51
  • @rmalchow it won't work indeed. I said that you don't have to initialize the variable outside, but you do have to declare it outside. Jul 25, 2016 at 7:38
8

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;
2
  • 1
    This is easy to shoot yourself in the foot with because it compiles just fine... boolean b = false; if ( b = true ) { //oops } Mar 16, 2018 at 12:52
  • @EddieB This isn't like shooting yourself in the foot. More about not knowing the kind of gun you have in your hands. Gosling messed up Java a lot in the name of the former when most of the time it had to do with the latter.
    – stillanoob
    Jul 14, 2020 at 9:53
2

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.

0
2

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.

0
1

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

1

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

0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.