# Conditionals in Java

### Boolean expressions

A *boolean expression* is an expression that evaluates either true or false. A boolean expression may use

- equality operators (==, !=),
- relational operators (>, >=, <, <=) or
- logical operators (!, &&, ||).

*Equality and relational operators* compare two values (operands), and return boolean (true/false) results. The operands could be of types such as int, double, etc., as long as the operator is defined on such types.

int a = 3, b = 4; boolean c; c = (a == b); c = (a != b);

*Logical operators* take boolean operands and produce boolean results, as shown in the truth table below. NOT operator (!) takes one operand, while AND (&&) and OR (||) take two operands. NOT has higher precedence than AND and OR.

a |
b |
!a |
a && b |
a || b |

false |
false |
true |
false |
false |

false |
true |
true |
false |
true |

true |
false |
false |
false |
true |

true |
true |
false |
true |
true |

boolean a = false, b = false; int c = 3, d = 4; boolean e; e = !a && (c == d); e = (c >= d) || a || b;

The following are some general rules of the operator precedence.

- Arithmetic operators have higher precedence than relational operators.
- Relational operators have higher precedence than logical operators.
- Parentheses can force the order of precedence.

### If-else statements

An if-statement starts with “if” and a boolean expression, followed by a block statement. Several statements can be grouped into a block statement which is enclosed in braces.

int a = 3, b = 4; if (a <= b) { System.out.println(a + “ <= ” + b + “ evaluates to be ”); System.out.println(a <= b); }

Note that, indentation means nothing except to the human reader.

An if-else statement takes care of both cases when the condition is true or false.

int a = 3, b = 4, min; if (a <= b) min = a; else min = b;

In the following we define a class MinThree which takes three integers and output the minimum value.

import java.util.Scanner; public class MinThree { int a, b, c, min; Scanner scan = new Scanner(System.in); a = scan.nextInt(); b = scan.nextInt(); c = scan.nextInt(); if (a < b && a < c) min = a; else if (b < c) min = b; else min = c; System.out.println("Minimum value " + min); }

In this example, we use the java.util.Scanner class to get inputs from the user. The nextInt() method reads an integer from the input. Related document:

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

### Conditional Operator

A *conditional operator* uses a boolean condition to determine which of two expressions is evaluated. It has three parts (one condition and two expressions) which are connected with “? :”. For example,

int a = 3, b = 4, c = 5; int min2 = (a < b) ? a : b; int min3 = (a < b && a < c) ? a : ((b < c) ? b : c);

The statement

min2 = (a < b) ? a : b;

is equivalent to the following:

if (a < b) min2 = a; else min2 = b;