2

I was running through some practice questions for an upcoming exam and came across a question that me nor my class mates can seem to understand. It is as follows:

where all variables are int or int array.

score += (rounds[i]) ? i + START : 0

How does the ternary operator work in java with += ? This is my understanding:

so it is score += round[i] == i+start or == 0.

Is this a correct understanding?

Kind regards, James

James_B
  • 137
  • 7
  • 3
    won't compile if `rounds` is an int array. – Johannes Kuhn Apr 15 '20 at 23:38
  • thanks, even if it wont compile could you explain how the ternary operator would work with += ? – James_B Apr 15 '20 at 23:47
  • 2
    If `rounds` is an `int[]`, this is a Java compile time error. If you're studying for the OCA or OCP Java exam, the correct answer will be "compile time error". You can consider it *like* `if ((rounds[i])) { score += i + START; } else { score += 0; }` hope that helps. Your example has redundant `()`. – Elliott Frisch Apr 15 '20 at 23:52
  • I once actually ran across a real-world Pascal program in my work. It was quite the novelty. – John Bollinger Apr 16 '20 at 00:06
  • @JohnBollinger I've run across a real-world [product](https://docs.oracle.com/cd/E52590_01/doc.440/910-6241-001_rev_b.pdf) with a Pascal OS. That was a ***shock***. But knowing Pascal didn't directly help me there. – Elliott Frisch Apr 16 '20 at 00:08
  • In 1997, I was employed to teach C++. I inherited lecture notes from my predecessor, who had been a C programmer, and had simply added `//` comments, `cout <<` and `cin >>` to an earlier C course. These lecture notes completely missed the point of C++, so I threw them away and started over. I fear that a C programmer teaching Java may go down the same route as my predecessor. – Dawood ibn Kareem Apr 16 '20 at 00:19
  • @DawoodibnKareem I inherited a set of early C++ documentation covering SABRE and cfront; that seriously set me back in learning C++. I feel your (and you predecessor)'s pain. – Elliott Frisch Apr 16 '20 at 00:25
  • @ElliottFrisch Since covid and online classes the quality has gone down alot in all schools. I honestly think w3 schools is better than most Post Secondary schools unless you are studying something very specialized. I have a decent amount of java experience compared to classmates and am the person people in the class come to for questions so this one really through me off. – James_B Apr 16 '20 at 00:40
  • @OleV.V. From the question: *where all variables are int or int array.* It's the first sentence of the question proper. – Elliott Frisch Apr 16 '20 at 00:44
  • @Ole V.V. No context given to me unfortunately other than the line of code I wrote here. I think it was from an online quiz where we have random questions and a fellow student passed it along to me to see if I could understand it. Not entirely sure though as I am waiting on a response for that. – James_B Apr 16 '20 at 00:44

4 Answers4

3

As with any combination of operators, it's a question of operator precedence and (where the operators have the same precedence) associativity. In Java, the simple assignment and all the operator/assignment operators share the lowest precedence tier. The ternary operator is the sole occupant of the next higher precedence tier. Therefore, your expression is equivalent to

score += ((rounds[i]) ? (i + START) : 0)

That is, the ternary expression is evaluiated, and its result is the right-hand operand of the +=.

As others have observed, that's not valid in Java if the type of rounds[i] is int, though that would be ok in C. But the expression could be sensible in Java if rounds[i] were an array of boolean, or it could be rewritten like this ...

score += ((rounds[i] != 0) ? (i + START) : 0)

... on the assumption that a C-style boolean interpretation of integer rounds[i] is what is wanted.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • 1
    Because this is for pedagogical purposes, and because I did recently pass the OCP Java 8 exam, I can say all of the parens here are correct **but** they are also completely unnecessary `score += rounds[i] != 0 ? i + START : 0;` would also be correct (and if studying for those exams, you need to know exactly what is legal and what is not legal). – Elliott Frisch Apr 16 '20 at 00:05
  • Of course the parentheses are unnecessary, @ElliottFrisch. Otherwise, adding them would not produce an equivalent expression. But I suppose it does not hurt to re-emphasize that. Congratulations on passing the exam. – John Bollinger Apr 16 '20 at 00:10
  • 1
    No worries. And thanks. But I was really also contrasting with the prof's original form: `score += (rounds[i]) ? i + START : 0` where the parens are (IMO) vestigial. – Elliott Frisch Apr 16 '20 at 00:16
1
score += (some condition which is true or false) ? value to add if true : value to add if false;
Eritrean
  • 15,851
  • 3
  • 22
  • 28
1

We can try it.

    int START = 3;

    int score = 0;
    boolean[] rounds = { true, false };
    for (int i = 0; i < rounds.length; i++) {
        score += (rounds[i]) ? i + START : 0;
        System.out.format("i is %d, score is %d%n", i, score);
    }

Output:

i is 0, score is 3
i is 1, score is 3

So the first time through the loop i is 0 and rounds[i] is true. In this case Java adds i and START to get 3 and adds this to score. Second time i is 1 and rounds[i] is false, so instead just 0 is added.

The statement you ask about adds a value to score. The value added is i + START if rounds[i] can be evaluated to true and 0 if it’s false. If i and START are both numeric, a number will be added. If score is numeric, adding 0 usually makes no difference, so you may think of the statement as adding a value only if rounds[i] is true.

so it is score += round[i] == i+start or == 0.

No, there is no implicit == comparison in the statement (as others have said, it requires that rounds[i] is a Boolean value, true or false).

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Thanks for this explanation. It goes fully in depth on what I was asking for clarification on! – James_B Apr 16 '20 at 00:52
  • If you like this answer and it meets your requirement you should consider accepting it. – WJS Apr 16 '20 at 01:13
0

The ternary operator ?: is used as follows:

  • a = bolean_expression ? this if true : else this if false.
        int start = 5;

        // In this case, start was added to itself to obtain 10.                
        start += true ? start  : 0;
        System.out.println(start); // prints 10

        // with out the compound assignment operator (+=) the
        // expression should be enclosed in () 
        start = start + (true ? start : 0);
        System.out.println(start); // prints 20

In the above cases, if the boolean was false, the start always have the value 5 since 0 would be added each time.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • Thanks man, that is much more clear. Teacher just made a mistake. no wonder why I could not find it anywhere. – James_B Apr 15 '20 at 23:56
  • 2
    @OleV.V. Not a down voter, but I would like some prose with the answer. Also, you might add an example with `false`. – Elliott Frisch Apr 16 '20 at 00:19
  • Technically, it's the JLS 15.25. [Conditional Operator `? :`](https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.25) and described in the [Java Tutorials](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html) under "The Conditional Operators". – Elliott Frisch Apr 16 '20 at 01:07
  • Ok, if you really want to get technical, I copied this from the JLS. *The ternary conditional operator ? : (§15.25)* So I just use ternary for short. – WJS Apr 16 '20 at 01:10
  • @WJS I included a link to that section. It does not include the word ternary. I know it is a ternary. So you're not wrong. But Java doesn't call it that. Don't ask me why. Wait, it includes the language at [15.28](https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.28) for some reason. What a pain. – Elliott Frisch Apr 16 '20 at 02:15