# Java - PowerPoint

Document Sample

					              Chapter 1

Introduction to Computers and Java
Objects
 Background information
» important regardless of programming language

 Introduction to Java
Computer Basics
• Computer system: hardware + software
• Hardware: the physical components
• Software: the instructions that tell the
hardware what to do
Common Hardware Components
Standard Hardware                                           • Processor (CPU)
– Central Processing Unit
Organization                                                  – Interprets and executes the
instructions
• Memory
– main & auxiliary
Memory                                        – holds data and instructions
(main & auxiliary)
• Input device(s)
– mouse, keyboard, etc.
Input
Processor
Output               • Output device(s)
Devices                 (CPU)            Devices                  – video display, printer, etc.
(such as mouse and                          (such as video
keyboard)                             display or printer)   • CPU and memory are
physically housed together
Physical Organization
• Keyboard
• Monitor
• Chassis
–   CPU
–   memory
–   disk drives
–   I/O connectors
–   etc.
Two Kinds of Memory
• Main
– working area
– temporarily stores program and data (while program is
executing)
• Auxiliary
– permanent (more or less)
– saves program and results
– includes floppy & hard disk drives, CDs, tape, etc.
Main Memory Organization

• Bit = one binary digit
– Binary digit can have only     3021    1111 0000   Item 1: 2 bytes
one of two values, 0 or 1                         stored
3022    1100 1100
• Byte = 8 bits
3023    1010 1010   Item 2: 1 byte
– Main memory is a list of       3024    1100 1110   Item 3: 3 bytes
stored
numbered locations that       3025    0011 0001
contain one byte of data in
3026    1110 0001
each location
3027    0110 0011   Item 4: 2 bytes
• Number of bytes per data item                         stored
may vary                          3028    1010 0010

3029    …           Next Item, etc.
Auxiliary Memory Organization
systems Organization
[fileAuxiliary Memoryfor users]
Main (Root) Directory / Folder

Files       Subdirectory    Subdirectory

Files       Subdirectory             Subdirectory

Subdirectory        Files            Files

Files       Subdirectory

Files
Running a Program
Program—a set of instructions for a computer to follow

Program

Data
Computer          Output
(input for the program)
Many Types of Programs
• User-created applications
• Existing applications
–   word-processor/editor
–   web browser
–   compiler or assembler
–   etc.
• Operating System
– DOS, Microsoft Windows, MacOS, Linux, UNIX, etc.
Various Types of User Interfaces

• Command-line
– type in key words and letters
– DOS and UNIX
– parts of DOS and Windows
• GUI (Graphical User Interface)
– click on icon
– also called “event-driven”
– MacOS, Windows
Programming Language Hierarchy

High-Level Language (HLL)

Assembly Lanuage

Machine Language

Hardware
The highs and lows
of programming languages ...
High-Level Language (HLL)          Machine Language
– closest to natural language   (lowest level)
– words, numbers, and math          – least natural language for
symbols                             humans, most natural
language for hardware
– not directly understood by        – just 0s and 1s
hardware
– directly understood by
– “portable” source code              hardware
(hardware independent)            – not portable (hardware
– Java, C, C++, COBOL,                dependent)
etc.
Assembly Language
(middle level)
• a more or less human readable version of machine language
• words, abbreviations, letters and numbers replace 0s and 1s
• easily translated from human readable to machine executable
code
• like machine code, not portable (hardware dependent)
Getting from Source to Machine Code
• “Compiling a program”
translating from a high-level language source code to machine (object, or
executable) code.
• “Compiler”
a program that translates HLL source code to machine (object, or
executable) code.
• “Assembly”
translating from assemble language source code to machine (object, or
executable) code.
• “Assembler”
a program that translates assembly source code to machine (object, or
executable) code.
• Compilers need to know the specific target hardware
Compilers vs. Assemblers vs. Interpreters

• Compilers and Assemblers
– translation is a separate user step
– translation is “off-line,” i.e. not at run time
• Interpreters - another way to translate source to object code
– interpretation (from source to object code) is not a separate user step
– translation is “on-line,” i.e. at run time

Compiler,
Source                                      Object
Code              Assembler, or            Code
Interpreter
Java Program Translation
Java Program           Data for Java Program
• Both Compilation and
Interpretation              Java Compiler         Java
• Intermediate Code:                               Virtual
Byte-Code
“Byte Code”                    Program
Machine

– similar to assembly
Byte-Code Interpreter
code, but hardware
independent            Machine-Language
Instructions
• Interpreter translates
from generic byte code                Computer Execution
to hardware-specific            of Machine-Language Instructions

machine code
Output of Java Program
Java Byte Code
• generated by Java compiler
– Instead of generating machine language as most compilers
do, the Java compiler generates byte code.
• translated to machine language of various kinds of
computers
• executed by Java interpreter
• invisible to programmer
– You don't have to know anything about how byte code
works to write a Java program.
Why Use Byte Code?
• requires both compiler and interpreter
• slower program execution
• portability
– very important
– same program can run on computers of different types
(useful with the Internet)
– Java compiler for new types of computers can be made
quickly
Java Program            Previously Compiled Helper Programs       Data for Java Program

Java Compiler
Java
Byte-Code                                        Virtual
Program                                         Machine

Byte-Code Interpreter

Machine-Language
Instructions

Computer Execution
of Machine-Language Instructions

Output of Java Program
Object-Oriented Programming: OOP

• A design and programming technique
• Some terminology:
– object - usually a person, place or thing (a noun)
– method - an action performed by an object (a verb)
– type or class - a category of similar objects (such as
automobiles)
• Objects have both data and methods
• Objects of the same class have the same data elements and
methods
• Objects send and receive messages to invoke actions
Example of an Object Class

Class: Automobile
Data Items:                  Methods:
–   manufacturer’s name      – Define data items (specify
–   model name                 manufacturer’s name,
–   year made                  model, year, etc.)
–   color                    – Change a data item (color,
engine, etc.)
–   number of doors
– Display data items
–   size of engine
– Calculate cost
–   etc.
– etc.
Why OOP?

• Save development time (and cost) by reusing code
– once a class is created, it can be used in other
applications

• Easier debugging
– classes can be tested independently
– reused objects have already been tested
Design Principles of OOP

Three main design principles of Object-Oriented
Programming (OOP):
• Encapsulation
• Polymorphism
• Inheritance
Encapsulation
• Design software
– can be easily used
– without knowing the details of how it works.
• Also known as information hiding

An analogy:
• When you drive a car, you don’t have know
– the details of how many cylinders the engine has or
– how the gasoline and air are mixed and ignited.
• only have to know how to use the controls.
Reusable Components
• saves time and money
• components that have been used before
– often better tested and more reliable than new software

• encapsulation
• general classes have a better chance of being reused
Polymorphism
• Polymorphism—the same word or phrase can be mean
different things in different contexts
• Analogy: in English, bank can mean:
– side of a river or
– a place to put money
• In Java, two or more classes could each have a method called
output
• Each output method would do the “right thing” for the class
that it was in. E.g.
– display a number (Integer class)
– display an image (Photo class)
Inheritance
• Inheritance—a way of organizing classes

• Term comes from inheritance of traits like eye color, hair color,
and so on.

• Classes with attributes in common can be grouped so that
their common attributes are only defined once.
An Inheritance Hierarchy
Vehicle

Automobile                  Motorcycle                       Bus

Sedan              Sports Car                  School Bus                Luxury Bus

