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 &amp;&amp; (c == d);
e = (c &gt;= 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 &lt;= b)
{
  System.out.println(a + “ &lt;= ” + b + “ evaluates to be ”);
  System.out.println(a &lt;= 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 &lt;= 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 &lt; b &amp;&amp; a &lt; c)
    min = a;
  else if (b &lt; c)
    min = b;
  else
    min = c;
  System.out.println(&quot;Minimum value &quot; + 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 &lt; b) ? a : b;
int min3 = (a &lt; b &amp;&amp; a &lt; c) ? a : ((b &lt; c) ? b : c);

The statement

min2 = (a &lt; b) ? a : b;

is equivalent to the following:

if (a &lt; b)
  min2 = a;
else
  min2 = b;

Comments

comments