Ternary operator in Java
![]() |
Image Source - Google | Image by - examtray.com |
It is a conditional operator in java which takes three operands or it is a one line replacement of if-else statements in java. It becomes more easier for a programmer to use ternary operator in place of if-else statement because it's syntax is quite easier as compared to if-else statements and consumes less space .
Syntax of ternary operator-
variable= (condition) ? expression 1: expression 2;
or
variable = expression 1 ? expression 2: expression 3
here, expression 1 is executed if condition is true and the value of expression 1 is assigned to the variable and if condition is false expression 2 is executed and the value of expression 2 is assigned to the variable, not clear don't worry once you see in the code with a problem statement you will for sure clear with the concept-
flowchart of Ternary operation-
![]() |
Image Source - Google | Image by - geeksforgeeks.com |
let's see first how it is easier from if-else statement by looking on the syntax of if-else statement-
if(condition)
{
//statement -1
}
else
{
//statement -2
}
okay, it is seen clearly from both syntaxes that it is easier than if-else now let's see some programming problems where it(ternary operator) is used-
program 1- "To check if one number is greater than another number".
problem statement- If one number is greater than second number returns true otherwise returns false.
public class MyForloop {
public static void main(String[] args)
{
int a=10;
int b=20;
boolean larger;
larger= a>b ? true: false;
System.out.println("a is greater than b:"+larger);
}
}
a is greater than b:false
another variant of same example-
public class MyForloop {
public static void main(String[] args)
{
int a=10;
int b=20;
String result=(a>b) ? "a is greater than b": "a is smaller than b";
System.out.println(result);
}
}
a is smaller than b
program 2- "To check if one number is greater than another number".
problem statement- If one number is greater than second number increase the value of one number by 100 else decrease the value of second number by 100.
public class MyForloop {
public static void main(String[] args)
{
int a=10;
int b=20;
boolean max;
max=(a>b) ? true: false;
int result = max==true ? a+100: b-100;
System.out.println("a is greater than b: "+max+"\n");
if(max)
{
System.out.println("after increasing the value of a by 100 the value of a is"+result+"\n");
}
else
{
System.out.println("after decreasing the value of b by 100 the value of b is"+result);
}
}
}
a is greater than b: false
after decreasing the value of b by 100 the value of b is-80
Hello, visitor your comments are so helpful for us so do not hesitate just write the comment we read all your comments so don't think your comment goes waste.