Skip to main content
ICT
Lesson A8 - Control Structures
 
Main   Previous Next
 

J. Conditional Operator page 12 of 17

  1. Java provides an alternate method of coding an if-else statement using the conditional operator. This operator is the only ternary operator in Java, as it requires three operands. The general syntax is:

(condition) ? statement1 : statement2;

  1. If the condition is true, statement1 is executed. If the condition is false, statement2 is executed.

  2. This is appropriate in situations where the conditions and statements are fairly compact.

    // returns the larger of two integers
    int max(int a, int b)
    {
       (a > b) ? return a : return b;
    }

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.