Search code examples
javaternary

Error while using Ternary operator with int and boolean


Can you please help me understand where i m doing the mistake. I cam across this question while doing the beginner java material.

Ques: - Show how this sequence can be rewritten using the ? operator if(x < 0) y = 10; else y = 20;

Ans: - x < 0 ? y =10 : y =20;

But when i tried performing the same i am getting an error

public class Ternary {
public static void main(String[] args) {
    int result, x, y;
    result = x < 0 ? y =10 : y =20;
    System.out.println(result);
    }

}

Error at result:- Multiple markers at this line - Incompatible conditional operand types int and boolean - Syntax error on token "=", != expected


Solution

  • When you use a ternary operator you're assigning the left most variable to the result of the condition. In other words you only need two variables (I'll use result and x).

    So the code should be:

    result = x < 0 ? 10 : 20;

    This will set result = 10 if x < 0 else result will be 20!