Məqalələr

Ternary Operatorun maraqlı şəkildə istifadəsi

ternary-operator-in-java
Written by Mushfiq Mammadov
package az.mm.test;

public class Test {

    public static void main(String[] args) {
        Integer i = 2;
        System.out.println("withIfElse:     " + withIfElse(i));
        System.out.println("withSwitchCase: " + withSwitchCase(i));
        System.out.println("ternary:        " + withTernary(i));
    }

    static Number withIfElse(Integer i){
        Number number;
        if(i == 1)
            number = Number.ONE;
        else if(i == 2)
            number = Number.TWO;
        else if(i == 3)
            number = Number.THREE;
        else if(i == 4)
            number = Number.FOUR;
        else if(i == 5)
            number = Number.FIVE;
        else
            number = null;

        return number;
    }

    static Number withSwitchCase(Integer i){
        Number number;
        switch (i){
            case 1: number = Number.ONE;   break;
            case 2: number = Number.TWO;   break;
            case 3: number = Number.THREE; break;
            case 4: number = Number.FOUR;  break;
            case 5: number = Number.FIVE;  break;
            default: number = null;
        }

        return number;
    }

    static Number withTernary(Integer i){
        Number number = i==1? Number.ONE:
                        i==2? Number.TWO:
                        i==3? Number.THREE:
                        i==4? Number.FOUR:
                        i==5? Number.FIVE:
                        null;
        return number;
    }
}


enum Number {
    ONE, TWO, THREE, FOUR, FIVE
}

About the author

Mushfiq Mammadov

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.