Java “? :” operator? [duplicate]

混江龙づ霸主 提交于 2019-12-18 08:46:54

问题


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.


回答1:


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.




回答2:


ternary is the word you are looking for.




回答3:


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;  



回答4:


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.




回答5:


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" ;
}



回答6:


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



来源:https://stackoverflow.com/questions/3085681/java-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!