2. Java Programming Basics

What We Will Cover


Illuminations

Homework Questions?

Questions from last class?

2.1: Data and Expressions

Objectives

At the end of the lesson the student will be able to:

  • Create variables and assign them values
  • Define the data type of a variable
  • Use expressions in programs

2.1.1: Data Types

  • Every variable has a data type associated with it
    • Tells the compiler how to store the data
  • Two main kinds of types in Java: Primitive and Class

Primitive Data Types

  • Simplest types
  • Atomic values -- cannot decompose into other types
  • Integer data types: byte, short, int, long
    • Default type is int
    • Literal values assigned with "=" sign
    • long integer types have "L" or "l" after the number
    • For example:
    •     int i = -215;
          long max = 12147483648L;
  • Character data type: char
    • char data type is actually a type of integer
    • Represents Unicode character set (letter, digits, symbols)
    • Unicode includes all ASCII codes plus additional ones for languages with an alphabet other than English
    • For example:
    •     char letterA = 65;
          char letterB = 0x0042;
          char letterC = 'C';
  • Floating-point types: float, double
    • Floating-point numbers follow standard IEEE 754-1985
    • double is the default floating-point type
    • Type float needs an "F" or "f" during assignment
    • For example:
    •     float pi = 3.14159F;
          double fraction = 1.0 / 3.0;
  • Boolean type: truth values (i.e. true, false)
    • For example:
    •     boolean truth = true;

Type Name Kind of Value Memory Used Size Range
byte integer 1 byte -128 to 127
short integer 2 bytes -32768 to 32767
int integer 4 bytes -2,147,483,648 to 2,147,483,647
long integer 8 bytes -9,223,372,036,854,775,808 to 9,223,374,036,854,775,807
char single character (Unicode) 2 bytes "all" Unicode characters
float floating point 4 bytes +/- 3.4028... x 1038 to
+/- 1.4023... x 10-45
double floating point 8 bytes +/- 1.767... x 10308 to
+/- 4.940... x 10-324
boolean true or false 1 byte Not applicable

2.1.2: Variables

About Variables

  • A variable is a named location (container) to store data
  • Name corresponds to a location in memory
  • Variables can hold only one type of data (such as int or char)
  • Using variables requires two steps:
    • Declaration
    • Assignment
  • These two steps can be combined into one program statement

Declaring Variables

  • All Java program variables must be declared before using them
  • Variable declaration associates a name with a storage location in memory
  • Also specifies the type of data it will store
  • Type Variable_1, Variable_2, ...;
    
  • For example, the following declares three integer variables:
  • int sum, number1, number2;
    

Assigning Values to Variables

  • Use the assignment operator ("equals sign"): =
  • variable = expression;
  • Assigns value of expression (right side) to the variable (left side)
  • Can have the same variable on both sides of an equals sign
  • int count = 10;    // initialize counter to ten
    count = count + 1; // increment counter
    
  • Note that the value of the variable changed in the second line
  • Reading variables from memory does not change them
  • Values placed into a variable replace previous values
  • Cannot erase a memory location

Assigning Initial Values to Variables

  • Initial values may or may not be assigned when variables are declared:
  • //These may not be initialized when declared
    //and have unknown values
    int sum, number1, number2;
    
    //These are initialized when declared
    int sum = 0;
    int number1 = 5, number2 = 10;
    
  • Java assigns default values to variables, except local variables inside methods
    • Integer (byte, short, int, long): 0
    • Floating-point (float, double): 0.0
    • Character (char): '\u0000'
    • Boolean: false
    • Objects: null
  • Good programming practice: explicitly initialize variables when declared.

Constant Variables

  • Java uses the keyword final to indicate a variable that cannot change
  • Usually implemented as a public static final
  • public static final int MY_CONSTANT = 10;
  • static means the variable is part of a class and not an object
    • Will discuss more later

2.1.3: Expressions

Expression -- a part of a program that returns a value

  • Consists of constants, variables, operators, parentheses and methods.
    • Will discuss methods next week
    int sum, number1, number2;
    number1 = 5;
    number2 = 10;
    sum = number1 + number2;
    
  • In the last line number1 returns the value 5 and number2 returns the value 10
  • number1 + number2 is an expression that returns the integer value 15

Examples of Expressions

Math Expression Java Expression
mc2
m * c * c
2(salary + bonus) 2 * (salary + bonus)
1

time + 3mass
1 / (time + 3 * mass)
a - 7

t + 9v
(a - 7) / (t + 9 * v)

