Short version of if condition in Java ? : ;-)

Sometimes we want to write some codes by shorter way, for example today I want to show you short version of IF statment (if condition)


 

package shortif;
public class ShortIF {
    public static void main(String[] args) {
        int max; int a = 5; int b = 2;
        
        if (a > b) max = a;
        else max = b;        
        System.out.println("#1. Max value = " + max);
        //OR short version
        a=10; b=20;
        <strong>max = (a &gt; b) ? a : b;  </strong> 
        System.out.println("#2. Max value = " + max);
    }
}

(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, 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.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *