Home> Java> javaTutorial> body text

What does ?: in java mean?

下次还敢
Release: 2024-04-25 20:54:22
Original
714 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:

condition ? value1 : value2;
Copy after login

where:

  • conditionis a Boolean expression that determines whether to selectvalue1orvalue2.
  • value1is the expression to select ifconditionistrue.
  • value2is the expression to select ifconditionisfalse.

How it works

?: The operator works through the following steps:

  1. First, the conditional expression is evaluated.
  2. If the conditional expression istrue, then selectvalue1.
  3. If the conditional expression isfalse, selectvalue2.

Example

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

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

In this example, the conditional expressionage >= 18istrue, so the ?: operator selectsvalue1, which is "adult".

Note

?: operator is a shortened version of theif-elsestatement, but it can only return a single value. If you need to return complex results based on conditions, you should use theif-elsestatement or theswitch-casestatement.

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!