Home > Java > javaTutorial > body text

What does ?: in java mean?

下次还敢
Release: 2024-04-25 20:54:22
Original
784 people have browsed it

?: operator (ternary operator) is a conditional operator that selects one of two values ​​based on the result of a Boolean expression. Here's how it works: A conditional expression is evaluated. If the condition is true, value1 is selected, otherwise value2 is selected. This operator is a shortened version of the if-else statement that returns only a single value.

What does ?: in java mean?

In Java, the meaning of ?: operator

?: operator, also known as triple Meta operator is a conditional operator used to select one of two values ​​based on the result of a conditional expression. The syntax is as follows:

<code class="java">condition ? value1 : value2;</code>
Copy after login

where:

  • condition is a Boolean expression that determines whether to select value1 or value2.
  • value1 is the expression to select if condition is true.
  • value2 is the expression to select if condition is false.

How it works

?: The operator works through the following steps:

  1. First, the conditional expression is evaluated.
  2. If the conditional expression is true, then select value1.
  3. If the conditional expression is false, select value2.

Example

The following example demonstrates how to use the ?: operator:

<code class="java">int age = 25;
String result = age >= 18 ? "成年" : "未成年";
System.out.println(result); // 输出:成年</code>
Copy after login

In this example, the conditional expression age >= 18 is true, so the ?: operator selects value1, which is "adult".

Note

?: operator is a shortened version of the if-else statement, but it can only return a single value. If you need to return complex results based on conditions, you should use the if-else statement or the switch-case statement.

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template