196

I have been working with Java a couple of years, but up until recently I haven't run across this construct:

int count = isHere ? getHereCount(index) : getAwayCount(index);

This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.

  • if isHere is true, getHereCount() is called,
  • if isHere is false getAwayCount() is called.

Correct? What is this construct called?

Randika Vishman
  • 7,983
  • 3
  • 57
  • 80
mainstringargs
  • 13,563
  • 35
  • 109
  • 174
  • 2
    See also http://stackoverflow.com/questions/795286/what-does-do-in-c for the C++ version of this question (asked just yesterday, in fact). – Michael Myers Apr 28 '09 at 15:38
  • 2
    Keep in mind that the C/C++/Java world is pretty evenly divided between people who think it's ugly and confusing and will avoid it like the plague, and people who think you can't really claim to know C, C++ or Java if you can't recognize it and use it without pausing to think. – Paul Tomblin Apr 28 '09 at 15:42
  • 3
    It is generally considered bad form in Java to use it beyond the clearest and simplest of cases. If you find yourself nesting them, you are way out. On the other hand, in the C culture where fast and clever code is valued above clarity, it is considered acceptable. – Yishai Apr 28 '09 at 15:58
  • 20
    answer_to_question = (recognize_operator) ? (social_acceptance) : (condescending_finger_wag) – Dan Apr 28 '09 at 16:34

17 Answers17

218

Yes, it is a shorthand form of

int count;
if (isHere)
    count = getHereCount(index);
else
    count = getAwayCount(index);

It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.

The official name is given in the Java Language Specification:

§15.25 Conditional Operator ? :

The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

Note that both branches must lead to methods with return values:

It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.

So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:

if (someBool)
    doSomething();
else
    doSomethingElse();

into this:

someBool ? doSomething() : doSomethingElse();

Simple words:

booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse 
Community
  • 1
  • 1
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
  • I don't understand what the bottom one does that is wrong. I believe you and all. It just looks the same to me as the original. Is it because they just call another function that may or may not return a value and allow the next code set to run? – johnny May 01 '09 at 16:00
  • 8
    I'm assuming doSomething() and doSomethingElse() are void methods. What that last bit of the spec says is that the ternary operator *must* return a value, so none of the operands can be void methods. – Michael Myers May 01 '09 at 16:32
  • It says a bit more than that. It says the conditional operator isn't allowed where a void method COULD appear. So, for example, the following statements: VALID: String x = (false) ? "X" : "Y"; NOT VALID: (false) ? "X" : "Y"; – kenj0418 Nov 07 '13 at 19:47
  • 4
    It is not erroneous to call it the "ternary operator", just as it is not erroneous (in 2016) to refer to Obama as "the President", even though it is possible that there will be other presidents in the future. – Dawood ibn Kareem Oct 07 '16 at 22:51
  • @DawoodibnKareem - Totally agree and the same JLS we're discussing here says this `The ternary conditional operator ? : (`[§15.25](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25)`)` too. – isank-a Nov 04 '17 at 19:36
  • 3
    @DawoodibnKareem I think Michael deliberately included `the` in the italicisation of `the ternary operator`, and *that's* what he means is erroneous, not that `ternary operator` is erroneous. *The* ternary operator implies that, as Michael says, it is the only one, which in turn could lead one to assume there can be no other ternary operators, which is what Michael is saying is erroneous, and I'd agree, it *would* be an erroneous assumption. – Ghoti and Chips Nov 23 '17 at 00:32
  • Contrary to the assertion that the condition operator is 'shorthand' for anything- **if-else** is a statement, **?:** is used in expressions. If you think of the latter, you'll get confused: as evidenced by the SO questions about getting "not a statement" errors because they wrote `x ? y : z` as a statement. See some of the comments to this very answer. – passer-by Dec 19 '21 at 23:16
  • It's not "erroneous" to call the conditional operator "the operator with three operands", it's just silly - because it says nothing at all about what the operator actually is or does. – passer-by Dec 19 '21 at 23:18
  • so I cannot assign a variable there right, e.g. `x() ? y() : z`, where `z` is a variable? – cryanbhu Feb 22 '22 at 00:40
33

Others have answered this to reasonable extent, but often with the name "ternary operator".

Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.