What properties does each vehicle inherit from the types of vehicles above it in the
diagram?
Algorithms
• Algorithm - a set of instructions (steps) for solving a
problem.
– must be precise
– must be complete

• May be in a number of different formats
– natural language (such as English)
– a specific programming language
– a diagram, such as a flow chart
– pseudocode - a mix of natural and programming
languages
Example of an Algorithm
Algorithm that determines the total cost of a list of items:

1. Write the number 0 on the blackboard.

2. Do the following for each item on the list:
--Add the cost of the item to the number on the blackboard.
--Replace the old number on the board by this sum.

3. Announce that the answer is the number written on the board
Program Design Process
•    Design, then code (not code, then design)
•    Design process
1.   define the problem clearly
2.   design objects your program needs
3.   develop algorithms for the methods of objects
4.   describe the algorithms, usually in pseudocode

•    Writing/Coding
1. write the code
2. test the code
3. fix any errors and retest
Testing and Debugging

• Even with careful programming, your code
could still contain errors and must be
thoroughly tested.

• Bug—a mistake in a program

• Debugging—fixing mistakes in a program
Types of Errors
• Syntax

• Run-Time

• Logic
Syntax
• Syntax: the set of grammar rules for a
programming language.

• The compiler checks your program to make
sure it follows the grammar/syntax

• Violating the syntax => error
Syntax Errors
• caught by compiler (“compiler-time error”)
• automatically found, usually the easiest to fix
• cannot run program until all syntax errors are
fixed
• error message may be misleading

Example:
Misspelling a command, for example “rtrn”
Run-Time Errors
•   An execution error (during run-time)
•   The program cannot continue to run
•   Not always so easy to fix
•   Error message may or may not be helpful
•   Not detected by the compiler.

Example:
Division by zero - if your program attempts to divide by zero it
automatically terminates and prints an error message.
Logic Errors

Just because it compiles and runs without getting an error
message does not mean the program is correct!

• An error in the design (the algorithm) or its implementation
– Program compiles without errors
– no run-time error messages
– but incorrect action or data occurs during execution
• Generally the most difficult to find and fix
• Need to be alert and test thoroughly
– think about test cases and predict results before executing the
code
Logic Error Examples
• Algorithm Error:

• Implementation Error:
– typed in wrong symbol in source code -
sum = a - b;
(should be sum = a + b;)
Finally! Now, a taste of Java!
History
• 1991 - James Gosling, Sun Microsystems, Inc.
• originally a language for programming home appliances
• later (1994) used for World Wide Web applications
• eventually used as a general-purpose programming
language (it is object-oriented)
• Why the name “Java”? Not sure - it may just be a name
that came during a coffee break and it had not been
Applets vs. Java Applications
• Applets
and run immediately
– “little applications”
– run in a web browser
• Applications
– Java programs intended to be installed then run
– often larger applications
• Slightly different programming for each
import java.util.*;
public class FirstProgram
A Sample Java Program
{
public static void main(String[] args)
{
System.out.println("Hello out there.");
System.out.println(“I will add two numbers for you");
System.out.println(“Enter two whole numbers on a line:");

int n1, n2;

Scanner keyboard = new Scanner(System.in);
n1 = keyboard.nextInt();
n2 = keyboard.nextInt();

System.out.println(“The sum of those two numbers is:”);
System.out.println(n1+ n2);
}
Explanation of Code ...
• Code to begin the program (to be explained later):
public class FirstProgram
{
public static void main(String[ ] args)
{

• Java applications all have similar code at the beginning
– The name of the class differs from one program to another.
Explanation of Code ...
• display text strings to the screen:
System.out.println("Hello out there.");
System.out.println(“I will add two numbers for you.");
System.out.println(“Enter two whole numbers on a line.");

–   Note the “dot” operator
–   System.out is an object
–   println is a method that it carries out
–   double-quoted text inside the parentheses is an argument to the method
–   general syntax: Object_Name.Method_Name(Arguments)
… Explanation of Code ...

• Code to create two variables named n1, n2 to contain
two whole numbers (integer):
int n1, n2;

• They store the user’s response.
… Explanation of Code ...
• Creating an object called keyboard of the Scanner
class:

Scanner keyboard = new Scanner(System.in);

• System.in is the keyboard, but the Scanner
class has easier methods to use.
… Explanation of Code ...
• Read two integers typed in from the keyboard and store
them in the variables n1 and n2:

n1 = keyboard.nextInt();
n2 = keyboard.nextInt();
… Explanation of Code
• Printing the sum to the console:

System.out.println(“The sum of those two numbers is:");
System.out.println(n1 + n2);
Compiling and Running
a Java Program
• Compile
– javac <file>.java
– java <file>
– <file> must have a main method
• BlueJ has two similar steps by mouse clicking
(discussed in the labs).
Summary
Part 1

• A computer’s main memory holds both the program that
is currently running and its data.
• Main memory is a series of numbered locations, each one
containing a single byte.
• Auxiliary memory is for more or less permanent storage.
• A compiler is a program that translates a high-level
language, like java, into a lower level format (“byte-code”
for java).
• Actual translation of Java byte-code to the hardware’s
specific machine code occurs at run time (it is
interpreted).
Summary
Part 2

• An algorithm is a set of instructions for solving a problem (it
must be complete and precise).
• An object is something that has both data and actions
(methods) associated with it.
• A class defines a type of object; all objects of the same class
have the same methods.
• Three OOP design principles are encapsulation,
polymorphism, and inheritance.
• In a java program, a method invocation has the general form
Object_Name.Method_Name(Arguments)
Primitive Types, Strings, and
Console I/O
Chapter 2
Objectives
• become familiar with Java primitive types
(numbers, characters, etc.)
• learn about assignment statements and
expressions
• become familiar with classes, methods, and
objects
• learn about simple keyboard input and screen
output
Outline
•   Primitive Types and Expressions
•   The Class String
•   Keyboard and Screen I/O
•   Documentation and Style
Variables and Values
• Variables store data such as numbers and
letters.
– Think of them as places to store data.
– They are implemented as memory locations.
• The data stored by a variable is called its value.
– The value is stored in the memory location.
• Its value can be changed.
Variables and Values
• variables
totalEggs

• assigning values
Naming and Declaring Variables

• Choose names that are helpful such as count
or speed, but not c or s.
• When you declare a variable, you provide its
name and type.
• A variable‘s type determines what kinds of
values it can hold (int, double, char, etc.).
• A variable must be declared before it is used.
Syntax and Examples
• syntax
type variable_1, variable_2, …;

• examples
int styleChoice, numberOfChecks;
double balance, interestRate;
char jointOrIndividual;
Types in Java
• A class type
– a class of objects and has both data and methods.
– “Think Whirled Peas” is a value of class type String
• A primitive type
– simple, nondecomposable values such as an
individual number or individual character.
– int, double, and char are primitive types.
Naming Conventions
• Class types
– begin with an uppercase letter (e.g. String).
• Primitive types
– begin with a lowercase letter (e.g. int).
• Variables of both class and primitive types
– begin with a lowercase letters (e.g. myName,
myBalance).
– Multiword names are ―punctuated‖ using uppercase
letters.
Where to Declare Variables
• Declare a variable
– just before it is used or
– at the beginning of the section of your program that is
enclosed in {}.
public static void main(String[] args)
{ /* declare variables here */

…

}
Java Identifiers
• An identifier
– a name, such as the name of a variable.
• Identifiers may contain only
– letters
– digits (0 through 9)
– the underscore character (_)
– and the dollar sign symbol ($) which has a special meaning – but the first character cannot be a digit. Java Identifiers, cont. • identifiers may not contain any spaces, dots (.), asterisks (*), or other characters: 7-11 netscape.com util.* (not allowed) • Identifiers can be arbitrarily long. • Since Java is case sensitive, stuff, Stuff, and STUFF are different identifiers. Keywords or Reserved Words • Words such as if are called keywords or reserved words and have special, predefined meanings. • Keywords cannot be used as identifiers. • See Appendix 1 for a complete list of Java keywords. • other keywords: int, public, class • Appendix 1 Primitive Types • four integer types (byte, short, int, and long) – int is most common • two floating-point types (float and double) – double is more common • one character type (char) • one boolean type (boolean) Primitive Types, cont. Examples of Primitive Values • integer types 0 -1 365 12000 • floating-point types 0.99 -22.8 3.14159 5.0 • character type a A #   • boolean type true false Assignment Statements • An assignment statement is used to assign a value to a variable. answer = 42; • The ―equal sign‖ is called the assignment operator. • We say, ―The variable named answer is assigned a value of 42,‖ or more simply, ―answer is assigned 42.‖ Assignment Statements, cont. • Syntax variable = expression ; where expression can be – another variable, – a literal or constant (such as a number), – or something more complicated which combines variables and literals using operators (such as + and -) Assignment Examples amount = 3.99; firstInitial = „W‟; score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2; (last line looks weird in mathematics, why?) Assignment Evaluation • The expression on the right-hand side of the assignment operator (=) is evaluated first. • The result is used to set the value of the variable on the left-hand side of the assignment operator. score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2; Specialized Assignment Operators • Assignment operators can be combined with arithmetic operators (including -, *, /, and %, discussed later). amount = amount + 5; can be written as amount += 5; yielding the same results. Simple Screen Output System.out.println(“The count is “ + count); • outputs the Sting literal ―The count is ― followed by the current value of the variable count. • + means concatenation if one argument is a string (an example of which of the three properties of OO languages?) Simple Input • Sometimes the data needed for a computation are obtained from the user at run time. • Keyboard input requires import java.util.* at the beginning of the file. Simple Input, cont. • Data can be entered from the keyboard using Scanner keyboard = new Scanner(System.in); followed, for example, by eggsPerBasket = keyboard.nextInt(); which reads one int value from the keyboard and assigns it to eggsPerBasket. Simple Input, cont. • class EggBasket2 Number Constants • Literal expressions such as 2, 3.7, or ‟y‟ are called constants. • Integer constants can be preceded by a + or - sign, but cannot contain commas. • Floating-point constants can be written – with digits after a decimal point or – using e notation. e Notation • e notation is also called scientific notation or floating-point notation. • examples – 865000000.0 can be written as 8.65e8 – 0.000483 can be written as 4.83e-4 • The number in front of the e does not need to contain a decimal point, eg. 4e-4 Assignment Compatibilities • Java is said to be strongly typed. – You can‘t, for example, assign a floating point value to a variable declared to store an integer. • Sometimes conversions between numbers are possible. doubleVariable = 7; doubleVariable = intVariable ; is possible even if doubleVariable is of type double, for example. Assignment Compatibilities, cont. • A value of one type can be assigned to a variable of any type further to the right byte --> short --> int --> long --> float --> double but not to a variable of any type further to the left. • You can assign a value of type char to a variable of type int. Type Casting • A type cast creates a value in a new type from the original type. • For example, double distance; distance = 9.0; int points; points = (int)distance; (illegal without (int)) Type Casting, cont. • The value of (int)distance is 9, but the value of distance, both before and after the cast, is 9.0. • The type of distance does NOT change and remains float. • Any nonzero value to the right of the decimal point is truncated, rather than rounded. Characters as Integers • Characters are actually stored as integers according to a special code – each printable character (letter, number, punctuation mark, space, and tab) is assigned a different integer code – the codes are different for upper and lower case – for example 97 may be the integer value for ‗a‘ and 65 for ‗A‘ • ASCII and Unicode are common character codes Unicode Character Set • Most programming languages use the ASCII character set. • Java uses the Unicode character set which includes the ASCII character set (Appendix 3) • The Unicode character set includes characters from many different alphabets other than English (but you probably won‘t use them). ASCII/Unicode 32 33 34 35 36 37 38 39 40 41 ! “ #$       %        &        ‘         (     )

48    …       57       …       65       …       90        …        97       … 122
0             9                A                Z                  a              z
Casting a char to an int
• Casting a char value to int produces the
ASCII/Unicode value
• For example, what would the following display?
• >y
>121
>
Initializing Variables
• A variable that has been declared, but no yet
given a value is said to be uninitialized.
• Uninitialized class variables have the value null.
• Uninitialized primitive variables may have a
default value.
• It‘s good practice not to rely on a default value,
which could be arbitrary.
Initializing Variables, cont.
• To protect against an uninitialized variable (and
to keep the compiler happy), assign a value at
the time the variable is declared.
• Examples:
int count = 0;
char grade = ‟A‟;   // default is an A
Initializing Variables, cont.
• syntax
type variable_1 = expression_1, variable_2 =
expression_2, …;
Binary Representation
• Assume an 8-bit type
• 5 as an integer
– 00000101
• ‗5‘ as a character
– 00110101 (53 decimal, ASCII)
• 5.0 as a floating point number
– How?
Binary Real Numbers
…         23   22   21   20       2-1   …
.
• 5.5
– 101.1
• 5.25
– 101.01
• 5.125
– 101.001
• 5.75
– 101.11
8 bits only
25      24       23      22      21      20      2-1   2-2

• 5.5
– 101.1 -> 000101 10
• 5.25
– 101.01 -> 000101 01
• 5.125
– 101.001 -> ??
• With only 2 places after the point, the precision is .25
• What if the point is allowed to move around?
Floating-point Numbers
• Decimal
– 54.3
– 5.43 x 101     [scientific notation]

• Binary
– 101.001
– 10.1001 x 21    [more correctly: 10.1001 x 101]
– 1.01001 x 22    [more correctly: 1.01001 x 1010]

– What can we say about the most significant bit?
Floating-point Numbers
• General form: sign 1.mantissa x 2exponent
– the most significant digit is right before the dot
• Always 1 [no need to represent it]
– (more details are not discussed here: mantissa has
no sign, but sign is embedded in exponent…)
• 1.01001 x 22
– Sign: positive (0)
– Mantissa: 01001
– Exponent: 10 (decimal 2)
• [IEEE standard: ―biased exponent‖
– exponent + 2numBits-1 - 1
– Example: 2 + 22-1 – 1 = 3 => 11 in binary]
Java Floating-point Numbers

sign     exponent            mantissa

• Sign:
– 1 bit [0 is positive]
• Mantissa:
– 23 bits in float
– 52 bits in double
• Exponent:
– 8 bits in float
– 11 bits in double
Imprecision in Floating-Point
Numbers
• Floating-point numbers often are only
approximations since they are stored
with a finite number of bits.
• Hence 1.0/3.0 is slightly less than 1/3.
• 1.0/3.0 + 1.0/3.0 + 1.0/3.0 could be
less than 1.
Arithmetic Operations
• Arithmetic expressions can be formed using the
+, -, *, and / operators
– together with variables or numbers referred to as
operands.
– When both operands are of the same type
• the result is of that type.
– When one of the operands is a floating-point type and
the other is an integer
• the result is a floating point type.
Arithmetic Operations, cont.
• Example
If hoursWorked is an int to which the value 40 has
been assigned, and payRate is a double to which
8.25 has been assigned

hoursWorked * payRate

is a double with a value of 500.0.
Arithmetic Operations, cont.
• Expressions with two or more operators can be
viewed as a series of steps, each involving only
two operands.
– The result of one step produces one of the operands
to be used in the next step.
• example
balance + (balance * rate)
Operators with integer and floating
point numbers
• if at least one of the operands is a floating-point
type and the rest are integers
– the result will be a floating point type.
• The result is the rightmost type from the
following list that occurs in the expression.
byte --> short --> int --> long
--> float --> double
The Division Operator
• The division operator (/) behaves as expected
– if one of the operands is a floating-point type.
• When both operands are integer types
– the result is truncated, not rounded.
– Hence, 99/100 has a value of 0.
– called integer division or integer divide
The mod Operator
• The mod (%) operator is used with operators of
integer type to obtain
– the remainder after integer division.
• 14 divided by 4 is 3 with a remainder of 2.
– Hence, 14 % 4 is equal to 2.
• The mod operator has many uses, including
– determining if an integer is odd or even
– determining if one integer is evenly divisible by
another integer.
Case Study:Vending Machine
Change
• requirements
– The user enters an amount between 1 cent and 99
cents.
– The program determines a combination of coins
equal to that amount.
– For example, 55 cents can be two quarters and
one nickel.
Case Study, cont.
• sample dialog
Enter a whole number from 1 to 99.
The machine will determine a combination of coins.
87
87 cents in coins:
3 quarters
1 dime
0 nickels
2 pennies
Case Study, cont.
• variables needed
int amount, quarters, dimes, nickels, pennies;
Case Study, cont.
•    algorithm - first version
2.   Find the maximum number of quarters in the amount.
3.   Subtract the value of the quarters from the amount.
4.   Repeat the last two steps for dimes, nickels, and pennies.
5.   Print the original amount and the quantities of each coin.
Case Study,cont.
• The algorithm doesn‘t work properly, because
the original amount is changed by the
intermediate steps.
– The original value of amount is lost.
• Change the list of variables
int amount, originalAmount, quarters, dimes,
nickles, pennies;

• and update the algorithm.
Case Study, cont.
2. Make a copy of the amount.
3. Find the maximum number of quarters in the
amount.
4. Subtract the value of the quarters from the amount.
5. Repeat the last two steps for dimes, nickels, and
pennies.
6. Print the original amount and the quantities of each
coin.
Case Study, cont.
• Write Java code that implements the algorithm
written in pseudocode.
Case Study, cont.
• How do we determine the number of quarters (or
dimes, nickels, or pennies) in an amount?
– There are 2 quarters in 55 cents, but there are also 2
quarters in 65 cents.
– That‘s because
55 / 2 = 2 and 65 / 25 = 2.
Case Study, cont.
• How do we determine the remaining amount?
– using the mod operator
55 % 25 = 5 and 65 % 25 = 15
– similarly for dimes and nickels.
– Pennies are simply amount % 5.
Case Study, cont.
• class ChangeMaker
Case Study—testing the
implementation
• The program should be tested with several
different amounts.
• Test with values that give zero values for each
possible coin denomination.
• Test with amounts close to
– extreme values such as 0, 1, 98 and 99
– coin denominations such as 24, 25, and 26
• Boundary values.
Increment (and Decrement)
Operators
• used to increase (or decrease) the value of a
variable by 1
• easy to use, important to recognize
• the increment operator
count++ or ++count

• the decrement operator
count-- or --count
Increment (and Decrement)
Operators
• ―mostly‖ equivalent operations
count++;
++count;
count = count + 1;

count--;
--count;
count = count - 1;
Increment (and Decrement)
Operators in Expressions
• after executing
int m = 4;
int result = 3 * (++m)

result hasa value of 15 and m has a value of 5
• after executing
int m = 4;
int result = 3 * (m++)

result has   a value of 12 and m has a value of 5
Increment and Decrement Operator
Examples
common code
int n = 3;
int m = 4;
int result;
What will be the value of m and result after each of these
executes?
(a) result = n * ++m; //preincrement m
(b) result = n * m++; //postincrement m
(c) result = n * --m; //predecrement m
(d) result = n * m--; //postdecrement m
Operator Questions
(a) 1) m = m + 1;        //m = 4 + 1 = 5
2) result = n * m;   //result = 3 * 5 = 15

(b) 1) result = n * m;   //result = 3 * 4 = 12
2) m = m + 1;        //m = 4 + 1 = 5

(c) 1) m = m - 1;        //m = 4 - 1 = 3
2) result = n * m;   //result = 3 * 3 = 9

(b) 1) result = n * m;   //result = 3 * 4 = 12
2) m = m - 1;        //m = 4 - 1 = 3
Summary of Operators
• +, -, *, /
• %
• ++, --
Parentheses and Precedence
• Parentheses can communicate the order in
which arithmetic operations are performed
• examples:
(cost + tax) * discount
cost + (tax * discount)

