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.
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>
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>
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!