- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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);
- Related Articles
- Java Ternary Operator Examples
- Apply Ternary operator on double value in Java
- Ternary Operator in C#
- Ternary Operator in Python?
- Changing ternary operator into non-ternary - JavaScript?
- Conditional ternary operator ( ?: ) in C++
- Ternary Operator in Dart Programming
- C/C++ Ternary Operator
- What is a Ternary operator/conditional operator in C#?
- What is ternary operator in C#?
- How Ternary operator in PowerShell Works?
- What is a ternary operator (?:) in JavaScript?
- How to overload python ternary operator?
- Difference between the Ternary operator and Null coalescing operator in php
- Ternary operator ?: vs if…else in C/C++
