Search code examples
javaif-statementnested-if

Can we use '?' operator instead of nested-if condition?


A nested-if condition to be written using the ? : syntax. Is it not an allowed scenario?

Below is the code

        int i=(10>5)?(2<5)?230:456;
        System.out.println("i="+i);

Which I thought would be equal to

if(10>5){
   if(2<5){
        i=230;
   }
   else{
       i=456;
   }
}

My idea was that first 10>5 would be evaluated, and as it is true, it would then verify if 2<5 or not. Now since that is also true, "i" should be assigned to 230. The error message was

ControlFlow.java:10: error: : expected
        int i=(10>5)?(2<5)?230:456;

ControlFlow.java:10: error: ';' expected
        int i=(10>5)?(2<5)?230:456;
                                   ^
ControlFlow.java:11: error: illegal start of expression
        System.out.println("i="+i);
              ^
ControlFlow.java:11: error: ';' expected
        System.out.println("i="+i);

Solution

  • You forgot to add a part of the expression. Try it as follows:

    int i = (10>5) ? ( (2<5) ? 230:456 ) : 0; 
    

    Replace the above 0 to be the desired number you want your variable to be when your first condition (10>5) is false.