15

I came across this syntax:

System.out.println(boolean_variable ? "print true": "print false");
  • What is this syntax with two dots : called?
  • Where can I find info about it?
  • Does it work just for booleans or is it implemented in other different ways?
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Carlo Luther
  • 2,402
  • 7
  • 46
  • 75
  • It is often called "ternary operation/operator", ternary = 3. It is an if-then-else expression, and might be chained: `x > 0.01 ? "positive" : x < -0.01 ? "negative" : "zero"`. Typing: `boolean ? A : B` with result common possible class of A and B. The type of `conditon ? null : ""` is String. – Joop Eggen Jul 04 '13 at 12:48

11 Answers11

55

? : is the conditional operator. (It's not just the : part - the whole of the method argument is one usage of the conditional operator in your example.)

It's often called the ternary operator, but that's just an aspect of its nature - having three operands - rather than its name. If another ternary operator is ever introduced into Java, the term will become ambiguous. It's called the conditional operator because it has a condition (the first operand) which then determines which of the other two operands is evaluated.

The first operand is evaluated, and then either the second or the third operand is evaluated based on whether the first operand is true or false... and that ends up as the result of the operator.

So something like this:

int x = condition() ? result1() : result2();

is roughly equivalent to:

int x;
if (condition()) {
    x = result1();
} else {
    x = result2();
}  

It's important that it doesn't evaluate the other operand. So for example, this is fine:

String text = getSomeStringReferenceWhichMightBeNull();
int usefulCharacters = text == null ? 0 : text.length();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Always assumed it was called ternary operator. Thanks. If you scroll down the link it is also mentioned as `The ternary conditional operator ? :` – rajesh Jul 04 '13 at 12:53
  • 4
    @rajesh: Yes, in the same way that there's the "binary + operator" and "the unary + operator" :) – Jon Skeet Jul 04 '13 at 12:55
  • 'is roughly equivalent to:' why only roughly? Can you name a difference? – Roland Nov 22 '19 at 08:23
  • 1
    @Roland: For that *precise* example, I can't right now - although that doesn't mean there aren't situations I haven't thought of. If the type of `x` were `Integer` instead of `int`, `result1()` returned `Integer` and `result2()` returned `int`, then there would be a very significant difference: the inferred type of the conditional expression would be `int` rather than `Integer`, so the result of `result1()` would be unboxed then reboxed, which could cause a NullPointerException if it returned null. It's that *sort* of subtlety that makes me write "roughly equivalent" to hedge my bets. – Jon Skeet Nov 22 '19 at 08:32
20

It's the conditional operator, often called ternary operator because it has 3 operands: An example would be:

int foo = 10;
int bar = foo > 5 ? 1 : 2; // will be 1
int baz = foo > 15 ? 3 : 4; // will be 4

So, if the boolean expression evaluates to true, it will return the first value (before the colon), else the second value (after the colon).

You can read the specifics in the Java Language Specification, Chapter 15.25 Conditional Operator ?

jlordo
  • 37,490
  • 6
  • 58
  • 83
  • 4
    Also important to note: the expression that is not used is not evaluated. The expression `x != null ? x.Method() : 0` won't trigger a null reference exception when x is null. This is an important advantage over a function that does the same thing as the ternary operator, since all arguments passed to functions are always evaluated. – Craig Gidney Jul 04 '13 at 16:01
4

It's a ternary operator, meaning that instead of having two operands like many other operators, it has three. Wikipedia on Ternary Operation and how it's used in Java. What it boils down to: the boolean operation (or just a variable) is evaluated. If it evaluates to true, the operator returns the value / executes the code before the :, otherwise the one after it.

SBI
  • 2,322
  • 1
  • 17
  • 17
2

That's an if statement.

What's to the left of ? is the condition, what's between the ? and : is the result if the condition is true, and what's to the right of : is the result if the condition is false.

Casteurr
  • 956
  • 3
  • 16
  • 35
2

This is ternary operator (http://en.wikipedia.org/wiki/?:). It can be used anywhere when you need a small if expression.

TulaGingerbread
  • 435
  • 5
  • 15
2

For your questions:

  1. The ?: (both characters together) are called conditional operator (or ternary operator). Only both together will work.
  2. Search for java ternery operator
  3. It only works for boolean

In principle the ternery operator is a shortened if/else. The boolean will be the condition to the if, the part between ? and : is the if branch and the part after this is the else branch.

Please note that the return type of the conditional operator is determined by the first branch.

Uwe Plonus
  • 9,803
  • 4
  • 41
  • 48
1

It's the ternary operator and it works with booleans. It can be used as a shorthand for if-else in some cases, but shouldn't be used for too complicated things as it can be difficult to read.

An example would be assigning value to a variable depending on a condition:

String message = doOperation() ? "Success" : "Error occurred";
System.out.println(message);

In this case, if doOperation returns a boolean telling whether it succeeded or not, the message to be shown can be assigned on a single line.

Please note that this example does not represent good programming practices.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

Its ternary operator.

The ternary operator or ?, is a shorthand if else statement. It can be used to evaluate an expression and return one of two operands depending on the result of the expression.

boolean b = true;
String s = ( b == true ? "True" : "False" );

This will set the value of the String s according to the value of the boolean b. This could be written using an if else statement like this:

boolean b = true;
String s;
if(b == true){
    s = "True";
}else{
    s = "False";
}
Manish Doshi
  • 1,205
  • 1
  • 9
  • 17
1

Its a short form of if-else statement.

It works in this way

(yourCondition ? STATEMENT1 : STATEMENT2)
  • The compiler checks for the condition.
  • IF it returns TRUE then STATEMENT1 will be executed.
  • ELSE STATEMENT2 will be executed.
R9J
  • 6,605
  • 4
  • 19
  • 25
0

The question mark followed by a colon (two dots) is a ternary operator usually called inline if.

In this case it returns a string depending on the value of boolean_variable.

http://en.wikipedia.org/wiki/%3F:

Brecht Yperman
  • 1,209
  • 13
  • 27
0

See here. The ternary operator is similar to an if expression but differs in that it is an expression - it has a return value, while if expressions don't. Sometimes you want to use it to make your code a little less cluttered.

kutschkem
  • 7,826
  • 3
  • 21
  • 56