Contents


Unit 8: Conditional operators and control statements

Make decisions in your code

Comments

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 1. Relational and conditional operators
OperatorUsageReturns true if...
>a > ba is greater than b
>=a >= ba is greater than or equal to b
<a < ba is less than b
<=a <= ba is less than or equal to b
==a == ba is equal to b
!=a != ba is not equal to b
&&a && ba and b are both true, conditionally evaluates b (if a is false, b is not evaluated)
||a || ba or b is true, conditionally evaluates b (if a is true, b is not evaluated)
!!aa is false
&a & ba and b are both true, always evaluates b
|a | ba or b is true, always evaluates b
^a ^ ba 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 conditional evaluates to true, Block 1 is executed and the program jumps to the next statement after the final curly brace (which is indicated by // End). If conditional does not evaluate to true, then conditional2 is evaluated. If conditional2 is true, then Block 2 is executed, and the program jumps to the next statement after the final curly brace. If conditional2 is not true, then the program moves on to conditional3, and so on. Only if all three conditionals fail is Block 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 conditional evaluates to true, statementIfTrue is executed; otherwise, statementIfFalse 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.

For further exploration

The Java Tutorials: Operators

The Java Tutorials: Control Flow Statements

What is the Java ?: operator called and what does it do?

Java — Decision Making

IBM Code: Java journeys

Previous: Strings and operatorsNext: Loops


Downloadable resources


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java development
ArticleID=1036617
ArticleTitle=Unit 8: Conditional operators and control statements
publish-date=09142016