
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Ternary Operator in Java
A ternary operator uses 3 operands and it can be used to replace the if else statement. This can be done to make the code simpler and more compact.
The syntax of the ternary operator is given as follows −
Expression ? Statement 1 : Statement 2
In the above syntax, the expression is a conditional expression that results in true or false. If the value of the expression is true, then statement 1 is executed otherwise statement 2 is executed.
A program that demonstrates the ternary operator in Java is given as follows.
Example
public class Example { public static void main(String[] args) { Double num = -10.2; String str; str = (num > 0.0) ? "positive" : "negative or zero"; System.out.println("The number " + num + " is " + str); } }
Output
The number -10.2 is negative or zero
Now let us understand the above program.
The number num is defined. Then the ternary operator is used. If num is greater than 0, str stores “positive”, otherwise it stores "negative or zero". Then this is displayed for the specified number. The code snippet that demonstrates this is given as follows.
Double num = -10.2; String str; str = (num > 0.0) ? "positive" : "negative or zero"; System.out.println("The number " + num + " is " + str);