Arithmetic

  • Arithmetic operators:
    • + and - for addition and subtraction
    • * for multiplication
    • / for division
    • % for modulus (integer remainder)
    • No operator for exponentiation (use Math.pow())
  • Integer division truncates remainder
    • 7 / 5 evaluates to 1
  • Modulus operator % returns the remainder
    • Used with integer types
    • Returns the remainder of the division of a by b
    • For example:
    • int a = 15; b = 12, c;
      c = a % b;
      
    • c has the value 3, the remainder when 15 is divided by 12

Abbreviated Assignment Expressions

  • Any statement of form: variable = variable <op> (expression);
  • May be written in an abbreviated form: variable <op>= expression;
  • <op> is one of: +, -, *, /, or %
  • For example:
  • sum = sum + 5;
    
  • Can be written as:
  • sum += 5;
    

Increment and Decrement Operators

  • Unary increment operator: ++
    • Increments variable’s value by 1
    • Preincrement adds 1 before using value in an expression
    • For example: ++i
    • Post-increment uses current value of expression then adds 1
    • For example: j++
  • Unary decrement operator: --
    • Predecrement subtracts 1 before using value in an expression
    • For example: --i
    • Post-decrement uses current value of expression then subtracts 1
    • For example: j--

Precedence and Associativity

  • Some arithmetic operators act before others (e.g., multiplication before addition)
    • Java expressions follow rules similar to real-number algebra
  • Arithmetic operators processed in algebraic order:
    1. Parentheses ( )
    2. Unary operators: +, -, ++, --
    3. Multiplication, division, modulus: *, /, %
    4. Addition, subtraction: +, -
  • Binary operators of same precedence evaluated left to right
  • Use parentheses to force precedence
    • Do not clutter expressions with parentheses when the precedence is correct and obvious
    • However, when in doubt use parentheses
  • Example: Find the average of three variables a, b and c
    • Do not use: a + b + c / 3
    • Use: (a + b + c ) / 3

Numerical Accuracy

  • Computers store numbers using a fixed number of bits
  • Not every real (floating-point) number can be encoded precisely
  • Infinite number of bits would be required to precisely represent any real number
  • For example, if a computer can represent up to 10 decimal digits, the number 0.9 may be stored as 0.90000004 if that is the closest it can come to 0.9
  • System.out.println(.8F + .1F);
    System.out.println(.8 + .1);
    
  • Integers, on the other hand, are encoded precisely
  • If the value 2 is assigned to an int variable, its value is exactly 2
  • However, integers can run out of room
  • Causes values to roll-over from highest to lowest
  • What is displayed by the following code?
  • public class Rollover {
        public static void main(String[] args) {
            int x = 2147483647;
            System.out.println(x);
            x = x + 1;
            System.out.println(x);
        }
    }
    
  • Java has math classes for numbers of any desired accuracy

2.1.4: Casting

Cast: change the data type of the returned value of an expression

  • Cast means to change the data type of a value returned by an expression
  • Java is a strongly-typed language and checks for compatible data types when compiling
  • To put a value of a different type in a variable, must convert it
  • Casting only changes the type of the returned value -- not the type of the variable
  • For example:
  • double x;
    int n = 5;
    x = n;
    
  • Since n is an integer and x is a double, the value returned by n must be converted to type double before it is assigned to x

Implicit Casting

  • Casting is done automatically (implicitly) when a narrower-type is assigned to a broader-type
  • Data type hierarchy (from narrowest to broadest):
  • byte => short => int => long => float => double
                    /
             char =/
    
  • For example:
  • double x;
    int n = 5;
    x = n;
    
  • Value returned by n is cast to type double, then assigned to x
  • x contains 5.000...
  • Called implicit casting because it is done automatically
  • Data type of variable n is unchanged -- still an int

Implicit Casting in an Expression

  • Some expressions have a mix of data types
  • All values implicitly cast to the highest level before the calculation
  • For example:
  • double a;
    int n = 2;
    float x = 5.1F;
    double y = 1.33;
    a = (n * x) / y;
    
  • n and x are automatically cast to type double before performing the arithmetic

