Search code examples
javaif-statementternary

Is it possible to use break with ternary operator


Is it possible use the break and continue words with ternary operator?

There is an example:

int variable = 0;
        
for (int i = 0; i < 10; i++)
    variable = (i % 2 == 0) ? break : variable;
    System.out.println(variable);

Solution

  • Is it possible use the break and continue words with ternary operator?

    No. It doesn't really make sense, and thus isn't supported.

    EDIT

    The following code has been added to the question:

    int variable = 5
            
    for (int i = 0; i < 10; i++)
        variable = (variable == 5) ? break : variable
        System.out.println(variable)
    

    variable = (variable == 5) ? break : variable isn't valid, but it were, I think that could be simplified to this:

    int variable = 5

    for (int i = 0; i < 10; i++)
        if(variable == 5) { break; }
        System.out.println(variable)
    

    The "else" condition in your proposed ternary operator would be assigning the variable its own value, which of course is a step you can skip.

    Presumably your actual scenario is more sensible than the way that sample code is written. You wouldn't want i < 10 if your intent was to quit when you got to 5.