Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+21 votes
asked in CSC305 Fall 2022 by (1 point)

2 Answers

+12 votes
 
Best answer

The use of a ? denotes a ternary operator. Ternary operators are java's shorthand for if-else statements. You find them often used when you need to do a quick check before assigning one of two values to a variable, or for any other occasion where you'd have a simple bodied if-else statement returning or assigning something based on a condition. It's probably best compared like-so:

int value1 = 5;
int value2 = 10;
int biggestValue;

if(value1 > value2) {
    biggestValue = value1;
} else {
    biggestValue = value2;
}

Whilst the previous code snippet works perfectly fine, some people might find it easier or cleaner to rewrite the statement as a ternary. The same code above could be rewritten as a ternary:

int value1 = 5;
int value2 = 10;
int biggestValue = value1 > value2 ? value1 : value2;

This alternative takes the exact same steps as before: It evaluates whether value1 is greater than value2, assigning biggestValue the greatest of the two values. As you can see, the basic structure of a ternary operator is as follows:

someVariable = condition ? expressionIfTrue : expressionIfFalse;

just to clarify, ternary operations always return a value, so you are expected to do something with said value. It's not possible to, for instance, put two void method calls as your expressions. Beyond that caveat, they're a nifty holdover from C that can be useful in a pinch. The only thing is to of course ensure that you do not negatively impact your code's readability using it. Whilst shorter code is often nice, hiding complex operations in a single line can very easily sidetrack anyone trying to follow your work.

answered by (134 points)
selected by
+2

Thorough explanation!

FYI, Python also has a ternary conditional operator, although it puts the operands in a different order:

text = "good" if score > 6 else "bad"

+7 votes

? acts like an if/else statement.

For example,

answer = (a = 2) ? 2 : 1;

means if a equals 2, then the answer is 2. Else, the answer is 1.

It could be rewritten as:

if (a = 2) {

 answer = 2;

} else {

 answer = 1;

}

answered by (1 point)
+5

You mean (a == 2) with 2 equals signs...

...