However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 3
    This answer is technically correct. However, since there is only one ternary operator you often see it referred to as the ternary operator. Even though this name does not convey the complete meaning of the operator, it is a name that has stuck. If you mention the name "ternary operator", programmers know what you are talking about. The spec you mention also refers to this operator as the "Ternary Conditional" which seems more informative. http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.28 – Gary Apr 28 '09 at 16:00
  • 17
    I just think it's worth calling something by its defined name. In particular, if Java ever gets another ternary operator, people who use the term "conditional operator" will still be correct and unambiguous - unlike those who just say "ternary operator". Yes, the phrase "ternary operator" has stuck - my answer is part of an effort to "unstick" it, just as I try to correct the claim that "objects are passed by reference". – Jon Skeet Apr 28 '09 at 16:08
  • 1
    May I direct you to [this page from Oracle](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html) which speaks of three "conditional operators" but only one "ternary operator"? If you want to make it clear which operator you mean, it's probably better to use the name that most people use. (Yes, I know I'm showing up at the party just as the host is washing the last of the dishes). – Dawood ibn Kareem Oct 07 '16 at 23:03
  • @DavidWallace: Using "conditional operator ?:" is better, IMO - will edit to clarify that. But I do think it's worth persuading people to use the actual name of the operator rather than focusing on one aspect of it (how many operands it has) that has nothing to do with its behaviour. (It's also not uncommon for tutorials to be less precise than the specification, which calls `&&` the conditional-and operator, and `||` the conditional-or operator, but uses just "the conditional operator" for `?:`. – Jon Skeet Oct 08 '16 at 07:05
  • I don't know. If someone says "conditional operator" to me, I won't be sure what they mean. Where I come from (the opposite end of the world from you) people just don't call it this. If they say "ternary operator" or "hook operator", then I understand. I admire your ambition, wanting to change the way people talk. If anyone can do it, it's you. But I neither hold out much hope nor see much point. – Dawood ibn Kareem Oct 08 '16 at 07:10
  • @DavidWallace: I would say if someone says to you "the conditional operator" you *should* be clear what they mean - and if they actually mean `&&` or `||` they should have said conditional-and or conditional-or, unless it's absolutely clear from context. If someone said "hook operator" to me I'd have no idea what they meant. And yes, this sort of gradual community improvement *is* possible - 20 years ago, it was very common for people to talk about Java being pass-by-reference; these days, it still crops up but is corrected very quickly. – Jon Skeet Oct 08 '16 at 07:13
  • Yes, I _should_. I probably _don't_. And it might get harder if Java introduces some of the new conditional operators that have been mooted for dealing with nulls. – Dawood ibn Kareem Oct 08 '16 at 07:19
  • @DavidWallace: I'd expect those to get new names, just like in C# there's the "conditional null" operator but "the conditional operator" is still the name for `?:`. – Jon Skeet Oct 08 '16 at 07:26
17

According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.

The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

ConditionalExpression:
        ConditionalOrExpression
        ConditionalOrExpression ? Expression : ConditionalExpression

The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.

The first expression must be of type boolean or Boolean, or a compile-time error occurs.

JRL
  • 76,767
  • 18
  • 98
  • 146
8
condition ? truth : false;

If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.

It is called the Conditional Operator and it is a type of Ternary Operation.

Joe Phillips
  • 49,743
  • 32
  • 103
  • 159
  • 1
    According to [JLS, 15.25. Conditional Operator ? :](https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.25) it's _evaluate_ rather than "return" and _expression_ rather than "parameter". – Gerold Broser Jun 09 '20 at 19:08
5
int count = isHere ? getHereCount(index) : getAwayCount(index);

means :

if (isHere) {
    count = getHereCount(index);
} else {
    count = getAwayCount(index);
}
Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273
5

Not exactly correct, to be precise:

  1. if isHere is true, the result of getHereCount() is returned
  2. otheriwse the result of getAwayCount() is returned

That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.

Also, it's not exactly syntactically equivalent to the if-else version. For example:

String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;

If coded with if-else will always result in more bytecode.

