Before you begin

This unit is part of the “Intro to Java programming” learning path. Although the concepts discussed in the individual units are standalone in nature, the hands-on component builds as you progress through the units, and I recommend that you review the prerequisites, setup, and unit details before proceeding.

Unit objectives

  • Know when and how to use relational operators, conditional operators, and control statements
  • Understand the concept of variable scope and its basic rules
  • Become familiar with the ternary operator

Relational and conditional operators

The Java language gives you operators and control statements that you can use to make decisions in your code. Most often, a decision in code starts with a Boolean expression— that is, one that evaluates to either true or false. Such expressions use relational operators, which compare one operand to another, and conditional operators.

Table 1 lists the relational and conditional operators of the Java language.

Table 3. Relational and conditional operators
Operator Usage Returns true if…
> a > b a is greater than b
>= a >= b a is greater than or equal to b
(less-than a (less-than b a is less than b
(less-than= a (less-than= b a is less than or equal to b
== a == b a is equal to b
!= a != b a is not equal to b
&& a && b a and b are both true, conditionally evaluates b (if a is false, b is not evaluated)
|| a || b a or b is true, conditionally evaluates b (if a is true, b is not evaluated)
! !a a is false
& a & b a and b are both true, always evaluates b
| a | b a or b is true, always evaluates b
^ a ^ b a and b are different

The if statement

Now that you have a bunch of operators, it’s time to use them. This code shows what happens when you add some logic to the Person object’s getHeight() accessor:

public int getHeight() {
  int ret = height;
  // If locale of the computer this code is running on is U.S.,
  if (Locale.getDefault().equals(Locale.US))
    ret /= 2.54;// convert from cm to inches
  return ret;

If the current locale is in the United States (where the metric system isn’t in use), it might make sense to convert the internal value of height (in centimeters) to inches. This (somewhat contrived) example illustrates the use of the if statement, which evaluates a Boolean expression inside parentheses. If that expression evaluates to true, the program executes the next statement.

In this case, you only need to execute one statement if the Locale of the computer the code is running on is Locale.US. If you need to execute more than one statement, you can use curly braces to form a compound statement. A compound statement groups many statements into one — and compound statements can also contain other compound statements.

Variable scope

Every variable in a Java application has scope, or localized namespace, where you can access it by name within the code. Outside that space the variable is out of scope, and you get a compile error if you try to access it. Scope levels in the Java language are defined by where a variable is declared, as shown in Listing 1.

Listing 1. Variable scope

public class SomeClass {
  private String someClassVariable;
  public void someMethod(String someParameter) {
    String someLocalVariable = "Hello";

    if (true) {
      String someOtherLocalVariable = "Howdy";
    someClassVariable = someParameter; // legal
    someLocalVariable = someClassVariable; // also legal
    someOtherLocalVariable = someLocalVariable;// Variable out of scope!
  public void someOtherMethod() {
    someLocalVariable = "Hello there";// That variable is out of scope!


Within SomeClass, someClassVariable is accessible by all instance (that is, nonstatic) methods. Within someMethod, someParameter is visible, but outside of that method it isn’t, and the same is true for someLocalVariable. Within the if block, someOtherLocalVariable is declared, and outside of that if block it’s out of scope. For this reason, we say that Java has block scope, because blocks (delimited by { and }) define the scope boundaries.

Scope has many rules, but Listing 1 shows the most common ones. Take a few minutes to familiarize yourself with them.

The else statement

Sometimes in a program’s control flow, you want to take action only if a particular expression fails to evaluate to true. That’s when else comes in handy:

public int getHeight() {
  int ret;
  if (gender.equals("MALE"))
    ret = height + 2;
  else {
    ret = height;
    Logger.getLogger("Person").info("Being honest about height...");
  return ret;

The else statement works the same way as if, in that the program executes only the next statement that it encounters. In this case, two statements are grouped into a compound statement (notice the curly braces), which the program then executes.

You can also use else to perform an additional if check:

if (conditional) {
  // Block 1
} else if (conditional2) {
  // Block 2
} else if (conditional3) {
  // Block 3
} else {
  // Block 4
} // End

If conditionalconditional evaluates to true, Block 1Block 1 is executed and the program jumps to the next statement after the final curly brace (which is indicated by // End). If conditionalconditional does not evaluate to true, then conditional2conditional2 is evaluated. If conditional2conditional2 is true, then Block 2Block 2 is executed, and the program jumps to the next statement after the final curly brace. If conditional2conditional2 is not true, then the program moves on to conditional3conditional3, and so on. Only if all three conditionals fail is Block 4Block 4 executed.

The ternary operator

The Java language provides a handy operator for doing simple if / else statement checks. This operator’s syntax is:

(conditional) ? statementIfTrue : statementIfFalse;

If conditionalconditional evaluates to true, statementIfTruestatementIfTrue is executed; otherwise, statementIfFalsestatementIfFalse is executed. Compound statements are not allowed for either statement.

The ternary operator comes in handy when you know that you need to execute one statement as the result of the conditional evaluating to true, and another if it doesn’t. Ternary operators are most often used to initialize a variable (such as a return value), like so:

public int getHeight() {
  return (gender.equals("MALE")) ? (height + 2) : height;

The parentheses following the question mark aren’t strictly required, but they do make the code more readable.

Previous: Strings and operatorsNext: Loops