#16 Java Control Statements Part 3

Ternary (?) Operator

Declared as follows: 
Exp1 ? Exp2 : Exp3;

  Exp1 would be a boolean expression, and Exp2 and Exp3 are expressions of any type other than     void. The type of Exp2 and Exp3 must be the same, though. Notice the use and placement of the   colon. Consider this example, which assigns absval the absolute value of val:

absval = val < 0 ? -val : val; // get absolute value of val

Here, absval will be assigned the value of val if val is zero or greater. If val is negative, then absval will be assigned the negative of that value (which yields a positive value).The same code written using the if-else structure would look like this:
if(val < 0) absval = -val; 
else absval = val; 

e.g. 2 This program divides two numbers, but will not allow a division by zero. 
// Prevent a division by zero using the ?.
 class NoZeroDiv {
 public static void main(String args[]) { 
int result; 
for(int i = -5; i < 6; i++) {
 result = i != 0 ? 100 / i : 0;
 if(i != 0) 
System.out.println("100 / " + i + " is " + result); 
        } 
     } 
}

The output from the program is shown here:

100 / -5 is -20 
100 / -4 is -25 
100 / -3 is -33 
100 / -2 is -50 
100 / -1 is -100 
100 / 1 is 100 
100 / 2 is 50 
100 / 3 is 33
100 / 4 is 25 
100 / 5 is 20

Please note:


result = i != 0 ? 100 / i : 0;

result is assigned the outcome of the division of 100 by i. However, this division takes place only if i is not zero. When i is zero, a placeholder value of zero is assigned to result. Here is the preceding program rewritten a bit more efficiently. It produces the same output as before.

// Prevent a division by zero using the ?. class
 NoZeroDiv2 {
public static void main(String args[]) {
for(int i = -5; i < 6; i++)
if(i != 0 ? true : false)
System.out.println("100 / " + i + " is " + 100 / i);
   }
 }

Notice the if statement. If i is zero, then the outcome of the if is false, the division by zero is prevented, and no result is displayed. Otherwise the division takes place.

Comments

Popular Posts