RichN
  • 6,181
  • 3
  • 30
  • 38
  • I believe javac is at liberty to generate the same bytecode. Although you are correct that there are obscure corner cases where they are not equivalent. – Tom Hawtin - tackline Apr 28 '09 at 23:47
  • Yes, of course. For me, the true merit of the conditional operator is the example I've given. The alternative are either: // gasp!! String temp = str1; if (check) temp += str2; else temp += str3; temp += str4; return temp; or handcoding the StringBuilder append operation. The 1st one suffer from serious efficiency issue while the 2nd one is too verbose and is a painstaking effort without much gain. – RichN Apr 29 '09 at 03:31
4

Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.

e.g.:

public class Foo {
    final double    value;

    public Foo(boolean positive, double value) {
        this.value = positive ? value : -value;
    }
}

Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.

Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
3

This construct is called Ternary Operator in Computer Science and Programing techniques.
And Wikipedia suggest the following explanation:

In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.

Not only in Java, this syntax is available within PHP, Objective-C too.

In the following link it gives the following explanation, which is quiet good to understand it:

A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.

In Perl/PHP it works as:
boolean_condition ? true_value : false_value

In C/C++ it works as:
logical expression ? action for true : action for false

This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.

We can simplify the If-Else blocks with this Ternary operator for one code statement line.
For Example:

if ( car.isStarted() ) {
     car.goForward();
} else {
     car.startTheEngine();
}

Might be equal to the following:

( car.isStarted() ) ? car.goForward() : car.startTheEngine();

So if we refer to your statement:

int count = isHere ? getHereCount(index) : getAwayCount(index);

It is actually the 100% equivalent of the following If-Else block:

int count;
if (isHere) {
    count = getHereCount(index);
} else {
    count = getAwayCount(index);
}

That's it!
Hope this was helpful to somebody!
Cheers!

Community
  • 1
  • 1
Randika Vishman
  • 7,983
  • 3
  • 57
  • 80
3

You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:

String s = mayBeNull?.toString() ?: "null";

It would be especially convenient where auto-unboxing takes place.

Integer ival = ...;  // may be null
int i = ival ?: -1;  // no NPE from unboxing

It has been selected for further consideration under JDK 7's "Project Coin."

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
erickson
  • 265,237
  • 58
  • 395
  • 493
  • That operator is not one of my favorites from Project Coin. Limited usefulness, not intuitive to read, and just plain ugly as all get-out. Maybe it would grow on me, though. – Michael Myers Apr 28 '09 at 17:27
  • IIRC< Neal didn't propose it. He just used it as a simple example of how to write a proposal. More details on the project coin mailing list archive. – Tom Hawtin - tackline Apr 28 '09 at 23:48
2

Its Ternary Operator(?:)

The ternary operator is an operator that takes three arguments. The first 
argument is a comparison argument, the second is the result upon a true 
comparison, and the third is the result upon a false comparison.
Darsy
  • 133
  • 1
  • 6
2

Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:

String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";

which is better than using if, else if, else.

Praised
  • 21
  • 2
2

Correct. It's called the ternary operator. Some also call it the conditional operator.

cletus
  • 616,129
  • 168
  • 910
  • 942
1

?: is a Ternary Java Operator.

Its syntax is:

condition ? expression1 : expression2;

Here, the condition is evaluated and

  • condition returns true, the expression1 will execute.

  • condition returns false, the expression2 will execute.

    public class Sonycode { public static void main(String[] args) { double marks = 90; String result = (marks > 40) ? "passed in exam" : "failed in exam"; System.out.println("Your result is : " + result); } }

Output :-

 Your result is :  passed in exam
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
0

Conditional expressions are in a completely different style, with no explicit if in the statement.

The syntax is: boolean-expression ? expression1 : expression2;

The result of this conditional expression is

expression1 if boolean-expression is true;

otherwise the result is expression2.

Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression: max = (num1 > num2) ? num1 : num2;

Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.

cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127

Emmanuel
  • 1
  • 1
0

Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.

Ternary Conditional Operator

Gary
  • 6,357
  • 5
  • 30
  • 36
0

It's the conditional operator, and it's more than just a concise way of writing if statements.

Since it is an expression that returns a value it can be used as part of other expressions.

justinhj
  • 11,147
  • 11
  • 58
  • 104
0

I happen to really like this operator, but the reader should be taken into consideration.

You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.

First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.

Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:

callMethodWhatever(Long + Expression + with + syntax) if conditional

If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.

The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.

When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.

Bill K
  • 62,186
  • 18
  • 105
  • 157