Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Multiple Ternary operators

I'm studying some Java at the moment at I've come across the following piece of code. I understand how the typical ternary operator (e.g. the line beginning with "boolean a" below), but I can't understand how to read the expression on the line beginning with "boolean b". Any help on how to read this line would be much appreciated! Thanks!

public class Ternary{
    public static void main (String[] args){
        int x = 10;
        int i = 2;
        boolean a = x > 10 ? true: false;
        boolean b = a = true ? ++i > 2 ? true:false:false;
        System.out.print(b);
    }
}
like image 766
John Kilo Avatar asked Feb 14 '23 15:02

John Kilo


1 Answers

Break it up like this:

true ? (++i > 2 ? true 
                : false)
     : false;

So here the testing condition is always set to true. So the branch of the ternary that executes is the ++i > 2 ? true : false part.

This simply checks to see if after incrementing, i is greater than 2. If so, it will return true. Otherwise it will return false.

This whole expression is actually needlessly complex. It can simply be written as such:

boolean b = a = (++ i > 2);

However, the code is probably logically incorrect since this abstruse expression doesn't make that much sense. Since the previous line sets the value of a, I'm assuming that the next line actually intends to test a. So the actual intent might be:

boolean b = a == true ? ++i > 2 ? true : false : false; //notice the ==

In which case you can break it up as:

(a == true) ? (++i > 2 ? true
                       : false)
            : false;

But you don't need to actually do a == true since a is already a boolean, so you can do:

a ? (++i > 2 ? true
             : false)
  : false;

Here, it checks to see if a is true. If it is, it performs the check we already went over (i.e., to see if the incremented value of i is greater than 2), otherwise it returns false.

But even this complicated expression can be simplified to just:

boolean b = a && (++i > 2);
like image 69
Vivin Paliath Avatar answered Feb 16 '23 04:02

Vivin Paliath