Why is a colon operator used?

Question mark and colon in Java

  1. Use question marks and colon operators in Java
  2. Use nested question marks and colon operators in Java

This tutorial introduces the use of question marks and colon operators in Java and lists some sample code to help understand the subject.

The question mark and colon operators are collectively referred to as ternary operators in Java because they work with three operands.

It is the shorthand version of the instruction in Java and can be used as a one-line instruction for decision making. Let's look at some examples.

Use question marks and colon operators in Java

The ternary operator consists of three segments. The first is a conditional expression that returns a Boolean value. The second and third values ​​are the values ​​before and after the colon. It returns the value before the colon when the conditional expression is evaluated as. Otherwise the value is returned after. The syntax is below.

See the example below.

Output:

We can get the return value of any type from the ternary operator. In the following example, we pass string values ​​and get a returned string value based on the condition.

Output:

The following example is a use case of the ternary operator in Java. We use this one-line conditional statement to check that the given string is in lowercase and convert it to uppercase if the string is in lowercase. Otherwise the original string is returned.

Output:

This is another use case of the ternary operator where we check whether the given integer is a positive integer or not and return a string value. See the example below.

Output:

Use nested question marks and colon operators in Java

In this example, we're using the nested ternary operator to see if we can do it like with the statement. Here we first check whether the given integer is a positive integer, then check whether it is between a given range and return a string value. See the example below.

Output:

Related Article - Java Operator

  • Difference between i ++ and ++ i operators in Java