2: Java Programming Essentials

What We Will Cover


Illuminations

Homework Questions?

Questions from last class?

2.1: Data and Arithmetic

Objectives

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

  • Create program variables and assign them values
  • Define the data type of a variable
  • Identify the data type of various literal values
  • Create code to perform arithmetic
  • Convert the data type of a primitive value to another type
  • Distinguish between pre and post operators for both increment and decrement operations
  • Generate code that uses literal strings

2.1.1: Variables and Data Types

  • A variable is a named location to store data
  • The name corresponds to a memory address
  • All Java program variables must be declared before using them
  • Every variable has a data type associated with it
  • A data type tells your computer program how to interpret data
    • Specifies how many bytes are needed to store the data
    • Tells the computer the format in which the data is saved
  • In general, the format of a variable declaration is:
  • typeName variableName1, variableName2, ...;
    
  • For example, the following declares three integer variables:
  • int sum, number1, number2;
    
  • Names must follow the rules for valid identifiers
  • Data types are described in the following section

Primitive Data Types

  • Two main kinds of types in Java: primitive and class
    • We will cover class types later in the course
  • Primitive types are the 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;
      
  • 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;
      
  • 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';
      
  • Boolean type: truth values (i.e. true, false)
    • For example:
    • boolean truth = true;
      boolean lies = false;
      

Java's Primitive Types

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
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
char single character (Unicode) 2 bytes All Unicode characters
boolean true or false 1 byte Not applicable

Programming Style: Variable Naming Conventions

  • Use meaningful names that are easy to remember as you code
  • Start variable names with a lowercase letter
  • Capitalize the first letter in all words after the first word

2.1.1: Assignment Statements

  • When variables are declared, the computer allocates storage space for them
  • Your program must then assign values to the variables

Assigning Values to Variables

  • To change the value of a variable, use the assignment operator ("equals sign"): =
  • variable = expression;
  • Assigns value of expression (right side) to the variable (left side)
  • For example:
  • int count = 10;    // initialize counter to ten
    count = count + 1; // increment counter
    
  • Note that a variable can occur on both sides of an equals sign
  • In the second line, count + 1 replaces the previous value of count

Assigning Initial Values to Variables

  • You can combine variable declaration and assignment into one statement
  • For example:
  • //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;
    

Abbreviated Assignment Expressions

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

2.1.3: Literal Values and Constants

  • As we saw before, you can use literal values in a program
  • A literal value is a sequence of characters that look like the conventional way to write the data
  • Java's literal values are:
    • Integer: zero or any positive or negative number without a decimal point
    • Floating-point: any signed or unsigned number with a decimal point
    • Character: letter, number or special symbol enclosed in single quotes
    • Boolean: either the value true or the value false
    • String: any character enclosed in double quotes
  • Examples of literals:
    • Integer: int x = 123;
    • Floating-point: double x = 1.23;
    • Character: char x = '1';
    • Boolean: boolean x = true;
    • String: String x = "123";
  • Note that literal values are constant -- they cannot change when your program is running

Constant Variables

  • A constant variable (or constant) is a variable that cannot change after being assigned a value
  • Sounds oxymoronic, but is actually quite useful
  • Java uses the keyword final to indicate a variable that cannot change
  • final int MY_CONSTANT = 10;
  • Note that you must assign a value when the constant is declared

Exponential Notation

  • Floating-point literals can be written in exponential notation
    • Similar to scientific notation
  • Used to express both very large and very small values in compact form
  • For example:
  • Decimal Notation Exponential Notation Scientific Notation
    1234. 1.234E3 1.234 x 103
    98765. 9.87654E4 9.8765 x 104
    .0123 1.23E-2 1.23 x 10-2
    .000625 6.25E-4 6.25 x 10-4

  • Letter E stands for exponent
  • Number following E represents a power of 10
  • Indicates the number of decimal places to move for standard decimal value
  • Note that floating-point numbers follow standard IEEE 754-1985
  • Zero can be either 0.0 or -0.0