Explicit Casting

  • Explicit casting changes the data type for a single use of the variable
  • Precede the variable name with the new data type in parentheses:
  • (<data type>) variableName
    
  • Data type is changed only for the single use of the returned value
  • For example:
  • int n;
    double x = 2.0;
    n = (int) x;
    
  • Value of x is converted from type double to integer before assigning the value to n
  • Explicit casting is required to assign a higher type to a lower type

  • ILLEGAL: Implicit casting to a lower data type
  • int n;
    double x = 2.1;
    n = x; // illegal in java
    

    Illegal since x is double, n is an int, and double is a higher data type than int

  • LEGAL: Explicit casting to a lower data type
  • int n;
    double x = 2.1;
    n = (int) x; // legal in java
    
  • Can use an explicit cast even when an implicit one will be done

Casting a char to an int

  • Casting a char value to int produces the ASCII/Unicode value
  • For example, what would the following display?
  • char answer = 'Y';
    System.out.println(answer);
    System.out.println((int) answer);
    
  • Answer:
  • >y
    >89
    

Truncation When Casting double to Integer type

  • Converting (casting) a double to integer type does not round -- it truncates
  • Fractional part is lost (discarded, ignored, thrown away)
  • For example:
  • int n;
    double x = 3.99999;
    n = (int) x; // x truncated
    
  • Value of n is 3

Truncation in Integer Division

  • No truncation if at least one of the values is of type float or double
  • All values are promoted to the highest data type
  • Truncation does occur if all the values in a division are integers
  • For example:
  • int a = 4, b = 5, c;
    double x = 1.5, y;
    y = b / x; //value returned by b is cast to double
               //value of y is about 3.33333
    c = b / a; //all values are ints so the division
               //truncates: the value of c is 1
    

2.1.5: Strings

  • Strings are objects in Java
    • Will discuss later how this affects their use
  • However, they have some special sytax to make their use easier
  • String literals are made by enclosing a sequence of characters in double quotes
  • For example:
  • "abc"   "b"   "3.14159"   "$3.95"   "My name is Ed"
  • You can assign a value to a String like a primitive type
  • String message = "Please enter an identification code";
  • Also, you can concatenate two strings using the "+" operator
  • "Java" + " rules!"

2.1.6: Summary

  • Java has eight primitive data types:
  • Type Bytes Use
    byte 1 Very short integers from -128 to 127.
    short 2 Short integers from -32,768 to 32,767.
    int 4 Integers from -2,147,483,648 to 2,147,483,647.
    long 8 Long integers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
    float 4 Single-precision, floating-point numbers from -3.4E38 to 3.4E38 with 6 or 7 significant digits.
    double 8 Double-precision, floating-point numbers from -1.7E308 to 1.7E-324 with from 14 to 15 significant digits.
    char 2 A single Unicode character that’s stored in two bytes.
    boolean 1 A true (1) or false (0) value.

  • Java uses the following operators for arithmetic
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • Results of integer division is truncated
  • Must use modulus operator (%) to get the remainder value
  • Operators have the same precedence as in algebra
    1. Parenthesis: ( )
    2. Unary operators: +, -
    3. Multiplication, division, modulus: *, /, %
    4. Addition, subtraction: +, -
  • More complex mathematical operations are available using the Math class
  • Variables store a value that can change as a program executes.
  • Constants store a value that cannot change.
  • Variables and constants must be declared before use.
  • To initialize a variable or constant, declare a name and assign a value.
  • Simple assignment statements have a variable, equals sign and an expression.
  • variable = expression;
  • The expression is computed before the assignment
  • Java has assignment variations of the form:
  • variable <op>= expression;
  • You can explicitly cast values of an expression to a different type.
  • You must use an explicit cast when assigning a broader type to a narrower type.

Exercise 2.1

Lets go through these one at a time. Take one minute to prepare an answer and then we will discuss it.

  1. Given the following code, which statement is true?
  2. int a, b = 1;
    

    1. Variable a is not declared
    2. Variable b is not declared
    3. Variable a is declared but not initialized
    4. Variable b is declared but not initialized
    5. Neither variable is declared nor initialized

  3. What is the value returned by the following expressions?
  4. - -1-3 * 10 / 5-1;
    

    1. -8
    2. -6
    3. 7
    4. 8
    5. 10

  5. Starting with the common code:
  6. int n = 3;
    int m = 4;
    int result;
    

    What will be the value of m and result after each of these executes?

    1. result = n * ++m; //preincrement m
    2. result = n * m++; //postincrement m
    3. result = n * --m; //predecrement m
    4. result = n * m--; //postdecrement m

2.2: Console I/O

Objectives

At the end of the lesson the student will be able to:

  • Display information to a console
  • Get user input from the command line
  • Convert strings into numbers

