CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Java

Java Programming
Control statements
if/else

The syntax of the if/else statement

if (booleanExpression) {statements}
[else if (booleanExpression) {statements}] ...
[else {statements}]

If statements without else if or else clauses

With a single statement

if (subtotal >= 100)
    discountPercent = .2;

With a block of statements


if (subtotal >= 100)
{
    discountPercent = .2;
    status = "Bulk rate";
}

An if statement with an else clause

if (subtotal >= 100)
    discountPercent = .2;
else
    discountPercent = .1;

An if statement with else if and else clauses

if (customerType.equals("T"))
    discountPercent = .4;
else if (customerType.equals("C"))
    discountPercent = .2;
else if (subtotal >= 100)
    discountPercent = .2;
else
    discountPercent = .1;

Nested if statements

if (customerType.equals("R"))
{                                      // begin nested if
    if (subtotal >= 100)
        discountPercent = .2;
    else
        discountPercent = .1;
}                                      // end nested if
else
    discountPercent = .4;

How to code if/else statements

  • An if/else statement, or just if statement, always contains an if clause. It can also contain one or more else if clauses, and a final else clause.
  • If a clause requires more than one statement, you enclose the block of statements in braces. Otherwise, the braces are optional.
  • Any variables that are declared within a block have block scope so they can only be used within that block.

Code that calculates weekly wages.

import java.util.*;

public class WeeklyWages
{
    static Scanner console =
    	new Scanner(System.in);

    public static void main(String[] args)
    {
        double wages, rate, hours;     //Line 1

        System.out.print("Line 2:
        	Enter the working "
                       + "hours: ");   //Line 2
        hours = console.nextDouble();  //Line 3
        System.out.println();          //Line 4

        System.out.print("Line 5:
        	Enter the pay "
                       + "rate: ");    //Line 5
        rate = console.nextDouble();   //Line 6
        System.out.println();          //Line 7

        if (hours > 40.0)              //Line 8
            wages = 40.0 * rate +
                    1.5 * rate *
                    (hours - 40.0);    //Line 9
        else                           //Line 10
            wages = hours * rate;      //Line 11

        System.out.printf("Line 12:
        	The wages are $%.2f %n",
                           wages);    //Line 12
        System.out.println();         //Line 13
    }
}
The console after the program finishes

Previous | Compare numeric variables | Compare string variables | if/else | while | Next