How Large is 1.7E308?

  • Largest possible double is 17 followed by 307 zeros
  • How large is that?
  • Current estimate of the number of atoms in the universe: about 1.0E78
  • Mathematicians use the term "google" for a very large number: 1.0E100
  • Data type double easily encompasses these numbers
  • What value is so large that it cannot be represented by type double?

2.1.4: Arithmetic Operators and Expressions

Arithmetic Operators

  • Like most languages, Java uses these arithmetic operators:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • For example:
  • 3 + 4
    12 - 7
    12.3 + 4.56
    .065 * 1200
    18 / 2
    17.4 / 2.2
    
  • These are known as binary operators because each operator requires two numbers
  • Java also uses the dash as a minus sign
    • Note that this is a unary operator
    • -1.1
  • You can use the plus sign for positive numbers as well
    • But why bother?

Expressions

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

  • Java allows you to form expressions using variables, constants and arithmetic operators
  • These expressions can be used anywhere it is legal to put the type produced by the expression
  • For example:
  • 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

Parenthesis and Precedence

  • 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
  • Parenthesis can be used to group expressions
    • Anything within parenthesis is evaluated first
    • 2 * (10 + 5)
  • You can have parenthesis within parenthesis
    • Innermost parenthesis evaluated first
    • (2 * (10 + 5))
  • 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

Truncation in Integer Division

  • Integer division truncates the remainder
    • 7 / 5 evaluates to 1
  • You need to use the modulus operator % to know the remainder
    • 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
  • No truncation occurs if at least one of the values is of type float or double
  • Instead, both values are promoted to the highest data type
  • byte => short => int => long => float => double
    
  • For example:
  • int a = 4, b = 5, c;
    double x = 1.5, y;
    y = b / x; // value returned by b is promoted 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
    

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.5: Type 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:
  • (typeName) 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

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

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
    

2.1.6: Increment and Decrement Operators

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

For Example

  • What is output by the following program?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class PrePost {
    public static void main(String[] args) {
        int a, b, c;

        // Prefix order
        a = 10;
        b = ++a;
        System.out.println("a=" + a + ", b=" + b);
        c = b + --a;
        System.out.println("a=" + a + ", c=" + c);
        --a;
        System.out.println("a=" + a + "\n");

        // Postfix order
        a = 10;
        b = a++;
        System.out.println("a=" + a + ", b=" + b);
        c = b + a--;
        System.out.println("a=" + a + ", c=" + c);
        a--;
        System.out.println("a=" + a);
    }
}

2.1.7: Strings

  • Strings are objects in Java
    • Will discuss later how this affects their use
  • However, they have some special syntax 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";
    System.out.println(message);
    
  • Also, you can concatenate two strings using the "+" operator
  • String cool = "Java" + " rules!"
    System.out.println(cool);
    

Using Special Characters

  • First 32 character codes are not visible on our monitors
    • Represent control codes
  • Java can access some of the control codes using escape sequences
  • Backslash (\) directly in front of a select character tells the compiler to escape from the normal interpretation
  • Following table has some nonprinting and hard-to-print characters:
  • Sequence Meaning Unicode Value
      Alert \u0007
    \b Backspace \u0008
    \f Formfeed \u000C
    \n Newline \u000A
    \r Carriage return \u000D
    \t Horizontal tab \u0009
    \\ Backslash \u005C
    \" Double quote \u0022
    \' Single quote \u0027

  • Some examples:
  • System.out.print('\u0007');
    System.out.print('\n');
    System.out.print("Left\tRight");
    System.out.print("one\ntwo\nthree");
    

2.1.8: Summary

  • 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 declare a variable or constant, specify a data type and a name.
  • 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.

  • You assign values to a variable using an assignment statement
  • 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;
  • 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: +, -
  • 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 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: Libraries and Console I/O

Objectives

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

  • Import standard API classes
  • Create objects and call methods
  • Display information to a console
  • Get user input from the console

2.2.1: Importing Classes

  • 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 java.util.Scanner;
    import java.util.*;
    import javax.swing.*;
    