2.2.1: Printing to a Console

  • Two useful prewritten methods are print() and println()
  • Their function is to display data
  • The difference between the two methods is that:
    • print() leaves the cursor positioned after the last character
    • println() positions the cursor on a new line
  • Cursor position determines where the next character is displayed
  • System.out.println("Hello, world!");
    
  • In this statement, out is the name of an object in a Java class named System
  • System is automatically created whenever a Java program is executed
  • System.out lets a program know to send data to the standard output stream
    • Usually the video display screen
  • The data to display is passed to the method within parenthesis

2.2.2: Importing Classes

About Classes and Packages

  • To make it easier to write programs, Java has many libraries
  • These libraries contain prewritten code
  • Referred to as the Java Application Programming Interface (API)
  • Recall that all Java code is stored in classes
  • Groups of related classes are organized into packages

Some Commonly Used Packages

Package Name Description
java.lang Provides classes fundamental to Java.
java.io Provides classes to read and write files.
java.txt Provides classes to handle text, dates, and numbers
java.util Provides classes to work with collections and miscellaneous utilities.
javax.swing Provides classes to create graphical user interfaces and applets.

Importing Classes and Packages

  • Classes in the java.lang package are available automatically
  • To use other classes, you must import them
  • import packagename.ClassName;
        or
    import packagename.*;
    
  • Using the '*' wildcard will import all classes in a package
  • For example:
  • import java.text.NumberFormat;
    import javax.swing.JOptionPane;
    import javax.swing.JFrame;
    import javax.swing.*;
    

2.2.3: Using System.in

  • System.in is the foundation object for entering data into a program
  • Recall that System.out is used to send data to the standard output stream
    • Usually the video display screen
  • Similarly, System.in is used to get data from the standard input stream
    • Usually the keyboard

  • Streams deliver data as a stream of individual data bytes to the program
  • Java uses a number of objects to manage the streams of data
  • To use the stream objects, we need to import the java.io package:
  • import java.io.*;
  • System.in is an InputStream object that has basic read methods
  • Processes the input data by accepting one or more bytes at a time
    • Each byte is processed as an int
    • Allows using -1 as an end-of-file (EOF) marker
  • Use an InputStreamReader to convert int values of InputStream to char values
  • To program this, we "wrap" an InputStreamReader around System.in
  • InputStreamReader isr = new InputStreamReader(System.in);
    
  • Although we can now work with the char data types, easier to use strings
  • Class BufferedReader provides a method to read one line at a time
  • To program this, we "wrap" a BufferedReader around our InputStreamReader
  • BufferedReader br = new BufferedReader(isr);
    
  • Can now use the readLine() method to read one line at a time
  • String data = br.readLine();
    
  • Method readLine() collects all the input until the Enter key is pressed
  • Putting everything together into one program, we have:
import java.io.*;

public class LineInput {
    public static void main(String[] args) throws IOException {
        // set up for basic input stream
        InputStreamReader isr =
            new InputStreamReader(System.in);
        // need to use readLine()
        BufferedReader br = new BufferedReader(isr);

        System.out.print("Type a line and press Enter: ");
        String data = br.readLine();
        System.out.println("You entered: " + data);
    }
}
  • Note that we added a line of code after the main() method header
  • throws IOException
  • This code is required at this point for us to use the readLine() method
    • Will review the reason later in this lesson

2.2.4: Reading Numbers

  • Method readLine() accepts input from the user as strings
  • Often need to convert String values to numeric types
  • Java provides some very handy String conversion methods
  • Can use these methods to convert our string input into numbers

Conversion to Primitive Values

Return
Type
Conversion Method Example
int Integer.parseInt(String) Integer.parseInt("1234")
long Long.parseLong(String) Long.parseLong("123456")
float Float.parseFloat(String) Float.parseFloat("123.45")
double Double.parseDouble(String) Double.parseDouble("123.45")

An Example

  • Consider an application to sum (add) two numbers

import java.io.*;

public class SumOf2 {
    public static void main(String[] args) throws IOException {
        double num1, num2;
        String data;

        InputStreamReader isr =
                new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);

        System.out.print("First number: ");
        data = br.readLine();
        num1 = Double.parseDouble(data);

        System.out.print("Second number: ");
        data = br.readLine();
        num2 = Double.parseDouble(data);

        System.out.println(num1 + " + " + num2
                + " = " + (num1 + num2));
    }
}

  • We setup for reading from the command line as usual
  • InputStreamReader isr =
            new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    
  • We read each number as a string
  • System.out.print("First number: ");
    data = br.readLine();
    
  • Final step is to convert the String to a double
  • num1 = Double.parseDouble(data);
    
  • Then we can use the numbers using arithmetic operators
  • System.out.println(num1 + " + " + num2
            + " = " + (num1 + num2));
    

