Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplifying Conditional Operators

Tags:

java

My friend wrote this code for an assignment in his programming class:

public class test {
   public static void main(String args[]) {
      double x = 0.9;
      double y = 0.1;
      boolean truth = x < 1 && x > 0 && y < 1 && y > 0;
      System.out.println(truth);
   }
}

I'm wondering (for myself) if there's a way to simplify the conditional operators in this line specifically:

boolean truth = x < 1 && x > 0 && y < 1 && y > 0;
like image 204
Aaron Avatar asked Jun 02 '26 13:06

Aaron


2 Answers

Your only option for a one-liner is to use parenthesis. Personally, I prefer multiple statements to make things much clearer:

boolean isXInRange = x > 0 && x < 1;
boolean isYInRange = y > 0 && y < 1;
boolean truth = isXInRange && isYInRange;
like image 148
Justin Niessner Avatar answered Jun 04 '26 03:06

Justin Niessner


No, but it might be made clearer (opinion):

boolean truth = (0 < x && x < 1 && 0 < y && y < 1);

The flipping of the zero check makes it easy to read as 0 < x < 1. Is that clearer? A very little bit.

The parenthesis is a style choice. Since boolean expressions are always parenthesized in if statements and while loops, I find it clearer to always parenthesize boolean operators.

like image 21
Andreas Avatar answered Jun 04 '26 03:06

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!