
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
Find Smallest of Three Numbers Using Ternary Operators in Java
To find the smallest from three given numbers using ternary operator, create a temporary variable to store the result of first comparison operation between two numbers. Then, perform second comparison operation between the result of first operation (i.e. temp) and third number to get the final result.
Let's understand the problem statement with an example ?
Example Scenario:
Input: nums = 20, 35, 10; Output: res = 10
What is Ternary Operator?
The conditional operator in Java is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The syntax of this operator is as shown below ?
variable x = (expression) ? value if true: value if false
Example 1
This is a Java program that illustrates how to find smallest of the three numbers using ternary operator.
public class SmallestOf3NumsUsingTernary { public static void main(String args[]) { int a, b, c, temp, result; a = 10; b = 20; c = 30; temp = a < b ? a:b; result = c < temp ? c:temp; System.out.println("Smallest number is:: " + result); } }
Output
Smallest number is:: 10
Example 2
This is another example that finds the smallest of three number using ternary operator. Here, we are passing the comparison logic in a user-defined function.
public class SmallestOf3NumsUsingTernary { public static void main(String args[]) { int a = 100, b = 20, c = 35; int smallest = findSmallest(a, b, c); System.out.println("Smallest number is:: " + smallest); } // User-defined function to find the smallest of three numbers public static int findSmallest(int a, int b, int c) { int temp = a < b ? a : b; return c < temp ? c : temp; } }
Output
Smallest number is:: 20