2.2.5: Summary

  • You can use the System.out object to print to the console
    • System.out.print() leaves the cursor positioned after the last character
    • System.out.println() positions the cursor on a new line
  • To make it easier to write programs, Java has many libraries of prewritten code
  • You can make use of this code by importing packages
  • import packagename.ClassName;
        or
    import packagename.*;
    
  • For example, to import all the java.io libraries
  • import java.io.*;
  • Alternatively, you can use the fully qualified package name
  • You can use System.in to read data from the command line
  • To use System.in, you need to need to import the java.io.IOException class
  • To convert bytes to chars, you wrap System.in in an InputStreamReader
  • To buffer the input and use the readLine() method, you also wrap the stream in a BufferedReader
  • Thus most code to read from the command line starts like:
  • public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
    ...
    }
    
  • To read a string from the command line, you use the readLine() method
  • String input = br.readLine();
  • If you need a number as an input, you convert the String to a number

Return
Type
Conversion Method Example
int Integer.parseInt(String) Integer.parseInt("1234")
long Long.parseLong(String) Long.parseLong("123456")
float Float.parseFloat(String) Float.parseFloat("123.45")
double Double.parseDouble(String) Double.parseDouble("123.45")

Exercise 2.2

Take one minute to prepare an answer the following question.

Write a main() method to read an int from the keyboard and display it to the console.

2.3: Making Decisions

Objectives

At the end of the lesson the student will be able to:

  • Use relational expressions to produce boolean values
  • Use if Statements
  • Use if-else Statements
  • Use switch Statements

2.3.1: Flow of Control

  • Determines the order a program executes instructions
  • All programs can be written with three control flow elements:
  1. Sequence - continue with the next instruction
    • Sequence is the default operation
  2. Selection - a choice between at least two
    • Either continue with the next instruction
    • Or jump to some other instruction
    • if
      if-else
      if-else if-else if- ... - else
      switch
      
  3. Repetition - a loop (repeats a block of code)
    At the end of the loop:
    • Either go back and repeat the block of code
    • Or continue with the next instruction after the block
    • while
      do-while
      for
      
  • First we will consider Java's selection statements
  • Since selection requires choosing between alternatives, we now examine Java's selection criteria

2.3.2: Relational Operators

  • Relational operators used to produce a boolean value
  • Math Name Java Example Result
    = Equal to == 5 == 10
    2 == 2
    false
    true
    Not equal to != 5 != 10
    2 != 2
    true
    false
    < Less than < 5 < 10
    5 < 5
    5 < 2
    true
    false
    false
    Less than or equal to <= 5 <= 10
    5 <= 5
    5 <= 2
    true
    true
    false
    > Greater than > 5 > 10
    5 > 5
    5 > 2
    false
    false
    true
    Greater than or equal to >= 5 >= 10
    5 >= 5
    5 >= 2
    false
    true
    true

Java Comparison Methods for String Class

  • "==" does not act like you may think for String objects
  • "==" tests to see if the storage addresses of the two objects are the same
  • Must use .equals method to test if the strings contents are equal
  • String s1 = new String("Fred");
    String s2 = new String("Fred");
    System.out.println(s1 == s2);      // prints false
    System.out.println(s1.equals(s2)); // prints true
    
  • Method equals() is case sensitive
  • Use equalsIgnoreCase() to ignore case

Numerical Accuracy Problem

  • Problems can occur with relational expressions using floating-point numbers
  • Tests for equality (==) should be avoided using floating-point numbers
  • Reason is that many decimal numbers (e.g. 0.1) cannot be represented exactly
  • For example:
  • Cannot find file: examples/Inexact1.java
  • Thus, testing for equality for such numbers may fail
  • When equality of non-integer values is needed, there is a possible solution
  • Can test that the absolute value of the difference is less than some small number
  • Instead of:
  • operandOne == operandTwo
    
  • Replace the condition with:
  • Math.abs(operandOne - operandTwo) < EPSILON
    
  • For example, instead of:
  • x/y == .35
    
  • Replace the condition with:
  • Math.abs(x/y - .35) < .0000001
    

