If-Else Absolute Value

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

  • What is the absolute value of -9?
    • +9
  • What is the absolute value of +9?
    • +9

If-Else Absolute Value

An if statement can be used to compute absolute values:

if ( value < 0 )
  abs = -value;
else
  abs = value;

This is awkward for such a simple idea. The following does the same thing in one statement:

abs = (value < 0 ) ? -value : value ;

This statement uses a conditional operator. The right side of the = is a conditional expression. The expression is evalutated to produce a value, which is then assigned to the variable, abs.

true-or-false-condition ? value-if-true : value-if-false

It works like this:

  1. The conditional expression evaluates to a single value.
  2. That value will be one of two choices:
    • If the true-or-false-condition is true, then use the expression between ? and :
    • If the true-or-false-condition is false, then use the expression between : and the end .

Here is how it works with the above example:

double value = -34.569;
double abs;

abs = (value < 0 )   ?   -value : value ;
      -------------       ------
      1. condition         2.  this is evaluated,
         is true               to +34.569
                      
----
3.  The +34.569 is assigned to abs

The conditional expression is a type of expression. It asks for a value to be computed but does not by itself change any variable. In the above example, the variable value is not changed.

QUESTION 2:

Given

int a = 7, b = 21;

What is the value of:

a > b ? a : b 

(Remember, even though it looks funny, the entire expression stands for a single value.)