3

Why does this return an error

return (n > 2) ? n = 5 : n = 4;

but this does not

return (n > 2) ? n = 5 : n + 4;

Should it not be able to return n depending on either case?

Christian Gibbons
  • 4,272
  • 1
  • 16
  • 29

3 Answers3

4

The code you have can't be compiled because the ternary operator has a higher operator precedence than the assignment operator:

Operator Precedence

  1. postfix (expr++ expr--)
  2. unary (++expr --expr +expr -expr ~ !)

...

  1. ternary (? :)
  2. assignment (= += -= *= /= %= &= ^= |= <<= >>= >>>=)

When parsing the code

(n > 2) ? n = 5 : n = 4;

it will parse it like this:

(n > 2) ? n = 5 : n     // ternary operator
                    = 4 // assignment operator

This would result in pseudo code like this:

someResultValue 
                = value;

That will not work and you get compile errors like:

'Syntax error on token "=", <= expected'

or

'Type mismatch: cannot convert from Object & Comparable<?> & Serializable to int'.

You can use parentheses to let java see the third argument of the ternary operator as n = 4. The code would look like this:

return (n > 2) ? n = 5 : (n = 4);
Progman
  • 16,827
  • 6
  • 33
  • 48
0

I think you may have any syntax error. I tried that in chrome JS console and worked fine!! Solution of question

Update: Some people argued in comments that I didn't write function so I wrote in functional format and got the same result!enter image description here

Marmik Patel
  • 21
  • 1
  • 4
0

syntax : condition ? expression1 : expression2;

Try this

public class Solution {
    public static void main(String[] args) throws IOException {
       int a = 10;
       int b = (a>5)?a=5:0;
       System.out.println("a = "+ a);
       System.out.println("b = "+b);
       
    }
}

output: a = 5 b = 5

shashank
  • 11
  • 7