2.3.3: Logical Operators

  • Sometimes must consider several logical values at same time
  • Logical operators allow you to consider multiple cases and to change conditions
  • Use ! operator to reverse value of expression
  • Use && to AND two or more conditions
  • Use || to OR two or more conditions
  • ! Operator
    If expr is... Then ! expr is... Example Result
    true false !true false
    false true !(5 < 2) true

  • && operator returns true only if expressions on both sides are true
  • && Operator
    If expr1 is... And expr2 is... Then expr1 && expr2 is... Example Result
    true true true 5 < 10 && 5 > 2 true
    true false false 5 < 10 && 5 < 2 false
    false true false 5 > 10 && 5 > 2 false
    false false false 5 > 10 && 5 < 2 false

  • || operator returns true if either expression is true
  • || Operator
    If expr1 is... || expr2 is... Then expr1 || expr2 is... Example Result
    true true true 5 < 10 || 5 > 2 true
    true false true 5 < 10 || 5 < 2 true
    false true true 5 > 10 || 5 > 2 true
    false false false 5 > 10 || 5 < 2 false

Common Mistake with Logical Expressions

Logical expressions often read like "normal" English. However, Java syntax requires more detail. For example we might say in English: A equals B or C, but the corresponding boolean expression is A == B || A == C

2.3.4: Branching and Boolean Expressions

  • Branching implies there is more than one choice for the next instruction
  • Which branch is taken depends on a test condition
  • A test condition evaluates to either true or false
    • If a test is true
      • then do this
    • otherwise it is false
      • so do something else
  • Variables that are either true or false are called boolean variables
  • Boolean expressions return either true or false

2.3.5: Using the if Statement

  • Executes a section of code if a condition is true
  • if (boolean expression is true) {
       Action1 //execute only if true
    }
    
  • If condition is not true, Java skips the code
  • What is displayed by running the following code?
  • import java.awt.*;
    import javax.swing.*;
    
    public class IfThen extends JApplet {
      private JTextArea out = new JTextArea();
    
      public void init() {
        getContentPane().add(out, BorderLayout.CENTER);
    
        //-----------------------------
        int errorCount = 1;
        out.append("OK so far\n");
        if (errorCount > 0) {
          out.append("Oops! We got an error!\n");
        }
        out.append("What happened?\n");
      }
    }
    
    See it!

  • Note that code is indented between the if and } for readability
  • What would be displayed if intErrorCount = 0?

Multiple Conditions

  • With logical operators (&&, ||, !), can test for multiple conditions
  • For example, can create condition that displays only if two conditions are true
  • What is displayed by running the following code?
  • import java.awt.*;
    import javax.swing.*;
    
    public class IfThen2 extends JApplet {
      private JTextArea out = new JTextArea();
    
      public void init() {
        getContentPane().add(out, BorderLayout.CENTER);
    
        //-----------------------------
        int x = 1, y = 2;
    
        out.append("OK so far\n");
        if (x == 1 && y == 2) {
          out.append("Its true!\n");
        }
        out.append("What happened?");
      }
    }
    
    See it!

2.3.6: Using the if-else Statement

  • Tests a condition to determine if true or false
  • if (boolean expression is true) {
       Action1 //execute only if true
    } else {
       Action2 //execute only if false
    }
    
  • If true, executes the first block {...} of code
  • If false, executes second block of code
  • What is displayed by running the following code?
  • import java.awt.*;
    import javax.swing.*;
    
    public class IfElse extends JApplet {
      private JTextArea out = new JTextArea();
    
      public void init() {
        getContentPane().add(out, BorderLayout.CENTER);
    
        //-----------------------------
        int errorCount = 0;
    
        out.append("OK so far\n");
        if (errorCount > 0) {
          out.append("Oops! We got an error!\n");
        } else {
            out.append("Everything is still OK\n");
        }
        out.append("What happened?");
        //-----------------------------
      }
    }
    
    See it!

Nested If Statements

  • Can include if statements within other if statements
  • Each if statement evaluated only if outer condition is met
  • What is displayed for the following?
  • import java.awt.*;
    import javax.swing.*;
    
    public class IfNested extends JApplet {
      private JTextArea out = new JTextArea();
    
      public void init() {
        getContentPane().add(out, BorderLayout.CENTER);
    
        //-----------------------------
        double temp = 77.0;
        if (temp > 65) {
          if (temp > 75) {
            out.append("Temperature is too hot\n");
          } else {
            out.append("Temperature is just right\n");
          }
        } else {
          out.append("Its cold!\n");
        }
        //-----------------------------
      }
    }
    
    
    See it!

  • Nested conditionals can be confusing if too deep
  • Rule of thumb: no more than three deep