Navigating the API

  • The Java API is located at: http://java.sun.com/j2se/1.5/docs/api/index.html
  • Related classes are organized into packages
    • Shown in the upper left frame
  • When you select a package, all the classes for that package are shown in the lower left frame
  • Once you select a class, it is shown in the right frame
  • Each class shows a variety of information including a summary of all its methods
  • To view the information about a method, either click on its hyperlink or scroll down the page

2.2.2: Creating Objects and Calling Methods

  • To use a Java class, you usually start by creating an object of the class
    • Also known as creating an instance of the class
  • There are two steps to creating an object:
    1. Create a variable to store the object
    2. Create the object using the new operator and assign it to the variable
  • To create the variable, you code the class name followed by an identifier
  • For example:
  • Scanner input;
  • To create the object, you use the new operator followed by the class name to assign a value to the variable
  • input = new Scanner(System.in);
  • When you create the object, you often pass it an argument like System.in as shown
  • The arguments are specified by the constructor as shown in the API documentation
  • You can combine both steps into one statement, like:
  • Scanner input = new Scanner(System.in);
  • When we cover objects in a few weeks, we will discuss this in more detail

Calling Object Methods

  • One you create an object, you can call its methods
  • Note that some classes have static methods that you can call without creating an object
  • To call a method, you use the object name, a dot (period), the method name and a set of parenthesis
  • For example:
  • input.nextInt();
  • When you call a method, the method may require one or more arguments
  • These arguments must be coded in the correct sequence separated by commas
  • System.out.println("Hello, World!");

