< Prev
Next >



Conditional Operator





Java conditional operator is also called ternary operator because it has three operands, such as -




Syntax of conditional operator -


boolean-condition ? first expression : second expression;






Conditional operator example.


class A
{
public static void main(String... ar)
{
int a=10, b=20;

int result =a>b ? 0 : 10;
System.out.println(result);

String str= a<b ? "a is less than b" : "a is greater than b";
System.out.println(str);

System.out.println(a>b ? 10 : 100.50);
System.out.println(a>b ? 'y' : 'n');

}
}
Output
10
a is less than b
100.5
n





Any expression of a conditional operator could even be a call to a method but this method mustreturn a value.
class Flower
{

public boolean hasAFlower()
{
return true;
}

public String getColor()
{
return "The color of flower is blue";
}

public static void main(String... ar)
{
Flower ob= new Flower();

System.out.println(ob.hasAFlower() ? ob.getColor(): "Doesn't have a flower");
}
}


Output-



The color of flower is blue

In the last code, the first expression of the conditional operator is a call to a method getColor(), which has returned us a String class object.



Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter




< Prev
Next >
< Logical Operators
instanceof operator>
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2