Advertisement



< 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





  • An expression of a conditional operator can be a method call.

  • 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 -





    < Prev
    Next >
    < Logical Operators
    instanceof operator>



    Advertisement

    Please Subscribe

    Please subscribe to our social media channels for daily updates.


    Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




    Advertisement



    Notifications



    Please check our latest addition

    C#, PYTHON and DJANGO


    Advertisement