I don't understand the logic of code that is given below

I have run this code in compiler and getting the output as 1 but I don’t understand how it will be 1. Please explain with answer.

public class Main {
    public static void main(String args[]) {
        int a = 10;
        int b = 2;
        System.out.println((a < b) ? a++ : --b);
    }
}

>Solution :

The ternary operator ?: will check the condition (a < b), since it is false, it will execute the expression after :, which is --b.

--b will subtract b by 1, and return the value after subtraction, which is 1.

Leave a Reply