Booleans, Relational Operators, and Comparison

(information via eIMACS.com)

Booleans

Booleans allow code to be executed conditionally. This means that the program branches depending on certain circumstances.

Boolean values are declared by using the keyword boolean.

They can only be assigned two values, true and false. Boolean values may be entered directly into Java expressions as boolean literals. Usually, they are not directly entered.

boolean a = true;
System.out.println("a is " + a);

This returns → a is true

Relational Operators

Java allows for relational operators to be used in expressions evaluating to true or false. The purpose of an expression with relational operators is to compare the values of the two operands.

int a = 11;
boolean b = (a>10);
System.out.println("b is " + b);

This returns → b is true

int a = 7;
boolean b = (a>10);
System.out.println("b is " + b);

This returns → b is false

In the first example, 11 is greater than 10, so the relational expression is true. In the second example, 7 is not greater than 10, so the relational expression is false.

The 6 relational operators are as follows:

  • < strictly less than
  • <= less than or equal to
  • > strictly greater than
  • >= greater than or equal to
  • == equal to AKA identity operator
  • != not equal to

All operands must be floating point numbers or integers. Integers are converted into floating point numbers when comparisons take place. Relational expressions are evaluated only after any arithmetic expressions.

Comparing Strings

Equals()

Java has an equals() method that can be called to determine whether two strings are the same. They must be identical, including case. The value returned is just like a boolean value: true or false.

String a = "fred";
String b = "Fred";
System.out.println(a.equals(b));

This returns → false

Note that the equals() method is necessary for Strings. == cannot be used for Strings.

compareTo()

Java has a compareTo() method that can be called on to determine the order of two strings in a dictionary. The technical term for this order is lexicographical order. The values returned are relative to the string in the parenthesis. The options for values are:

  • negative numbers if the outside string precedes the inside string.
  • 0 if the outside and inside string are the same string.
  • positive numbers if the inside string precedes the outside string.
String a = "fred";
String b = "Fred";
String c = "Frederick";

System.out.println(a.compareTo(b));
System.out.println(b.compareTo(c)<0);

This returns → 32

true

32 is a positive number, so “Fred” comes before “Fred.” Then, “Fred” comes before “Frederick” because it’s shorter, so the second is a negative number which the relational operator checks and determines is true.