Search code examples
javavariable-assignmentconditional-operator

Java - Assigning variable in ternary operator - unexpected type error


I'm relatively new to coding and Java. I'm trying to work on using the ternary operator in place of some of my "if" statements. When I code the below as an if/else, it works fine, but when I run it as is I get

unexpected type
required: variable
found:    value line:3

Can you not assign value via ternary, or am I doing it wrong? Thanks in advance!

  int front;
  nums.length>4 ? front = 4 : front = nums.length;

Solution

  • In Java the ternary operator is an "assignemnt" one, this means that the result of the operation "always" must be assigned to a variable.
    The destination variable goes at left (as usual) of the symbol "=", whilst the operator goes at right. As you said, it just works as an if/else. The structure is this one:

    <destination_variable> = <condition> ? <value_if_cond_true> : <value_else>
    

    So, in your specific case, the ternary operator will be written as follow:

    int front = nums.length > 4 ? 4 : nums.length;