The value of a variable often depends on whether a particular Boolean expression is or is not true.
Java ternary operator let’s you assign a value to a variable based on a boolean expression.Ternary operator (also known as the conditional operator) can be used as an alternative to the Java if-then-else syntax.
For example lets take the below common operation which is setting the value of a variable to the maximum of two quantities. In Java you might write
if (a > b) { maxVal = a; } else { maxVal = b; }
Using the conditional operator you can rewrite the above example in a single line like below
maxVal = (a > b) ? a : b;
Here (a > b) ? a : b is an expression which returns one of two values, either ‘a’ or ‘b’ based on the condition (a > b). If it is true the first value ‘a’ is returned. If it is false ‘b’ is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.
Syntax of Ternary Operator
result = Condition ? value1 : value2
As per the Sun documentation, if the condition is true then assign the value of value1 to the result, else assign value2 to the result. Both value1 and value2 should be of same value type.
Ternary Operator Example
Lets check whether the value entered is greater than 5 or not
import java.util.*; class TernaryOperatorExample { public static void main(String args[]) { System.out.println("Please enter a value to check"); Scanner s=new Scanner(System.in); int val=s.nextInt(); String st=(val>5? val+">5":val+"<5"); System.out.println(st); } }
Output :
Please enter a value to check 3 3<5
Calling a function
Lets take a look into the other example where we will be calling a function as well. We will be getting input from the user and will call the check() method to check if it is odd or even
package com.javainterviewpoint; import java.util.Scanner; public class TernaryExample { public static void main(String args[]) { System.out.println("Please enter a value to check if it is Even or Odd"); Scanner s=new Scanner(System.in); int val=s.nextInt(); //Check if the entered value is even or odd System.out.println("The value entered is a "+(check(val)?"Even ":"Odd ")+"Number"); } public static boolean check(int val) { if((val%2)==0) return true; else return false; } }
Output :
Please enter a value to check if it is Even or Odd 2 The value entered is a Even Number
Leave a Reply