Question

Possible Duplicate:
What is the Java ?: operator called and what does it do?

hi, may i know what is the java ?: operator called, i am trying to find information on how it works but i do not know what is it called, typing ?: in google dont give a correct result.

Was it helpful?

Solution

It's the conditional operator.

Some people call it the ternary operator, but that's really just saying how many operands it has. In particular, a future version of Java could (entirely reasonably) introduce another ternary operator - whereas the name of the operator is the conditional operator.

See section 15.25 of the language specification:

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

OTHER TIPS

ternary is the word you are looking for.

JLS 15.25 Conditional Operator ? :

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

JLS 15.28 Constant Expression

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • The ternary conditional operator ? :

Thus, the Java Language Specification officially calls it the (ternary) conditional operator.


Java Coding Conventions - Indentation

Here are three acceptable ways to format ternary expressions:

alpha = (aLongBooleanExpression) ? beta : gamma;  

alpha = (aLongBooleanExpression) ? beta
                                 : gamma;  

alpha = (aLongBooleanExpression)
        ? beta 
        : gamma;  

This is known as the ternary or conditional operator (depending on who you ask)

It allows you to do single line conditional statements such as in this pseudocode

print a==1 ? 'a is one' : 'a is not one'

As Jon Skeet notes, it's proper name is the conditional operator, but it has 3 operands so is a ternary operator.

Do you mean for an if else statement? Look up the word ternery.

int x = 2;
String result = x > 1 ? "a" : "b";

equates to:

int x = 2;
String result = "";
if (x > 1) {
   result = "a";
} else {
   result = "b" ;
}

it's called the conditional operator but very often called ternary operator (which is a class of operators all taking 3 operands however in Java only one such exits namely the conditional operator)

some times it's called the tertiary operator which is simply a language (english) usage error

Eventhouigh this is for c# the same applies to Java

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top