2.3.7: if-else if-else if-...-else Statement

  • Tests multiple conditions until the first true condition is found
  • If true condition is found, executes code within the block
  • What is displayed by running the following code?
  • import java.awt.*;
    import javax.swing.*;
    
    public class IfElseIf extends JApplet {
      private JTextArea out = new JTextArea();
    
      public void init() {
        getContentPane().add(out, BorderLayout.CENTER);
    
        //-----------------------------
        double temp = 77.0;
        if (temp > 75) {
          out.append("Temperature is too hot!");
        } else if (temp > 65) {
          out.append("Temperature is just right.");
        } else {
          out.append("Its cold!");
        }
        //-----------------------------
      }
    }
    
    
    See it!

  • Note nesting is now only one level deep

"Dangling Else" Problem

    if (Expression1)
        if (Expression2)
            Statement1
    else
        Statement2
    
  • Indentation is misleading
  • if (Expression1)
        if (Expression2)
            Statement1
        else
            Statement2
    
  • Common mistake is not matching else with the correct if
  • Rule: else always matches the last unmatched if
  • Use braces to force a different grouping

2.3.8: Using the switch Statement

  • Executes a section of code depending on value of a variable
  • switch (integerExpression)
    {
       case label1:
          statements
          break;
       case label2:
          statements
          break;
       ...
       case labeln:
          statements
          break;
       default:
          statements
          break;
    }
    
  • Code executes if variable matches the case label value
  • Use default for default conditions
  • What is displayed by running the following code?
  • import java.awt.*;
    import javax.swing.*;
    
    public class Switch extends JApplet {
      private JTextArea out = new JTextArea();
    
      public void init() {
        getContentPane().add(out, BorderLayout.CENTER);
    
        //-----------------------------
        final int PARCEL_POST = 0;
        final int UPS = 1;
        final int FED_EX = 2;
        int shippingOption = UPS;
    
        switch (shippingOption) {
          case PARCEL_POST:
            out.append("Delivery in two weeks.");
            break;
          case  UPS:
            out.append("Delivery in three days.");
            break;
          case FED_EX:
            out.append("Overnight delivery.");
            break;
          default:
            out.append("It may never get there!");
        }
        //-----------------------------
      }
    }
    
    
    See it!

Exercise 2.3

Take one minute to prepare an answer the following questions.

  1. What will happen if we attempt to compile and run the following code?
  2. class IfTest {
        public static void main(String[] args) {
            if (true)
            if (false)
            System.out.println("first");
            else
            System.out.println("second");
        }
    }
    
  3. What, if anything, is wrong with the following code?
  4. class SwitchTest {
        public static void main(String[] args) {
            int x = 1;
            switch(x) {
                case 1:
                case 2:
                case 0:
                default:
                case 5:
            }
        }
    }
    

2.4: Repetition

Objectives

At the end of the lesson the student will be able to:

  • Select the appropriate repetition structure in a Java program
  • Use while Loops
  • Use do-while Loops
  • Use for Loops
  • Programs often need to repeat series of steps
  • This process called looping

2.4.1: while Loops

  • General loop structure:
    • Initialization code
    • Loop condition -- evaluated during the loop
    • Loop body
  • while loop Syntax:
  • //Initialization
    ...
    while (loopTest) { //loop condition
       //loop body
       ...
    }
    
  • Initialization statements usually precede the loop for while loops
  • Checks loopTest at start of every loop iteration
  • Continues as long as loopTest is true
  • Note that if the loop condition is initially false then loop body never executes
  • Several logical organizations and uses of loops
    • Counter-controlled loops
    • Sentinel-controlled loops
    • Infinite loops

Counter-Controlled Loop

  • Executed a specified number of times
  • Use a variable in the loop test called the counter
  • Counter must be incremented every time the body of the loop is executed
  • What is displayed for the following?
  • class Counter5 {
        public static void main(String[] args) {
            //Initialization
            int count = 0;
            while (count < 5) { //loop condition
                //loop body
                ++count;
                System.out.println(count);
            }
            System.out.println("After count= " + count);
        }
    }
    

Sentinel-Controlled Loop

  • Used when we do not know in advance how many iterations are needed
  • Commonly used for reading input from a user or file
  • Use a sentinel value to tell the program that there is no more data
  • Looping continues as long as the data value read is not the sentinel
  • When the sentinel is read, execution continues at the statement after the loop
  • Following example loops to sum positive numbers entered by the user
import java.io.*;

