CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Control

Control Statements
if/else and switch
if/else

The syntax of the if/else statement


if (booleanExpression) {statements}
[else if (booleanExpression) {statements}] ...
[else {statements}]
  • Simplest statement to make decision
  • Boolean expression appears within parentheses
  • Space between keyword if and opening parentheses
  • Execution always continues to next independent statement
  • Use double equal sign (==) to determine equivalency

Pitfall: Misplacing a Semicolon in an if Statement

  • No semicolon at end of first line of if statement
    • if (someVariable == 10)
    • Statement does not end there
  • When semicolon follows if directly
    • Empty statement contains only semicolon
    • Execution continues with the next independent statement

Pitfall: Using the Assignment Operator Instead of the Equivalency Operator

  • Attempt to determine equivalency
    • Using single equal sign
    • Rather than double equal sign
    • Illegal
  • Can store Boolean expression's value in Boolean variable
    • Before using in if statement

Pitfall: Attempting to Compare Objects Using the Relational Operators

  • Use standard relational operators to compare values of primitive data types
    • Not objects
  • Can use equals and not equals comparisons (== and !=) with objects
    • To compare objects' memory addresses instead of values

Making Accurate and Efficient Decisions

Range check:
  • Series of if statements that determine whether:
    • Value falls within specified range
  • Java programmers commonly place each else of subsequent if on same line
  • Within nested if...else
    • Most efficient to ask most likely question first
    • Avoid asking multiple questions

Conditional (? :) Operator

It is a tertiary operator, which means that it takes three arguments.

Syntax
expression1 ? expression2 : expression3

The expressions1 is a logical expression.

If expression1 = true, then the result of the condition is expression 2; otherwise, the result of the condition is expression 3

example: max = (a>=b) ? a:b;
Previous | if/else | switch | Application | Next