Home >Java >javaTutorial >What does ? in java mean?
The "?" in Java represents the ternary operator, which is used to return different values based on a Boolean expression: a true value or a false value is returned based on whether the Boolean expression is true. It is a shorthand form of if-else statement and is used to concisely perform conditional judgments.
The meaning of ? in Java
The ? in Java is a function called the ternary operator (or conditional operator) special operator. It allows returning different values based on a given Boolean expression. Its syntax is as follows:
<code class="java"><布尔表达式> ? <真值> : <假值></code>
Usage
The first operand of the ternary operator is a Boolean expression that evaluates to true or false. If the Boolean expression is true, the operator returns the second operand (a true value); otherwise, it returns the third operand (a false value).
Example
The following example demonstrates how to use the ternary operator:
<code class="java">int age = 25; String message = age >= 18 ? "成年人" : "未成年人";</code>
In this example, if age
Greater than or equal to 18, message
will be set to "Adult"; otherwise, it will be set to "Minor".
Alternative Usage
The ternary operator is the shorthand form of the if-else
statement. The above example can be rewritten using the if-else
statement as:
<code class="java">int age = 25; String message; if (age >= 18) { message = "成年人"; } else { message = "未成年人"; }</code>
However, the ternary operator is often more concise, especially for the single-row case.
The above is the detailed content of What does ? in java mean?. For more information, please follow other related articles on the PHP Chinese website!