Java Ternary Operator

The ternary operator is a shorthand way of writing an if-else statement. It takes the form of a question mark (?) and a colon (:), and can be used to assign a value to a variable based on a condition. The basic syntax of the ternary operator is as follows:

variable = (condition) ? value1 : value2;

For example, you could use the ternary operator to check whether a number is positive or negative as follows:

int num = 5;
String result = (num > 0) ? "positive" : "negative";
System.out.println("The number is " + result);

In this case, the condition is “num > 0”, and if the condition is true, the variable result will be assigned the value “positive”. If the condition is false, result will be assigned the value “negative”. The program will then print “The number is positive”, since num is 5.

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author