2.2.3: 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.print("Hello, ");
    System.out.println("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 the parenthesis

2.2.4: Reading Input from the Console

  • You can read input from the command line (console) using a Scanner object
  • Located in the java.util package, so you need to import the class
  • import java.util.Scanner;
    or
    import java.util.*;
  • You then create a scanner class like:
  • Scanner input = new Scanner(System.in);
  • Note that System.in is used to get data from the standard input stream
  • To use one of the methods of a Scanner object, call it like the following:
  • int count = input.nextInt();
    
  • When you call a method of a Scanner object, the program waits for the user to enter data with the keyboard
  • Each group of characters that a user enters is called a token
  • The program waits until the user presses the Enter key
  • The user can enter multiple tokens by separating them with whitespace
  • If the user enters the wrong type, an error occurs and the program aborts
  • When you combine different scanner methods, you sometimes have to include an extra call to nextLine() to get rid of a newline

Some Commonly Used Methods of a Scanner Object

  • Here are some commonly used methods of a Scanner object
  • Method Description
    next() Returns the next token as a String object.
    nextLine() Returns the rest of the current line as a String object.
    nextDouble() Provides classes to handle text, dates, and numbers
    nextInt() Returns the next token as an int value.

For Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;

public class InputApp {
    public static void main(String[] args) {
        String name;
        int age;
        double weight;
        Scanner input  = new Scanner(System.in);

        System.out.print("Enter your name: ");
        name = input.next();
        System.out.print("Enter your age: ");
        age = input.nextInt();
        System.out.print("Enter your weight: ");
        weight = input.nextDouble();

        System.out.println("\nYou entered:");
        System.out.println("Name:" + name);
        System.out.println("Age:" + age);
        System.out.println("Weight:" + weight);
    }
}

Scanner Pitfall: next() vs. nextLine()

  • Notice the difference between methods next() and nextLine()
  • Method next() first skips whitespace and reads until it finds whitespace again
  • Method nextLine() reads the remainder of a line of text, starting wherever the last read left off, but excluding the '\n' at the end of the line
  • Thus, you use nextLine() if you allow spaces in the input
  • System.out.print("Enter your name: ");
    name = input.nextLine();
    

Other Input Methods

  • The Scanner class was introduced in Java version 5.0 (JDK 1.5)
  • For console input without the Scanner class, see: Using System.in

2.2.5: Summary

  • 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.util libraries
  • import java.util.*;
  • Alternatively, you can use the fully qualified package name
  • import java.util.Scanner;
  • To create an object for a class, you:
    1. Create a variable to store the object
    2. Create the object using the new operator and assign it to the variable
  • You can combine both steps into one statement, like:
  • Scanner input = new Scanner(System.in);
  • One you create an object, you can call its methods
  • To call a method, you use the object name, a dot (period), the method name and a set of parenthesis
  • For example:
  • input.nextInt();
  • 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
  • You can use a Scanner object to read data from the console
  • To use Scanner, you need to need to import the java.util.Scanner class
  • You then create a Scanner object like:
    Scanner input = new Scanner(System.in);
  • Each group of characters that a user enters is called a token
  • To read each token, you call a method of a Scanner object
  • int count = input.nextInt();

Exercise 2.2

Take one minute to prepare an answer the following.

Write a program 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:

  • Formulate relational expressions to produce boolean values
  • Assemble complex boolean expressions
  • Generate if and if-else statements
  • Create multiway if-else statements
  • Recognize switch statements and conditional operators

2.3.1: Flow of Control

  • The term flow of control refers to the order in which a computer executes instructions
  • All programs can be written with just three control-flow elements:
  1. Sequence - continue with the next instruction
    • Sequence is the default operation
  2. Selection - a choice between at least two options
    1. Either execute some instruction based on a condition
    2. Or continue with the next instruction
    3. if
      if-else
      switch
      
  3. Repetition - a loop (repeat 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
    • for
      do-while
      while
      
  • We will start with selection statements

2.3.2: Test Conditions and Relational Operators

  • Selection means that there is more than one choice for the next instruction
  • Which instruction is executed 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 truth = true, lies = false;
  • You can compare two numbers using a relational operator to generate a boolean value

The Value of a Relationship

  • All computers can compare numbers and many decisions can be reduced to choosing between two numbers
  • Comparing numbers can make computers seem "intelligent"
  • Expressions that compare operands are called relational expressions
    • Also called conditions
  • Simple relational expressions have one relational operator comparing two values
  • relational expression diagram

  • A relational expression always evaluates to either true or false
  • The relational operators are:
  • Math Name Operator 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

  • You may use relational operators with integer, floating-point and character data

Comparing Characters

  • Character data can be evaluated using relational operators
  • For these comparisons, char values are automatically coerced to int values
  • Letters nearer to the start of the alphabet have lower numerical values
  • Thus a numerical comparison can decide the alphabetical order of characters
  • For example:
  • Expression Result
    'A' > 'C' false
    'D' <= 'Z' true
    'E' == 'F' false
    'G' >= 'M' false
    'B' != 'C' true

Comparing Strings

  • "==" 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

2.3.3: Using the if-else Statement

  • The if-else statement chooses between two alternatives based on a condition
  • The condition must evaluate to either true or false
  • If a condition is true
    • then do this
  • Otherwise it is false
    • so do something else
  • General syntax:
  • if (condition) {
        statements1;
    } else {
        statements2;
    }
    
  • For clarity, if and else are written on different lines than the statements and the statements are indented
  • Note that the else clause can be omitted entirely
  • if (condition) {
       // execute statements only if true
    }
    
  • The statements are executed only if the condition is true

For Example

import java.util.Scanner;

public class GradeApp {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);

        System.out.print("I show pass or fail based"
            + " on a score.\nEnter your score: ");
        int score = input.nextInt();

        if (score >= 60) {
            System.out.println("You passed!");
        } else {
            System.out.println("Sorry, you failed.");
        }
    }
}

About those Curly Braces

  • Technically, the if and else affects only the single statement that follows
  • We can use curly braces to make the following statement into a block
  • This allows us to put any number of statements within the block
  • Though curly braces are not always required, the best practice is to include them

Programming Style: Placement of Braces

  • Different practices for placing curly braces in a compound statement
  • Many programmers prefer placing curly braces on separate lines
  • However, Java standard is to place the opening brace on the same line as shown above
  • In practice, you should use the style dictated by your company's policy
    • Or your professor's instructions
  • For the acceptable styles for this course see: Curly Braces

2.3.4: Nested if Statements

  • You can include if statements within other if statements
  • Each inner if statement is evaluated only if outer condition is met