• Without parentheses, an expression is evaluated
according to the rules of precedence.
Precedence Rules
Precedence Rules—Binary Operators

• The binary arithmetic operators *, /, and %
– have lower precedence than the unary operators +, -,
++, --, and !
– but have higher precedence than the binary arithmetic
operators + and -. (Appendix 2)
• When binary operators have equal precedence
– the operator on the left has higher precedence than
the operator(s) on the right.
Precedence Rules—Unary Operators

• When unary operators have equal precedence
– the operator on the right has higher precedence than
the operation(s) on the left
• opposite order to binary operators
– if x is 10
• -++x is -11 and x is 11 afterwards
• same as –(++x)
– if x is 10
• -x++ is -10 and x is 11 afterwards
• same as –(x++)
Use Parentheses
• Even when parentheses are not needed,
they can be used to make the code
clearer.
balance + (interestRate * balance)
• [Spaces also make code clearer
balance + interestRate*balance
but spaces do not dictate precedence.]
Sample Expressions
The Class String
• We‘ve used constants of type String already.
“Enter a whole number from 1 to 99.”

• A value of type String is a sequence of
characters treated as a single item.
Declaring and Printing Strings
• declaring
String greeting;
greeting = “Hello!”;
or
String greeting = “Hello!”;
or
String greeting = new String(“Hello!”);

• printing
System.out.println(greeting);
Concatenation of Strings
• Two strings are concatenated using the +
operator.
String greeting = “Hello”;
String sentence;
sentence = greeting + “ officer”;
System.out.println(sentence);

• Any number of strings can be concatenated
using the + operator.
Concatenating Strings and
Integers
String solution;

solution = “The temperature is “ + 72;
System.out.println (solution);

