javaternary

Using += in Java ternary expression


I am trying to use a generic type with a ternary expression to execute expressions that do not return a value. Here is my class:

  static class Generic<T> {
    T t;
  }

  public static Generic generic = new Generic();

I am executing a simple command. The Java compiler does not produce any errors for my_a += 1, yet it disallows my_b += 1.

generic.t = X ? my_a += 1 : my_b += 1;

My question is: why doesn't it allow the second expression?

This is mostly an experimental piece of code. I am just trying to understand the way ternary works in Java and why can't I use += in my_b += 1 .

code:

bool X = true;
int my_a = 0;
int my_b = 0;
generic.t = X ? my_a += 1 : my_b += 1;

Exception:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
        Syntax error on token "+=", + expected

Changing my_b += 1; to my_b++ compiles and executes the code successfully. I expected the code will execute with my_b += 1; since a generic type is designed to be compatible with various data types.


Solution

  • The operator precedence rules are wonky here. You need parentheses. This works fine:

    generic.t = X ? (my_a += 1) : (my_b += 1);