For Example

import java.util.Scanner;

public class GradeApp2 {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);

        System.out.print("I show a grade based on a"
            + " score.\nEnter your score: ");
        int score = input.nextInt();

        if (score >= 60) {
            if (score >= 70) {
                if (score >= 80) {
                    if (score >= 90) {
                        System.out.println("A");
                    } else {
                        System.out.println("B");
                    }
                } else {
                    System.out.println("C");
                }
            } else {
                System.out.println("D");
            }
        } else {
            System.out.println("Sorry, you got an F");
        }
    }
}
  • Nested conditionals can be confusing if too deep
  • Rule of thumb: no more than three deep

"Dangling Else" Problem

  • Potential problem with nested if statements is the dangling else problem
  • if (condition1)
        if (condition2)
            Statement1;
    else
        Statement2;
    
  • Indentation is misleading and should be:
  • if (condition1)
        if (condition2)
            Statement1;
        else
            Statement2;
    
  • Common mistake is not matching else with the correct if
  • Rule: else always matches the last unmatched if
  • Avoid this problem by using curly braces to specify the grouping
  • if (condition1) {
        if (condition2) {
            Statement1;
        } else {
            Statement2;
        }
    }
    

2.3.5: Testing Multiple Conditions

  • One reason to use nested if statements is for testing multiple conditions
  • However, a better way is to combine conditions using conditional operators
  • Conditional operators allow you to consider multiple cases and to change conditions

AND Operation

  • One such operator is "and", which is spelled && in Java
  • For example, the following is true if score >= 80 and score < 90
  • (score >= 80) && (score < 90)
  • When two boolean expressions are connected using && the whole expression is true only if both conditions are true
  • However, if either condition is false the whole expression is false

OR Operation

  • Also, you can combine two boolean expressions using the "or" operator, spelled || in Java
  • For example, the following is true if score < 0 or score > 100
  • (score < 0) || (score > 100)
  • When two boolean expressions are connected using || the whole expression is true if either condition is true
  • Only if both conditions are false is the entire expression false

NOT Operation

  • Additionally, you can negate any expression using ! operator
  • To use it, place the entire expression in parenthesis and place the ! operator in front
  • For example, to get a age between 0 and 100, we can negate our previous example:
  • !((score < 0) || (score > 100))

For Example

import java.util.Scanner;

public class GradeApp3 {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);

        System.out.print("I show a grade based on a"
            + " score.\nEnter your score: ");
        int score = input.nextInt();

        if (score >= 90 && score < 100) {
            System.out.println("You got an A");
        }
        if (score >= 80 && score < 90) {
            System.out.println("You got a B");
        }
        if (score >= 70 && score < 80) {
            System.out.println("You got a C");
        }
        if (score >= 60 && score < 70) {
            System.out.println("You got a D");
        }
        if (score >= 0 && score < 60) {
            System.out.println("Sorry, you got an F");
        }

        if (score < 0 || score > 100) {
            System.out.println("Invalid score");
        }
    }
}

Truth Table for ! Operator

If expr is... Then ! expr is... Example Result
true false !true false
false true !(5 < 2) true

Truth Table for && 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

Truth Table for || 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

More Information

2.3.6: Using Multiway else-if Statements

  • Often confusing when if statements are nested within other if statements
    • Should avoid this type of construction
  • However, a very useful construction is an if ... else-if statement
    • An if statement is nested inside an else statement
  • Tests conditions are checked sequentially until the first true condition is found
    • Executes the code within the associated block
    • Skips the remainder of the if-else chain
  • You can code a final else clause as a default condition
    • If none of the other conditions are true then execute the default code
  • Often used to create a menu

For Example

import java.util.Scanner;

public class GradeApp4 {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);

        System.out.print("I show a grade based on a"
            + " score.\nEnter your score: ");
        int score = input.nextInt();

        if (score >= 90) {
            System.out.println("You got an A");
        } else if (score >= 80) {
            System.out.println("You got a B");
        } else if (score >= 70) {
            System.out.println("You got a C");
        } else if (score >= 60) {
            System.out.println("You got a D");
        } else {
            System.out.println("Sorry, you got an F");
        }
    }
}
  • Note the formatting of if ... else-if statements
  • The statements are aligned rather than deeply indented