The temperature is 72
Classes
• A class is a type used to produce objects.
• An object is an entity that stores data and can
take actions defined by methods.
• An object of the String class stores data
consisting of a sequence of characters.
• The length() method returns the number of
characters in a particular String object.
int howMany = solution.length()
Objects, Methods, and Data
• Objects within a class
– have the same methods
– have the same kind(s) of data but the data can have
different values.
• Primitive types have values, but no methods.
String Methods
The Method length()
• The method length() returns an int.
• You can use a call to method length() anywhere
an int can be used.
int count = solution.length();
System.out.println(solution.length());
spaces = solution.length() + 3;
Positions in a String
– The „J‟ in “Java is fun.” is in position 0
Positions in a String, cont.
• A position is referred to an an index.
– The „f‟ in “Java is fun.” is at index 9.
Indexing Characters within a String
• charAt(position)method
– returns the char at the specified position
• substring(start, end) method
– returns the string from start upto excluding end
• For example:
String greeting = "Hi, there!";
greeting.charAt(0)      returns H
greeting.charAt(2)      returns ,
greeting.substring(4,7) returns the

H      i     ,            t     h     e         r   e   !
0      1     2     3      4     5     6         7   8   9
Using the String Class
• class StringDemo
Escape Characters
• How would you print
“Java” refers to a language.?

• The compiler needs to be told that the quotation
marks (“) do not signal the start or end of a
string, but instead are to be printed.
System.out.println(
“\”Java\” refers to a language.”);
Escape Characters

• Each escape sequence is a single character
even though it is written with two symbols.
Examples
System.out.println(“abc\\def”);
abc\def
System.out.println(“new\nline”);
new
line
char singleQuote = „\‟‟;
System.out.println(singleQuote);
‘
The Unicode Character Set
• Most programming languages use the ASCII
character set.
• Java uses the Unicode character set which
includes the ASCII character set
– Backward compatible to ASCII
• The Unicode character set includes characters
from many different alphabets (but you probably
won‘t use them).
Keyboard and Screen
I/O: Outline
• Screen Output
• Keyboard Input
Screen Output
• We‘ve seen several examples of screen output
• System.out is an object that is part of Java.

• println() is one of the methods available to the
System.out object.
Screen Output, cont.
• The concatenation operator (+) is useful when
everything does not fit on one line.
System.out.println(“When everything “ +
“does not fit on one line, use the” +
“ concatenation operator (\‟+\‟)”);
– Do not break the line except immediately before or
after the concatenation operator (+).
Screen Output, cont.
• Alternatively, use print()
System.out.print(“When everything “);
System.out.print(“does not fit on “);
System.out.print(“one line, use the “);
System.out.print(“\”print\” ”);
System.out.println(“statement”);

ending with a println().
Screen Output, cont.
• syntax
System.out.println(output_1 + output_2 + ...+ output_n);
• example
System.out.println (1967 + “ “ + “Oldsmobile” + “
“ + 442);
1967 Oldsmobile 442
printf (or format) Method for Output
Formatting
• Heavily influenced by C
• outputStream.printf(formatString, args…)
– System.out.printf(…)
– smileyOutStream.printf(…)
• formatString specifies how to format args
• System.out.printf(“%s %d %f%n”, name, id, gpa);
– System.out.println(name + “ “ + id + “ “ +
gpa);
• Useful for “right justified” numbers
• Numbers in println and print are “left justified”
Formatting String
• % width conversion
• width specifies how many slots are available for output
• If width > number of characters, spaces are printed first
before the characters—“right justified”
• printf(“%5d”, count)
– Count
• 32901: 3 2 9 0 1
• 2004:          2 0 0 4

• 22:                2 2

• 6747280: all digits are printed, width is ignored
Conversion Characters
Conversion   Argument                     Description
d            integer                      Decimal integer
f            floating point               Decimal float
s            general (String, Boolean, …) String
n                                         New line
c            character                    Character (unicode)
e            floating point               Decimal scientific notation
o            integer                      Octal integer
%                                         %    (%% to output %)
Floating-point Precision
• width.precision conversion
• printf(“%5.2f”, PI)

3        .       1       4
• printf(“%7.4f”, PI)

3       .        1       4       1   5
Left Justified
• Minus (-) sign before the width
• …printf(“%-7s %-4d”, name, age)

J o h n                     2 0

• Why are there 4 spaces after ―John‖ instead of 3?
Example
• http://www.cs.fit.edu/~pkc/classes/cse1001/P
rintf.java
Keyboard Input
• Starting from Java 5.0
– Java has reasonable facilities for handling keyboard
input.
• Scanner   class in the java.util package
– A package is a library of classes.
Using the Scanner Class
• Near the beginning of your program, insert
import java.util.*

• Create an object of the Scanner class
Scanner keyboard =
new Scanner(System.in)

• Read data (an int or a double, for example)
int n1 = keyboard.nextInt();
double d1 = keyboard.nextDouble();
Some Scanner Class
•   syntax    Methods
Int_Variable =    Object_Name.nextInt();
Double_Variable = Object_Name.nextDouble();
Float_Variable = Object_Name.nextFloat();

String_Variable = Object_Name.next();
String_Variable = Object_Name.nextLine();

Boolean_Variable = Object_Name.nextBoolean();

nextByte(), nextShort(), nextLong()
Some Scanner Class Methods,
cont.
• examples
int count = keyboard.nextInt();
double distance = keyboard.nextDouble();
String word = keyboard.next();
String wholeLine = keyboard.nextLine();

• Remember to prompt the user for input, e.g.
System.out.print(“Enter an integer: “);
Keyboard Input Demonstration
• class ScannerDemo
nextLine()Method Caution
• The nextLine() method reads the remainder of
the current line, even if it is empty.
nextLine()Method Caution, cont.
• example
int n;
String s1, s2;
n = keyboard.nextInt();
s1 = keyboard.nextLine();
s2 = keyboard.nextLine();
5440
or bust

n isset to 5440
but s1 is set to the empty string.
The Empty String
• String with zero characters

String s3 = “”;

• Good for String initialization
Other Input Delimiters
• Characters for separating ―words‖
– Default is ―whitespace‖: space, tab, newline
• Change the delimiter to “##”

