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

How to use question mark in java

下次还敢
Release: 2024-05-01 19:39:15
Original
977 people have browsed it

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:

condition ? trueExpression : falseExpression;
Copy after login
  • 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:

int x = 5;
int y = x > 0 ? 10 : 20;
Copy after login

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:

variable != null ? variable.method() : defaultValue;
Copy after login
  • variable: The variable to check.
  • method: The method to be called.
  • defaultValue: The default value returned if variable is null.

For example:

String name = null;
String safeName = name != null ? name : "Unknown";
Copy after login

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