Home  >  Article  >  Java  >  How to use question mark in java

How to use question mark in java

下次还敢
下次还敢Original
2024-05-01 19:39:15645browse

The question mark operator (?) has two main uses in Java: Conditional operator (ternary operator), which is used to return true or false expressions based on conditions. Null check, used to check whether a variable is null and avoid null pointer exceptions, returning the default value.

How to use question mark in java

Using Question Marks in Java

The question mark (?) has two main uses in Java:

1. Conditional operator (ternary operator)

The ternary operator uses the following syntax:

<code class="java">condition ? trueExpression : falseExpression;</code>
  • condition: The Boolean expression to evaluate.
  • trueExpression: The expression that is evaluated and returned if condition is true.
  • falseExpression: The expression that is evaluated and returned if condition is false.

For example:

<code class="java">int x = 5;
int y = x > 0 ? 10 : 20;</code>

In this case, if x is greater than 0, y will be equal to 10, otherwise it will be equal to 20.

2. Null check and prevent null pointer exception

In Java, you can use the question mark operator to check whether a variable is null and avoid errors caused by accessing null references. resulting in a NullPointerException.

Syntax:

<code class="java">variable != null ? variable.method() : defaultValue;</code>
  • variable: The variable to check.
  • method: The method to be called.
  • defaultValue: The default value returned if variable is null.

For example:

<code class="java">String name = null;
String safeName = name != null ? name : "Unknown";</code>

In this case, if name is null, safeName will be assigned the value "Unknown", otherwise it will be assigned the value of name.

The above is the detailed content of How to use question mark in java. 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