keyboard2.useDelimiter(“##”);

– whitespace will no longer be a delimiter for keyboard2
input
Other Input Delimiters, cont.
• class DelimitersDemo
Documentation and Style: Outline
•   Meaningful Names
•   Indentation
•   Named Constants (ALL CAPITAL LETTERS)
Documentation and Style
• Most programs are modified over time to
respond to new requirements.
• Programs which are easy to read and
understand are easy to modify.
• Even if it will be used only once, you have to
read it in order to debug it .
Meaningful Names for Variables
• A variable‘s name should suggest its use.
• Observe conventions in choosing names for
variables.
– Use only letters and digits.
– Use more than one character.
– ―Punctuate‖ using uppercase letters at word
boundaries (e.g. taxRate).
– Start variables with lowercase letters.
– Start class names with uppercase letters.
• The best programs are self-documenting.
– clean style
– well-chosen names
• Comments are written into a program as needed
explain the program.
– They are useful to the programmer, but they are
ignored by the compiler.
• Begin each program file with an explanatory
comment
–   what the program does
–   the name of the author
–   contact information for the author
–   date of the last modification.
• Provide only those comments which the
expected reader of the program file will need in
order to understand it.
• class CircleCalculation
• A program can usually be broken into
segments/blocks based on the algorithm, e.g. in
–   Prompt the user for input
–   Input from the keyboard
–   Calculation
–   Output to the screen
• Blank line between two segments
• A description (comment) before each segment
•   Solving a problem
1.   Devise an algorithm (steps to solve the problem)
2.   Write the algorithm in pseudocode (semi English, semi Java)
•   Tip:
1.   type the English part of pesudocode as comments into your program
first
2.   write the detailed Java instructions to satisfy/implement the
pesudocode
1.   Each line of pseudocode helps you focus on a small task
2.   Pseudocode tells you what steps you want to achieve
• A comment can begin with //.
– Everything after these symbols and to the end of the
line is treated as a comment and is ignored by the
compiler.
• A comment can begin with /* and end with */
– Everything between these symbols is treated as a
comment and is ignored by the compiler.
/* the simplex method is used to
• A javadoc comment, begins with /** and ends
with */.
– It can be extracted automatically from Java software.
/** method change requires the number of coins to
be nonnegative */
Indentation
• Indentation should communicate nesting clearly.
• A good choice is four spaces for each level of
indentation.
• Indentation should be consistent.
• Indentation should be used for second and
subsequent lines of statements which do not fit
on a single line.
Indentation, cont.
• Indentation does not change the behavior of the
program.
• Improper indentation can miscommunicate the
behavior of the program.
Named Constants
• To avoid confusion, always name constants (and
variables).
is clearer than
circumference = 3.14159 * 6.023;

• Place constants near the beginning of the
program.
Named Constants, cont.
• The value of a constant cannot be changed
once it is initialized

public static final double INTEREST_RATE = 6.65;

• Consider the interest rate is used many times in the
program:
– What if you type 6.65 in some places, but 6.56 in others?
– What if the interested rate has changed to 7.3?
– Is balance * INTEREST_RATE easier to read than
balance * 6.65 ?
Declaring Constants
• syntax
public static final Type Name = Constant;

• examples
public static final double PI = 3.14159;
public static final String MOTTO = “The customer
is always right.”;
– By convention, uppercase letters are used for
constants.
Named Constants
• class CircleCalculation2
Summary
• You have become familiar with Java primitive
types (numbers, characters, etc.).
• You have learned about assignment statements
and expressions.
• You have learned about stings.
• You have become familiar with the basics of
classes, methods, and objects.
• You have learned about simple keyboard input
and screen output.
Flow of Control
Chapter 3
Objectives
• learn about Java branching statements
• learn about the type boolean
Flow of Control
• Flow of control is the order in which a
program performs actions.
– Up to this point, the order has been
sequential.
• A branching statement chooses between two
or more possible actions.
• A loop statement repeats an action until a
stopping condition occurs.
Branching Statements: Outline
• The if-else Statement
• Introduction to Boolean Expressions
• Nested Statements and Compound
Statements
• Multibranch if-else Statements
• The switch Statament
• (optional) The Conditional Operator
The if-else Statement
• A branching statement that chooses between
two possible actions.
• syntax
if (Boolean_Expression)
Statement_1
else
Statement_2
The if-else Statement,
cont.
• example
if (count < 3)
total = 0;
else
total = total + count;
The if-else Statement, cont.
• class BankBalance
Compound Statements
• To include multiple statements in a branch,
enclose the statements in braces.
if (count < 3)
{
total = 0;
count = 0;
}
Omitting the else Part
• If the else part is omitted and the expression
after the if is false, no action occurs.
• syntax
if (Boolean_Expression)
Statement

• example
if (weight > ideal)
caloriesPerDay -= 500;
Introduction to Boolean
Expressions
• The value of a boolean expression is either
true or false.

• examples
time < limit
balance <= 0
Java Comparison Operators
Compound Boolean
Expressions
• Boolean expressions can be combined using
the ―and‖ (&&) operator.
• example
if ((score > 0) && (score <= 100))
...

• not allowed
if (0 < score <= 100)
...
Compound Boolean
Expressions, cont.
• syntax
(Sub_Expression_1) && (Sub_Expression_2)
• Parentheses often are used to enhance
• The larger expression is true only when both
of the smaller expressions are true.
Compound Boolean
Expressions, cont.
• Boolean expressions can be combined using
the ―or‖ (||) operator.
• example
if ((quantity > 5) || (cost < 10))
...

• syntax
(Sub_Expression_1) || (Sub_Expression_2)
Compound Boolean
Expressions, cont.
• The larger expression is true
– when either of the smaller expressions is
true
– when both of the smaller expressions are
true.
• ―or‖ in Java is inclusive or
– either or both to be true.
• exclusive or
– one or the other, but not both to be true.
Negating a Boolean
Expression
• Boolean negation
– ―not‖ (!) operator.
• syntax
!Boolean_Expression
• Example:
Boolean walk = false;
System.out.println(!walk);
Truth Tables
Primary Logical Operators
• Primary logical operators: and, or, not
• Any logical expression can be composed
• Example: exclusive or
(a || b) && !(a && b)
• Either work or play:
(work || play) && !(work && play)
• ^ is exclusive-or in Java
– work ^ play
– not a logical operator in most languages
Using ==
• ==   is appropriate for determining if two
integers or characters have the same value.
if (a == 3)
where a is an integer type
•   == is not appropriate for determining if two
floating point values are equal.
– Use < and some appropriate tolerance instead.
if (Math.abs(b - c) < epsilon)
– b, c, and epsilon are of floating point type
Using ==, cont.
• ==is not appropriate for determining if two
objects have the same value.
– if (s1 == s2)
• determines only if s1 and s2 are at the same
memory location.
– If s1 and s2 refer to strings with identical
sequences of characters, but stored in
different memory locations
• (s1 == s2)   is false.
Using ==, cont.
• To test the equality of objects of class String,
use method equals.
s1.equals(s2)
or
s2.equals(s1)
www.cs.fit.edu/~pkc/classes/cse1001/StringEqual.java
• To test for equality ignoring case, use method
equalsIgnoreCase.
(“Hello”.equalsIgnoreCase(“hello”))
equals and
equalsIgnoreCase
• syntax
String.equals(Other_String)
String.equalsIgnoreCase(Other_String)
Testing Strings for Equality
• class StringEqualityDemo
Lexicographic Order
• Lexicographic order is similar to alphabetical
order, but is it based on the order of the
characters in the ASCII (and Unicode)
character set.
– All the digits come before all the letters.
– All the uppercase letters come before all
the lower case letters.
Lexicographic Order, cont.
• Strings consisting of alphabetical characters
can be compared using method compareTo and
method toUpperCase or method toLowerCase.
String s1 = “Hello”;
String lowerS1 = s1.toLowerCase();
String s2 = “hello”;
if (lowerS1.compareTo(s2) == 0)
System.out.println(“Equal!”);

//or use s1.compareToIgnoreCase(s2)
Method compareTo
• syntax
String_1.compareTo(String_2)
• Method compareTo returns
– a negative number if String_1 precedes
String_2
– zero if the two strings are equal
– a positive number of String_2 precedes
String_1
– Tip: Think of compareTo is subtraction
Comparing Numbers vs.
Comparing Strings

Integer and floating-      String objects
point values
==                  equals( )
!=             equalsIgnoreCase( )

>                compareTo( )
<              [lexicographical
ordering]
>=
<=
Nested Statements
• An if-else statement can contain any sort of
statement within it.
• In particular, it can contain another if-else
statement.
– An if-else may be nested within the ―if‖
part.
– An if-else may be nested within the ―else‖
part.
– An if-else may be nested within both parts.
Nested Statements, cont.
• syntax
if (Boolean_Expression_1)
if (Boolean_Expression_2)
Statement_1
else
Statement_2
else
if (Boolean_Expression_3)
Statement_3
else
Statement_4
Nested if Example
if (temperature > 90) // int temperature
if (sunny)            // boolean sunny
System.out.println(“Beach”);
else
System.out.println(“Movie”);
else
if (sunny)
System.out.println(“Tennis”);
else
System.out.println(“Volleyball”);
Nested Statements, cont.
• Each else is paired with the nearest
unmatched if.
• Indentation can communicate which if goes
with which else.
• Braces are used to group statements.
Nested Statements, cont.
• Different indentation
first form            second form
if (a > b)          if (a >   b)
if (c > d)          if (c   > d)
e = f;              e =   f;
else                  else
g = h;                g =   h;

Same to the compiler!
Nested Statements, cont.
• Are these different?
first form           second form
if (a >   b)        if (a > b)
{                     if (c > d)
if (c   > d)          e = f;
e =   f;        else
}                     g =h;
else
g =   h;
Nested Statements, cont.
• Proper indentation and nested if-else
statements
―else‖ with outer ―if‖ ―else‖ with inner ―if‖
if (a >   b)          if (a > b)
{                       if (c > d)
if (c   > d)            e = f;
e =   f;            else
}                         g =h;
else
g =   h;
Compound Statements
• When a list of statements is enclosed in
braces ({}), they form a single compound
statement.
• syntax
{
Statement_1;
Statement_2;
…
}
Compound Statements, cont.
• A compound statement can be used
wherever a statement can be used.
• example
if (total > 10)
{
sum = sum + total;
total = 0;
}
Multibranch if-else
Statements
• syntax
if (Boolean_Expression_1)
Statement_1
else if (Boolean_Expression_2)
Statement_2
else if (Boolean_Expression_3)
Statement_3
else if …
else
Default_Statement
Multibranch if-else Statements, cont.
Multibranch if-else
Statements, cont.
• equivalent logically
if (score >= 90)
if ((score >= 80) && (score < 90))
if ((score >= 70) && (score < 80))
if ((score >= 60) && (score < 70))
if (score < 60)
switch Statement
• The switch statement is a multiway branch
that makes a decision based on an integral
(integer or character) expression.
• The switch statement begins with the keyword
switch followed by an integral expression in
parentheses and called the controlling
expression.
switch Statement, cont.
• A list of cases follows, enclosed in braces.
• Each case consists of the keyword case
followed by
– a constant called the case label
– a colon
– a list of statements.
• The list is searched for a case label matching
the controlling expression.
switch Statement, cont.
• The action associated with a matching
case label is executed.
• If no match is found, the case labeled
default is executed.
– The default case is optional, but
recommended, even if it simply prints a
message.
• Repeated case labels are not allowed.
switch Statement, cont.
• class MultipleBirths
switch Statement, cont.
• The action for each case typically ends with
the word break.
• The optional break statement prevents the
consideration of other cases.
• The controlling expression can be anything
that evaluates to an integral type (integer or
character).
The switch Statement, cont.
• syntax
switch (Controlling_Expression)
{
case Case_Label:
Statement(s);
break;
case Case_Label:
…
default:
…
}
Switch with char Type
{
case 'A':
case 'B':
case 'C':
case 'D':
System.out.println("Pass");
break;
case 'W':
System.out.println("Withdraw");
break;
case 'I':
System.out.println("Incomplete");
break;
default:
System.out.println("Fail");
}
Conditional Operator
if (n1 > n2)
max = n1;
else
max = n2;
can be written as
max = (n1 > n2) ? n1 : n2;
• The ? and : together is called the conditional
operator (a ternary operator).
• Note (n1 > n2) ? n1 : n2 is an expression that
has a value unlike the ―normal‖ if statement
Conditional Operator, cont.
• The conditional operator can be useful with
print statements.
System.out.print(“You worked “ + hours + “ “ +
((hours > 1) ? “hours” : “hour”));
Summary of branching
• if statement (1 or 2 branches)
• Multi-branch if-else-if statement (3 or
more branches)
• Multi-branch switch statement
• Conditional operator ? :
Loop Statements
• A portion of a program that repeats a
statement or a group of statements is called a
loop.
• The statement or group of statements to be
repeated is called the body of the loop.
• A loop could be used to compute grades for
each student in a class.
• There must be a means of exiting the loop.
Loop Structure
1. Control of loop: ICU
1. Initialization
2. Condition for termination (continuing)
3. Updating the condition
2. Body of loop
Loop Statements
• the while Statement
• the do-while Statement
• the for Statement
while Statement
• also called a while loop
• a controlling boolean expression
– True -> repeats the statements in the loop body
– False -> stops the loop
– Initially false (the very first time)
• loop body will not even execute once
while Statement, cont.
• syntax
while (Boolean_Expression)
Body_Statement
or
while (Boolean_Expression)
{
First_Statement
Second_Statement
…
}
while Statement, cont.
while Statement, cont.
• class WhileDemo
do-while Statement
• also called a do-while loop (repeat-until loop)
• similar to a while statement
– except that the loop body is executed at least
once
• syntax
do
Body_Statement
while (Boolean_Expression);

– don’t forget the semicolon at the end!
do-while Statement, cont.
• First, the loop body is executed.
• Then the boolean expression is checked.
– As long as it is true, the loop is executed
again.
– If it is false, the loop exits.
• equivalent while statement
Statement(s)_S1
while (Boolean_Condition)
Statement(s)_S1
do-while Statement, cont.
do-while Statement, cont.
• class DoWhileDemo
Programming Example:
Bug Infestation
• given
– volume of a roach: 0.0002 cubic feet
– starting roach population
– rate of increase: 95%/week
– volume of a house
• find
– number of weeks to exceed the capacity of
the house
– number and volume of roaches
Programming Example: Bug Infestation, cont.
• class BugTrouble
Infinite Loops
• A loop which repeats without ever ending
• the controlling boolean expression (condition
to continue)
– never becomes false
• A negative growth rate in the preceding
problem causes totalBugVolume always to be
less than houseVolume
– the loop never ends.
for Statement
• A for statement executes the body of a loop a
fixed number of times.
• example
for (count = 1; count < 3; count++)
System.out.println(count);
System.out.println(“Done”);
for Statement, cont.
• syntax
for (Initialization; Condition; Update)
Body_Statement
– Body_Statement
• a simple statement or
• a compound statement in {}.
• corresponding while statement
Initialization
while (Condition)
Body_Statement_Including_Update
for Statement, cont.
for Statement, cont.
• class ForDemo
Multiple Initialization, etc.
• example
for (n = 1, p = 1; n < 10; n++)
p = p * n

• Only one boolean expression is allowed, but
it can consist of &&s, ||s, and !s.
• Multiple update actions are allowed, too.
for (n = 1, p = 100; n < p; n++, p -= n)

• rarely used
Choosing a Loop Statement
• If you know how many times the loop will be
iterated, use a for loop.
• If you don‘t know how many times the loop
will be iterated, but
– it could be zero, use a while loop
– it will be at least once, use a do-while loop.
• Generally, a while loop is a safe choice.
Summary of loop statements
• while loop
• do-while loop
• for loop
break Statement in Loops:
NOT recommended
• A break statement can be used to end a loop
immediately.
• The break statement ends only the innermost loop
that contains the break statement.
• break statements make loops more difficult to
understand:
– Loop could end at different places (multiple
possible exit points), harder to know where.
• Always try to end a loop at only one place--makes
debugging easier (only one possible exit point)
Misuse of break Statements in loops (p.
177)
• “Because of the complications they introduce,
break statements in loops should be avoided.
• Some authorities contend that a break statement
should never be used to end a loop,
• but virtually all programming authorities agree that
they should be used at most sparingly.”
exit Method
• Sometimes a situation arises that makes
continuing the program pointless.
• A program can be terminated normally by
System.exit(0).

• example
if (numberOfWinners == 0)
{
System.out.println(“/ by 0”);
System.exit(0);
}
Programming with Loops:
Outline
•   The Loop Body
•   Initializing Statements
•   Ending a Loop
•   Loop Bugs
•   Tracing Variables
Loop Body
• To design the loop body, write out the actions
the code must accomplish.
• Then look for a repeated pattern.
action.
– The repeated pattern will form the body of
the loop.
– Some actions may need to be done after
the pattern stops repeating.
Initializing Statements
• Some variables need to have a value before
the loop begins.
– Sometimes this is determined by what is
supposed to happen after one loop
iteration.
– Often variables have an initial value of zero
or one, but not always.
• Other variables get values only while the loop
is iterating.
Ending a Loop
• If the number of iterations is known before the
loop starts, the loop is called a count-
controlled loop.
– use a for loop.
• Asking the user before each iteration if it is
time to end the loop is called the ask-before-
iterating technique.
– appropriate for a small number of iterations
– Use a while loop or a do-while loop.
Ending a Loop, cont.
• For large input lists, a sentinel value can be
used to signal the end of the list.
– The sentinel value must be different from
all the other possible inputs.
– A negative number following a long list of
nonnegative exam scores could be
suitable.
90
0
10
-1
Ending a Loop, cont.
• example - reading a list of scores followed by
a sentinel value
int next = keyboard.nextInt();
while (next >= 0)
{
Process_The_Score
next = keyboard.nextInt();
}
Ending a Loop, cont.
• class ExamAverager
Nested Loops
• The body of a loop can contain any kind of
statements, including another loop.
• In the previous example
– the average score was computed using a
while loop.

– This while loop was placed inside a do-while
loop so the process could be repeated for
other sets of exam scores.
Nested Loops
• The body of a loop can have any kind of statements,
including another loop.
for (line = 0; line < 4; line++)
body of
{
outer loop
for (star = 0; star < 5; star++)
System.out.print('*');                          body of
System.out.println();
inner loop
}

• Each time the outer loop body is executed, the inner loop
body will execute 5 times.
*****
• 20 times total                   *****  Output:
*****
*****
Declaring Variables Outside
Loop Bodies
• Declaration of variables   while (…)
inside a loop body is      {
repeated with each           int x;
…
execution of the loop
}
body--can be inefficient
• Declaration of variables
can generally be moved
outside the loop body.
Loop Bugs
• common loop bugs
– unintended infinite loops
– off-by-one errors
– testing equality of floating-point numbers
• subtle infinite loops
– The loop may terminate for some input
values, but not for others.
– For example, you can‘t get out of debt
when the monthly penalty exceeds the
monthly payment.
Off-by-One Errors
• The loop body is repeated one too many
times or one too few times.
• examples
– < is used when <= should be used or <= is
used when < should be used
– using the index of the last character of a
string instead of the length of the string (or
vice versa)
• easy to overlook
Off by One

int i = 0;
while (i <= 10)
{
System.out.println(i);
i++;
}
Empty for Statement
• What is printed by
int product = 1, number;
for (number = 1; number <= 10; number++);
product = product * number;
System.out.println(product);

• The last semicolon in
for (number = 1; number <= 10; number++);

produces an empty for statement.
Empty while Statement
int product = 1, number = 1;
while (number <= 10);
{
product = product * number;
number++;
}
System.out.println(product);
• The last semicolon in
while (number <= 10);
produces an empty while loop body.
Testing Equality of Floating-
point Numbers
• == works satisfactorily for integers and
characters.
• == is not reliable for floating-point numbers
(which are approximate quantities).
– Can cause infinite loops
– Use <= or >= rather than == or !=.
Tracing Variables
• Tracing variables means watching the
variables change while the program is
running.
– Simply insert temporary output statements
in your program to print of the values of
variables of interest
– or, learn to use the debugging facility that
may be provided by your system.
Tracing Variables, cont.
float creditCardBalance = 9000.0;
while (creditCardBalance > 0)
{
… // input payment
creditCardBalance -= payment;

… // calculate penalty
creditCardBalance += penalty;

system.out.println(creditCardBalance);
}
Type boolean
• Boolean Expressions and Variables
• Truth Tables and Precedence Rules
• Input and Output of Boolean Values
Type boolean, cont.
• The type boolean is a primitive type with only
two values: true and false.
• Boolean variables can make programs more
if (systemsAreOK)
if((temperature <= 100) && (thrust >= 12000)
&& (cabinPressure > 30) && …)
Boolean Expressions and
Variables
• Variables, constants, and expressions of type
boolean all evaluate to either true or false.

• A boolean variable can be given the value of
a boolean expression by using an assignment
operator.
boolean isPositive = (number > 0);
...
if (isPositive) ...
Naming Boolean Variables
• Choose names such as isPositive or
systemsAreOk.
• Avoid names such as numberSign or
systemStatus.
Precedence Rules
• Parentheses should be used to indicate the
order of operations.
• When parentheses are omitted, the order of
operation is determined by precedence rules.
Precedence Rules, cont.
• Operations with higher precedence are
performed before operations with lower
precedence.
• Operations with equal precedence are done
left-to-right (except for unary operations
which are done right-to-left).
Precedence Rules, cont.

Comparison operators:
<, >, <=, >=
==, !=

Logical operators:
&
|
&&
||
Precedence Rules, cont.
• In what order are the operations
performed?

score < min/2 - 10 || score > 90
score < (min/2) - 10 || score > 90
score < ((min/2) - 10) || score > 90
(score < ((min/2) - 10)) || score > 90
(score < ((min/2) - 10)) || (score > 90)
Short-circuit Evaluation
• Sometimes only part of a boolean expression
needs to be evaluated to determine the value
of the entire expression.
– If the first operand of || is true
• entire expression is true
– If the first operand of && is false
• entire expression is false
• This is called short-circuit or lazy evaluation.
Short-circuit Evaluation, cont.
• Short-circuit evaluation is not only efficient,
sometimes it is essential!
• A run-time error can result, for example, from
an attempt to divide by zero.
if ((number != 0) && (sum/number > 5))

• Complete evaluation can be achieved by
substituting & for && or | for ||.
Short-circuit Evaluation

int count = 1;
…
if ( … && (++count < 10) )
{
…
}
System.out.println(count);
Input and Output of Boolean
Values
• example
boolean boo = false;
System.out.println(boo);
System.out.print(“Enter a boolean value: “);
Scanner keyboard = new Scanner (System.in);
boo = keyboard.nextBoolean();
System.out.println(boo);
Input and Output of Boolean
Values, cont.
• dialog
false
Enter a boolean value: true
true
Using a Boolean Variable to
End a Loop
• example
{
next = keyboard.nextInt();
if (next < 0)
else
Process_Next_Number
}
Using a Boolean Variable to End a Loop, cont
• class BooleanDemo
Summary
• You have learned about Java branching
statements.
• You have learned about loops.
• You have learned about the type boolean.


DOCUMENT INFO
Shared By:
Categories:
Stats:
 views: 122 posted: 7/13/2011 language: English pages: 287