Ternary operator in Java

output is small number

The ternary operator is a simple conditional branching statement. It returns a value based on condition.

int num = 54;
String str = num > 100 ? "big number" : "small number";

num > 100 ? is our condition.

"big number" the first value(before :) will be returned if a condition is true.

"small number" the second value(after :) will be returned if a condition is false. In our case, this value is returned because the condition is false.

Turnery operator can be used with any other data types as well.

public class Main {
public static void main(String[] args) {
boolean b = false;
int num = b ? 7 : 9;
System.out.println(num); // 9
This article is part of the series of articles to learn Java programming language from Tech Lead Academy:

Software Developer, Java Instructor https://www.techleadacademy.io/