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?
The code you have can't be compiled because the ternary operator has a higher operator precedence
than the assignment operator:
Operator Precedence
- postfix (
expr++ expr--
)- unary (
++expr --expr +expr -expr ~ !
)...
- ternary (
? :
)- 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);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.