Home >Java >javaTutorial >What does ? in java mean?

What does ? in java mean?

下次还敢
下次还敢Original
2024-04-27 00:54:15929browse

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.

What does ? in java mean?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does : in java mean?Next article:What does : in java mean?