2.3.7: switch Statements

  • The switch statement provides an alternative to an if-else chain
  • Executes a section of code depending on value of a variable
  • General form:
  • switch (integerExpression) {
       case label1:
          statements
          break;
       case label2:
          statements
          break;
       ...
       case labeln:
          statements
          break;
       default:
          statements
          break;
    }
    
  • Keyword switch identifies the start of the switch statement
  • Expression in parenthesis is evaluated for comparison to each case label
    • integerExpression must evaluate to an integer
    • Otherwise a compilation error occurs
  • Within a switch statement, keyword case labels each entry point into the code
    • Code executes if integerExpression matches the case label value
    • Execution starts with the statement immediately following the match
  • Any number of case labels can be placed in any order
  • Any value that does not match starts executing with the statement after default
  • Execution continues until the end of the switch statement or a break statement
  • The break statement causes an immediate exit from the switch statement
  • Just as case identifies possible starting points, break determines end points

For Example:

import java.util.Scanner;

public class GradeApp5 {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);

        System.out.print("I show a grade based on a"
            + " score.\nEnter your score: ");
        int score = input.nextInt();

        switch (score / 10) {
            case 10:
            case 9:
                System.out.println("You got an A");
                break;
            case 8:
                System.out.println("You got a B");
                break;
            case 7:
                System.out.println("You got a C");
                break;
            case 6:
                System.out.println("You got a D");
                break;
            default:
                System.out.println("Sorry, an F");
        }
    }
}
  • Notice that each case other than the last contains a break statement
  • Ensures that the switch statement is exited after a matching case is found

When to Use switch Statements

  • You can only use switch statements with integer expressions
  • Inherently less useful than if-else statements
  • Syntax is no clearer than if-else statements
  • Thus, no real need to ever use a switch statement
  • One acceptable use is for a menu

2.3.8: Conditional (Ternary) Operators

  • Provides a compact if-else structure
  • Syntax:
  • operand1 ? operand2 : operand3;
    
  • First operand must be a conditional expression that evaluates to true or false
  • If operand1 is true, return operand2; otherwise return operand3.

For Example

  • Following is an if-else statement
  • if (n1 > n2) {
        max = n1;
    } else {
        max = n2;
    }
    
  • Equivalent using the conditional operator
  • max = (n1 > n2) ? n1 : n2;
    

When to Use Conditional (Ternary) Operators

  • Older style rarely used in professional programing
  • Almost always better to use if-else statements
  • You can use it for the Java version of the Obfuscated C Code Contest

2.3.9: Summary

  • Selection is a choice between at least two options
  • Selection statements include:
  • if
    if-else
    switch
    
  • Single statements are expanded into compound statements using blocks
  • Test conditions can be created using relational expressions such as:
  • ==  !=  <   <=  >   >=
  • All relational expression evaluate to a boolean value: true or false
  • You can build complex conditions using logical operators
  • !   &&  ||
  • Nested if statements are legal but often confusing
    • Which if does an else match up with?
    • Use curly braces to clarify
    • Better yet, avoid using nested if statements
  • In contrast, multiway if ... else-if statements are very useful
    • if statements are nested in the else clause
    • Programs execute the code when the first condition matches
    • Often used to create menus
  • Java has an older style switch statement that is sometimes used
    • Inherently more limited than if-else statements
  • Also, Java has an older style conditional (ternary) operator that is rarely used

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. Which of the following boolean expressions tests to see if x is between 2 and 15 (including 2 and 15)?
    1. (x <= 15 || x >= 2)
    2. (2 <= x || x <= 15)
    3. (x >= 2 && x <= 15)
    4. (2 <= x <= 15)

2.4: Repetition

Objectives

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

  • Use while and do-while Loops
  • Use for Loops
  • Generate the appropriate repetition structure for a Java program
  • Diagnose common looping problems