public class SumInput {
    public static void main(String[] args) throws IOException {
        InputStreamReader isr =
                new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);

        System.out.println("Enter positive numbers");

        // Initialization
        double input = 0.0;
        double total = 0.0;
        while (input >= 0.0) { // Loop condition
            // Loop body
            total = total + input;
            String data = br.readLine();
            input = Double.parseDouble(data);
        }
        System.out.println("Total:" + total);
    }
}
  • Sentinel variable is input
  • Sentinel value is any negative number
  • Terminates when the user enters a negative number

Infinite loops

  • Common error: infinite loop
  • Sometimes we do want loops to continue indefinitely
  • How would we intentionally write an infinite while-loop?

2.4.2: do-while Loops

  • Syntax:
  • //Initialization
    ...
    do {
       //loop body
       ...
    } while (loopTest); //loop condition
    
  • Initialization code may precede loop body
  • Loop test is after loop body
  • Loop must execute at least once (minimum of at least one iteration)
  • May be either counting- or sentinel-controlled loop
  • Use when you want to force a minimum of one iteration

Sentinel-Controlled-Loop Example

import java.io.*;

public class SumInputDo {
    public static void main(String[] args) throws IOException {
        InputStreamReader isr =
                new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);

        System.out.println("Enter positive numbers");

        // Initialization
        double input = 0.0;
        double total = 0.0;
        do { // Loop body
            total += input;
            String data = br.readLine();
            input = Double.parseDouble(data);
        } while (input >= 0.0); // Loop condition
        System.out.println("Total:" + total);
    }
}

2.4.3: for Loops

  • Syntax:
  • for (initialization; loopTest; incrementExpression) {
       //loop body
       ...
    }
    
  • Initialization, loop-test, and increment-expression are part of the syntax
  • Mostly used for counter-controlled loops
  • Execution sequence as follows:
    1. When for statement reached -- initialization executes
    2. Check if loop-test is true
      • if true then continue with Step 3
      • Otherwise, continue with Step 6
    3. Execute block containing the loop body
    4. When end of loop body is reached, execute the incrementExpression
    5. Return to Step 2
    6. Loop is finished: Continue with statements after the loop

Counter-Controlled-Loop Example

  • What is displayed by the following code?
  • class CounterFor {
        public static void main(String[] args) {
            for (int count = 0; count < 5; ++count) {
                System.out.println(count);
            }
        }
    }
    
  • Note that code is indented in the loop body for readability

Stepping Down

  • Can also count downwards
  • Positive numbers step higher (+inf) and negative numbers step lower (-inf)
  • What is displayed with the following?
  • class CountDown {
        public static void main(String[] args) {
            int count = 0;
            for (count = 5; count > 0 ; --count) {
                System.out.println(count);
            }
            System.out.println("After count= " + count);
        }
    }
    

2.4.4: Exiting Early

  • break statement can be used to exit loops
  • Transfers control to statement following the loop
  • Provides a way to break out of an intentional infinite loop
  • class BreakOut {
        public static void main(String[] args) {
            int count = 0;
            while (true) {
                ++count;
                System.out.println(count);
                if (count >= 5) break;
            }
            System.out.println("After count= " + count);
        }
    }
    

2.4.5: Nested Loops

  • Often necessary to have one loop inside another
  • Following example shows this structure
  • Let's follow the execution sequence before checking the result
class Nested {
   public static void main(String[] args) {
      for (int outer = 1; outer < 4; outer++) {
         for (int inner = 1; inner < 4; inner++) {
            System.out.println(outer + " " + inner);
         }
      }
   }
}

2.4.6: Practical Advice

Loopy Errors

  • Most common errors with loops:
    • Unintended infinite loops
    • Off-by-one errors in counter-controlled loops
  • Everyone writes an unintentional infinite loop
  • To get out of an unintended infinite loop: ^C (control-C) keys
  • Thoroughly test loops -- especially at the boundaries of the loop test
  • Check for off-by-one and other error conditions

Exercise 2.4

Take one minute to prepare an answer the following:

for loops and while loops can be used interchangeably. Convert the following code from a for-loop to a while-loop.

class CountDown {
    public static void main(String[] args) {
        int count = 0;
        for (count = 5; count > 0 ; --count) {
            System.out.println(count);
        }
        System.out.println("After count= " + count);
    }
}

Wrap Up

Home | WebCT | Announcements | Schedule | Expectations | Course info
Help | FAQ's | HowTo's | Links

Last Updated: March 02 2004 @14:02:24