2.4.1: About Loops

  • Loops are used to repeat sections of code
  • General loop structure:
    • Initialization code
    • Loop condition -- evaluated during the loop
    • Loop body
  • Java has 3 loop statement
  • for
    while
    do-while
    
  • You can use any loop statement in place of another loop statement
    • With minor changes to your code

2.4.2: Using while and do-while Loops

  • The simplest loop statement is the while loop
  • while loop Syntax:
  • //Initialization
    ...
    while (loopTest) { //loop condition
       //loop body
       ...
    }
    
  • Initialization statements usually precede the 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
  • A variant of the while loop is the do-while loop
  • Syntax:
  • //Initialization
    ...
    do {
       //loop body
       ...
    } while (loopTest); //loop condition
    
  • The important difference between the while and do-while is when the loop test is checked
  • The body of the do-while loop always executes at least one time

For Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class WhileDoWhile {
    public static void main(String[] args) {
        int countDown;

        System.out.println("First while loop:");
        countDown = 3;
        while (countDown > 0) {
            System.out.println("while");
            countDown = countDown - 1;
        }

        System.out.println("Second while loop:");
        countDown = 0;
        while (countDown > 0) {
            System.out.println("while");
            countDown = countDown - 1;
        }

        System.out.println("First do-while loop:");
        countDown = 3;
        do {
            System.out.println("do-while");
            countDown = countDown - 1;
        } while (countDown > 0);

        System.out.println("Second do-while loop:");
        countDown = 0;
        do {
            System.out.println("do-while");
            countDown = countDown - 1;
        } while (countDown > 0);
    }
}

2.4.3: Using for Loops

  • Provides a more compact loop structure
  • Syntax:
  • for (initialization; condition; update) {
       //loop body
       ...
    }
    
  • Initialization, condition, and update are part of the syntax
  • Initialization: set a value before the loop executes
  • Condition: determines when the loop will end
  • Update: evaluated at the end of each loop iteration
  • Statements to repeat are enclosed in curly brackets
  • Execution sequence as follows:
  1. When for statement reached -- initialization executes
  2. Check if condition 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 increment
  5. Return to Step 2
  6. Loop is finished: continue with statements after the loop

for Loop Example

1
2
3
4
5
6
7
8
public class CounterFor {
    public static void main(String[] args) {
        int count;
        for (count = 0; count < 5; count++) {
            System.out.println(count);
        }
    }
}
  • Note that code is indented in the loop body for readability

2.4.4: 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
1
2
3
4
5
6
7
8
9
public 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);
         }
      }
   }
}
  • Tracing nested loops is difficult if there is a lot of code inside the loops
  • Usually clearer to place the inner loop inside a method definition
  • Then call the method from inside the outer loop
  • We will cover methods later in the course

2.4.5: Using break and continue Statements

  • break and continue statements transfer control to another part of a program
  • Within a loop break statements an immediate exit
  • Transfers control to statement following the loop
  • Provides a way to break out of an intentional infinite loop
  • public class BreakOut {
        public static void main(String[] args) {
            int count = 0;
            while (true) {
                count++;
                if (count == 3) continue;
                System.out.println(count);
                if (count >= 5) break;
            }
            System.out.println("After count= " + count);
        }
    }
    
  • continue statement transfers control to the loop condition
  • Causes the loop to skip the rest of the current iteration
  • When encountered in a loop, starts the next iteration of the loop immediately

When to Use break and continue Statements

  • Use break statements in switch statements only
  • Never use break in looping constructs
    • Poor coding habit
    • Should only have one exit point in a loop
  • In this course, you will never a need to write infinite loops
  • Do not need to use continue statements either
  • Can accomplish the same operation other ways

2.4.6: Looping Patterns

  • Let us look at some ways loops are commonly used

Counter-Controlled Loops

  • Use this pattern when you know how many times to repeat a section of code
  • The key is a variable called the counter
    1. Initialize the counter variable to 0
    2. Set the loop condition to check for the maximum count
    3. Adjust the counter variable inside the body of the loop
  • We saw this in our previous example:
public class CounterFor {
    public static void main(String[] args) {
        int count;
        for (count = 0; count < 5; count++) {
            System.out.println(count);
        }
    }
}
  • A variation is to start at the maximum value and count down

Ask Before Repeating

  • Another pattern is to ask the user whether or not to repeat a loop
  • Often used to allow the user to control the flow of a program
  • For example:
import java.util.Scanner;

public class SumAsker {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);

        System.out.println("I sum numbers");
        double total = 0.0; // Loop initialization
        do {
            System.out.print("Enter a number: ");
            double num = input.nextDouble();
            total += num;
            System.out.print("Another number? (y/n): ");
        } while (input.next().charAt(0) == 'y');
        System.out.println("Total: " + total);
    }
}
  • For a long list, this approach can be tiring
  • Often time, a better solution is to use a sentinel-controlled loop

Sentinel-Controlled Loops

  • Use a sentinel when you can use input data to tell the program when to stop
  • Looping continues as long as the data value read is not a sentinel value
  • When a sentinel value is read, the loop exits
  • For example:
import java.util.Scanner;

public class SumInput {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);

        System.out.println("I sum numbers.\n"
            + "Enter 0 to exit");
        double total = 0.0; // Loop initialization
        double num = 0.0;
        do {
            System.out.print("Enter a number: ");
            num = input.nextDouble();
            total += num;
        } while (num != 0);
        System.out.println("Total: " + total);
    }
}
  • num is the sentinel variable
  • The sentinel value is the number: 0
  • The program ends when the user enters the sentinel value

2.4.7: Common Loop Pitfalls

Infinite Loops

  • Common error: unintentional infinite loop
  • For example, what is wrong with the following code?
  • 1
    2
    3
    4
    5
    6
    7
    8
    
    public class InfiniteLoop1 {
        public static void main(String[] args) {
            int count = 0;
            while (count < 10) {
                System.out.println(count); // trace
            }
        }
    }
    

Empty Statements

  • Remember that statements are terminated by a semicolon
  • Is the following a legal statement?
  • ;
  • Known as an empty or null statement
  • Empty statements are a common source of infinite loops
  • For example, what is wrong with the following code?
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    
    public class InfiniteLoop2 {
        public static void main(String[] args) {
            int count = 0;
            while (count < 10); {
                System.out.println(count); // trace
                count++;
            }
        }
    }
    

Off-By-One Errors

  • A common looping problem is the off-by-one error
  • Often a less-than is confused with a less-than-or-equal-to
  • For example, to sum the even numbers between one and 10, what is wrong with:
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    
    public class OffByOne {
        public static void main(String[] args) {
            int sum = 0;
            for (int i = 1; i < 10; i += 2) {
                sum += i;
            }
            System.out.println(sum);
        }
    }
    

Tracing Variables

  • One good way to discover loop errors is to trace key variables
  • Tracing variables means watching them change as the program executes
  • You can insert temporary output statements in your program
  • For instance, we had trace statements in the infinite loop examples above
  • What variables would we trace for the off-by-one error example?

2.4.8: Summary

  • Loops are used to repeat sections of code
  • General loop structure:
    • Initialization code
    • Loop condition -- evaluated during the loop
    • Loop body
  • Several common uses of a loop
    • Counter-controlled loops
    • Ask Before Repeating
    • Sentinel-controlled loops
  • It is legal code to have one loop nested inside another
  • Several problems that can occur when using a loop
    • infinite loops: loops that "never" stop
    • Off-by-one errors: start or stop at a wrong value
  • Thoroughly test loops -- especially at the boundaries of the loop test
  • Tracing variables is a good way to discover loop errors

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.

public class CounterFor {
    public static void main(String[] args) {
        int count;
        for (count = 0; count < 5; count++) {
            System.out.println(count);
        }
    }
}

Wrap Up

Home | WebCT | Announcements | Schedule | Room Policies | Course Info
Help | FAQ's | HowTo's | Links

Last Updated: May 23 2005 @17:09:17