+ All Categories
Home > Documents > Chapter 1 lBackground information »important regardless of programming language lIntroduction to...

Chapter 1 lBackground information »important regardless of programming language lIntroduction to...

Date post: 19-Dec-2015
Category:
View: 219 times
Download: 0 times
Share this document with a friend
287
Transcript
Page 1: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.
Page 2: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Chapter 1

Background information» important regardless of programming language

Introduction to Java

Introduction to Computers and Java Objects

Page 3: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Computer Basics

• Computer system: hardware + software• Hardware: the physical components• Software: the instructions that tell the

hardware what to do

Page 4: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Common Hardware Components

• Processor (CPU)– Central Processing Unit– Interprets and executes the

instructions

• Memory– main & auxiliary– holds data and instructions

• Input device(s)– mouse, keyboard, etc.

• Output device(s)– video display, printer, etc.

• CPU and memory are physically housed together

Standard Hardware Organization

Memory(main & auxiliary)

Processor(CPU)

Input Devices

(such as mouse and keyboard)

Output Devices(such as video

display or printer)

Page 5: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Physical Organization

• Keyboard• Monitor• Chassis

– CPU– memory– disk drives– I/O connectors– etc.

Page 6: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 7: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Main Memory Organization

• Bit = one binary digit – Binary digit can have only

one of two values, 0 or 1• Byte = 8 bits• “Byte Addressable”

– Main memory is a list of numbered locations that contain one byte of data in each location

• Number of bytes per data item may vary

Address Data Byte

3021 1111 0000 Item 1: 2 bytes stored

3022 1100 1100

3023 1010 1010 Item 2: 1 byte stored

3024 1100 1110 Item 3: 3 bytes stored

3025 0011 0001

3026 1110 0001

3027 0110 0011 Item 4: 2 bytes stored

3028 1010 0010

3029 … Next Item, etc.

Page 8: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

A u xilia ry M em ory O rg an iza tion

F iles

F iles

F iles

F iles

S u b d irec to ry

S u b d irec to ry F iles

S u b d irec to ry

F iles

S u b d irec to ry

S u b d irec to ry S u b d irec to ry

M ain (R oo t) D irec to ry / F o ld er

Auxiliary Memory Organization[file systems for users]

Page 9: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Running a Program

Program

ComputerData(input for the program) Output

Program—a set of instructions for a computer to follow

Page 10: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 11: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Various Types of User Interfaces

• Command-line– type in key words and letters– DOS and UNIX

• Menu– parts of DOS and Windows

• GUI (Graphical User Interface)– click on icon– also called “event-driven” – MacOS, Windows

Page 12: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Programming Language Hierarchy

H ard w are

M ach in e L an g u ag e

A ssem b ly L an u ag e

H ig h -L eve l L an g u ag e (H L L )

Page 13: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

The highs and lowsof programming languages ...

High-Level Language (HLL)– closest to natural language– words, numbers, and math

symbols– not directly understood by

hardware– “portable” source code

(hardware independent)– Java, C, C++, COBOL,

FORTRAN, BASIC, Lisp, Ada, etc.

Machine Language(lowest level)

– least natural language for humans, most natural language for hardware

– just 0s and 1s– directly understood by

hardware– not portable (hardware

dependent)

Page 14: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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)

Page 15: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 16: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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,

Assembler, or

Interpreter

SourceCode

ObjectCode

Page 17: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Java Program Translation

• Both Compilation and Interpretation

• Intermediate Code:“Byte Code”– similar to assembly

code, but hardware independent

• Interpreter translates from generic byte code to hardware-specific machine code

Java Program Data for Java Program

Java Compiler

Byte-CodeProgram

Byte-Code Interpreter

Machine-LanguageInstructions

Computer Executionof Machine-Language Instructions

Output of Java Program

JavaVirtual

Machine

Page 18: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 19: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Why Use Byte Code?

Disadvantages:• requires both compiler and interpreter• slower program execution

Advantages:• 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

Page 20: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Java Program Data for Java Program

Java Compiler

Byte-CodeProgram

Byte-Code Interpreter

Machine-LanguageInstructions

Computer Executionof Machine-Language Instructions

Output of Java Program

JavaVirtual

Machine

Linker

Previously Compiled Helper Programs

Java Program Translation Including Linker

Page 21: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 22: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Example of an Object Class

Data Items:– manufacturer’s name– model name– year made– color– number of doors– size of engine– etc.

Methods:– Define data items (specify

manufacturer’s name, model, year, etc.)

– Change a data item (color, engine, etc.)

– Display data items– Calculate cost– etc.

Class: Automobile

Page 23: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 24: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Design Principles of OOP

Three main design principles of Object-Oriented Programming (OOP):

• Encapsulation

• Polymorphism

• Inheritance

Page 25: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 26: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Reusable Components

Advantages of using reusable components:• saves time and money• components that have been used before

– often better tested and more reliable than new software

Make your classes reusable:• encapsulation• general classes have a better chance of being reused

than ad hoc classes

Page 27: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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)

Page 28: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 29: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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?

Page 30: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 31: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 32: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Program Design Process

• Design, then code (not code, then design)

• Design process1. define the problem clearly2. design objects your program needs3. develop algorithms for the methods of objects4. describe the algorithms, usually in pseudocode

• Writing/Coding1. write the code2. test the code3. fix any errors and retest

Page 33: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 34: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Types of Errors

• Syntax

• Run-Time

• Logic

Page 35: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 36: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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” instead of “return”

Page 37: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 38: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 39: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Logic Error Examples

• Algorithm Error:– circleArea = radius * radius;

(pi * radius * radius)

• Implementation Error:– typed in wrong symbol in source code -sum = a - b;(should be sum = a + b;)

Page 40: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

– byte code can be downloaded and run without compiling it• 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 copyrighted, yet.

Page 41: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Applets vs. Java Applications

• Applets– Java programs intended to be downloaded via the WWW

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

Page 42: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

import java.util.*;

public class FirstProgram

{

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);

}

}

A Sample Java Program

Page 43: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 44: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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)

Page 45: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

… 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.

Page 46: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

… 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.

Page 47: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

… 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();

Page 48: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

… Explanation of Code

• Printing the sum to the console:

System.out.println(“The sum of those two numbers is:");

System.out.println(n1 + n2);

Page 49: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Compiling and Running a Java Program

• Compile– javac <file>.java

• Run (and link)– java <file>– <file> must have a main method

• BlueJ has two similar steps by mouse clicking (discussed in the labs).

Page 50: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

SummaryPart 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).

Page 51: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

SummaryPart 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)

Page 52: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Primitive Types, Strings, and Console I/O

Chapter 2

Page 53: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Objectives

• become familiar with Java primitive types (numbers, characters, etc.)

• learn about assignment statements and expressions

• learn about strings• become familiar with classes, methods, and

objects• learn about simple keyboard input and screen

output

Page 54: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Outline

• Primitive Types and Expressions• The Class String• Keyboard and Screen I/O• Documentation and Style

Page 55: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 56: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Variables and Values

• variablesnumberOfBaskets

eggsPerBasket

totalEggs

• assigning valueseggsPerBasket = 6;

eggsPerBasket = eggsPerBasket - 2;

Page 57: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.int numberOfBaskets, eggsPerBasket;

• 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.

Page 58: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Syntax and Examples

• syntaxtype variable_1, variable_2, …;

• examplesint styleChoice, numberOfChecks;

double balance, interestRate;

char jointOrIndividual;

Page 59: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 60: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 61: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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 */

}

Page 62: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 63: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 64: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 65: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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)

Page 66: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Primitive Types, cont.

Page 67: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Examples of Primitive Values

• integer types0 -1 365 12000

• floating-point types0.99 -22.8 3.14159 5.0

• character type`a` `A` `#` ` `

• boolean typetrue false

Page 68: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.”

Page 69: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Assignment Statements, cont.

• Syntaxvariable = 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 -)

Page 70: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Assignment Examples

amount = 3.99;

firstInitial = ‘W’;

score = numberOfCards + handicap;

eggsPerBasket = eggsPerBasket - 2;

(last line looks weird in mathematics, why?)

Page 71: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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;

Page 72: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Specialized Assignment Operators

• Assignment operators can be combined with arithmetic operators (including -, *, /, and %, discussed later).amount = amount + 5;

can be written asamount += 5;

yielding the same results.

Page 73: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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?)

Page 74: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Simple Input

• Sometimes the data needed for a computation are obtained from the user at run time.

• Keyboard input requiresimport java.util.*

at the beginning of the file.

Page 75: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Simple Input, cont.

• Data can be entered from the keyboard usingScanner keyboard =

new Scanner(System.in);

followed, for example, byeggsPerBasket = keyboard.nextInt();

which reads one int value from the keyboard and assigns it to eggsPerBasket.

Page 76: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Simple Input, cont.• class EggBasket2

Page 77: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 78: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 79: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 80: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Assignment Compatibilities, cont.• A value of one type can be assigned to a

variable of any type further to the rightbyte --> 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.

Page 81: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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))

Page 82: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 83: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 84: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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).

Page 85: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

ASCII/Unicode

32 33 34 35 36 37 38 39 40 41

! “ # $ % & ‘ ( )

48 … 57 … 65 … 90 … 97 … 122

0 9 A Z a z

Page 86: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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);

• >y>121>

Page 87: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 88: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 89: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Initializing Variables, cont.

• syntaxtype variable_1 = expression_1, variable_2 = expression_2, …;

Page 90: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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?– What about 5.5?

Page 91: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Binary Real Numbers

• 5.5– 101.1

• 5.25– 101.01

• 5.125– 101.001

• 5.75– 101.11

… 23 22 21 20

. 2-1 …

Page 92: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

8 bits only

• 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?

25 24 23 22 21 20 2-1 2-2

Page 93: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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?

Page 94: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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]

Page 95: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Java Floating-point Numbers

• Sign:– 1 bit [0 is positive]

• Mantissa: – 23 bits in float– 52 bits in double

• Exponent:– 8 bits in float– 11 bits in double

sign exponent mantissa

Page 96: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 97: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 98: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 99: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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)

Page 100: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 101: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 102: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 103: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 104: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Case Study, cont.

• sample dialogEnter 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

Page 105: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Case Study, cont.

• variables neededint amount, quarters, dimes, nickels, pennies;

Page 106: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Case Study, cont.

• algorithm - first version1. Read the amount.

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.

Page 107: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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 variablesint amount, originalAmount, quarters, dimes, nickles, pennies;

• and update the algorithm.

Page 108: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Case Study, cont.

1. Read the amount.

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.

Page 109: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Case Study, cont.

• Write Java code that implements the algorithm written in pseudocode.

Page 110: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 111: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 112: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Case Study, cont.• class ChangeMaker

Page 113: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 114: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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 operatorcount-- or --count

Page 115: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Increment (and Decrement) Operators

• “mostly” equivalent operationscount++;

++count;

count = count + 1;

count--;

--count;

count = count - 1;

Page 116: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Increment (and Decrement) Operators in Expressions

• after executingint m = 4;

int result = 3 * (++m)

result has a 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

Page 117: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Increment and Decrement Operator Examples

common codeint 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

Page 118: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Answers to Increment/Decrement 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

Page 119: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Summary of Operators

• +, -, *, /• %• ++, --

Page 120: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 121: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Precedence Rules

Page 122: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 123: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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++)

Page 124: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Use Parentheses

• Even when parentheses are not needed, they can be used to make the code clearer.balance + (interestRate * balance)

• [Spaces also make code clearerbalance + interestRate*balance

but spaces do not dictate precedence.]

Page 125: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Sample Expressions

Page 126: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 127: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Declaring and Printing Strings

• declaring String greeting;

greeting = “Hello!”;

orString greeting = “Hello!”;

orString greeting = new String(“Hello!”);

• printingSystem.out.println(greeting);

Page 128: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 129: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Concatenating Strings and Integers

String solution;

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

The temperature is 72

Page 130: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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()

Page 131: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 132: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

String Methods

Page 133: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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;

Page 134: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Positions in a String

• positions start with 0, not 1.– The ‘J’ in “Java is fun.” is in position 0

Page 135: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

• A position is referred to an an index.– The ‘f’ in “Java is fun.” is at index 9.

Positions in a String, cont.

Page 136: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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 Hgreeting.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

Page 137: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Using the String Class• class StringDemo

Page 138: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.”);

Page 139: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Escape Characters

• Each escape sequence is a single character even though it is written with two symbols.

Page 140: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Examples

System.out.println(“abc\\def”);

abc\def

System.out.println(“new\nline”);

new

line

char singleQuote = ‘\’’;

System.out.println(singleQuote);

Page 141: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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).

Page 142: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Keyboard and ScreenI/O: Outline

• Screen Output• Keyboard Input

Page 143: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Screen Output

• We’ve seen several examples of screen output already.

• System.out is an object that is part of Java.• println() is one of the methods available to the

System.out object.

Page 144: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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 (+).

Page 145: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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().

Page 146: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Screen Output, cont.

• syntaxSystem.out.println(output_1 + output_2 + ...+ output_n);

• exampleSystem.out.println (1967 + “ “ + “Oldsmobile” + “ “ + 442);

1967 Oldsmobile 442

Page 147: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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”

Page 148: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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:• 2004:• 22: • 6747280: all digits are printed, width is ignored

3 2 9 0 1

2 0 0 4

2 2

Page 149: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Conversion CharactersConversion 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

x integer Hexadecimal integer

% % (%% to output %)

Page 150: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Floating-point Precision• width.precision conversion• printf(“%5.2f”, PI)

• printf(“%7.4f”, PI)

3 . 1 4

3 . 1 4 1 5

Page 151: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Left Justified

• Spaces are added (padded) on the right• Minus (-) sign before the width• …printf(“%-7s %-4d”, name, age)

• Why are there 4 spaces after “John” instead of 3?

J o h n 2 0

Page 152: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Example

• http://www.cs.fit.edu/~pkc/classes/cse1001/Printf.java

Page 153: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 154: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Using the Scanner Class

• Near the beginning of your program, insertimport java.util.*

• Create an object of the Scanner classScanner keyboard =

new Scanner(System.in)

• Read data (an int or a double, for example)int n1 = keyboard.nextInt();

double d1 = keyboard.nextDouble();

Page 155: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Some Scanner Class Methods• syntax

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()

Page 156: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Some Scanner Class Methods, cont.

• examplesint 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: “);

Page 157: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Keyboard Input Demonstration• class ScannerDemo

Page 158: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

nextLine()Method Caution

• The nextLine() method reads the remainder of the current line, even if it is empty.

Page 159: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

nextLine()Method Caution, cont.

• exampleint n;

String s1, s2;

n = keyboard.nextInt();

s1 = keyboard.nextLine();

s2 = keyboard.nextLine();

5440

or bust

n is set to 5440

but s1 is set to the empty string.

Page 160: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

The Empty String

• String with zero characters

String s3 = “”;

• Good for String initialization

Page 161: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 162: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Other Input Delimiters, cont.• class DelimitersDemo

Page 163: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Documentation and Style: Outline

• Meaningful Names• Self-Documentation and Comments• Indentation• Named Constants (ALL CAPITAL LETTERS)

Page 164: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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 .

Page 165: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 166: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Documentation and Comments

• 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.

Page 167: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

When to Use Comments

• 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.

Page 168: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Comments Example• class CircleCalculation

Page 169: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Comments

• 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

Page 170: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Pseudocode and Comments• Solving a problem

1. Devise an algorithm (steps to solve the problem)2. Write the algorithm in pseudocode (semi English, semi Java)3. English part of pseudocode becomes comments in your program

• Tip: 1. type the English part of pesudocode as comments into your program

first2. write the detailed Java instructions to satisfy/implement the

pesudocode• Advantages:

1. Each line of pseudocode helps you focus on a small task2. Pseudocode tells you what steps you want to achieve3. No need to add comments later on

Page 171: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Comments

• 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.

double radius; //in centimeters

Page 172: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Comments, cont.

• 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

calculate the answer*/

Page 173: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Comments, cont.

• 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 */

Page 174: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 175: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Indentation, cont.

• Indentation does not change the behavior of the program.

• Improper indentation can miscommunicate the behavior of the program.

Page 176: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Named Constants

• To avoid confusion, always name constants (and variables).circumference = PI * radius;

is clearer thancircumference = 3.14159 * 6.023;

• Place constants near the beginning of the program.

Page 177: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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 ?

Page 178: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Declaring Constants

• syntaxpublic static final Type Name = Constant;

• examplespublic static final double PI = 3.14159;

public static final String MOTTO = “The customer is always right.”;

– By convention, uppercase letters are used for constants.

Page 179: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Named Constants• class CircleCalculation2

Page 180: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 181: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Flow of Control

Chapter 3

Page 182: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Objectives

• learn about Java branching statements• learn about loops• learn about the type boolean

Page 183: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 184: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 185: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

The if-else Statement

• A branching statement that chooses between two possible actions.

• syntaxif (Boolean_Expression)

Statement_1

else

Statement_2

Page 186: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

The if-else Statement, cont.

• exampleif (count < 3)

total = 0;

else

total = total + count;

Page 187: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

The if-else Statement, cont.• class BankBalance

Page 188: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Compound Statements

• To include multiple statements in a branch, enclose the statements in braces.if (count < 3)

{

total = 0;

count = 0;

}

Page 189: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Omitting the else Part

• If the else part is omitted and the expression after the if is false, no action occurs.

• syntaxif (Boolean_Expression)

Statement

• exampleif (weight > ideal)

caloriesPerDay -= 500;

Page 190: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Introduction to Boolean Expressions

• The value of a boolean expression is either true or false.

• examplestime < limit

balance <= 0

Page 191: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Java Comparison Operators

Page 192: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Compound Boolean Expressions

• Boolean expressions can be combined using the “and” (&&) operator.

• exampleif ((score > 0) && (score <= 100))

...

• not allowedif (0 < score <= 100)

...

Page 193: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Compound Boolean Expressions, cont.

• syntax(Sub_Expression_1) && (Sub_Expression_2)

• Parentheses often are used to enhance readability.

• The larger expression is true only when both of the smaller expressions are true.

Page 194: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Compound Boolean Expressions, cont.

• Boolean expressions can be combined using the “or” (||) operator.

• exampleif ((quantity > 5) || (cost < 10))

...

• syntax(Sub_Expression_1) || (Sub_Expression_2)

Page 195: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 196: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Negating a Boolean Expression

• Boolean negation– “not” (!) operator.

• syntax!Boolean_Expression

• Example:Boolean walk = false;

System.out.println(!walk);

Page 197: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Truth Tables

Page 198: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 199: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 200: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 201: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Using ==, cont.

• To test the equality of objects of class String, use method equals.s1.equals(s2)

ors2.equals(s1)

www.cs.fit.edu/~pkc/classes/cse1001/StringEqual.java

• To test for equality ignoring case, use method equalsIgnoreCase.

(“Hello”.equalsIgnoreCase(“hello”))

Page 202: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

equals and equalsIgnoreCase

• syntaxString.equals(Other_String)

String.equalsIgnoreCase(Other_String)

Page 203: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Testing Strings for Equality• class StringEqualityDemo

Page 204: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 205: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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)

Page 206: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Method compareTo

• syntaxString_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

Page 207: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Comparing Numbers vs. Comparing Strings

Integer and floating-point values

String objects

==

!=

equals( )

equalsIgnoreCase( )

>

<

>=

<=

compareTo( )

[lexicographical ordering]

Page 208: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 209: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Nested Statements, cont.

• syntaxif (Boolean_Expression_1)if (Boolean_Expression_2)

Statement_1else

Statement_2elseif (Boolean_Expression_3)

Statement_3else

Statement_4

Page 210: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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”);

Page 211: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 212: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Nested Statements, cont.

• Different indentation

first form second formif (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!

Page 213: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Nested Statements, cont.

• Are these different?

first form second formif (a > b) if (a > b)

{ if (c > d)

if (c > d) e = f;

e = f; else

} g =h;

else

g = h;

Page 214: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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;

Page 215: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Compound Statements

• When a list of statements is enclosed in braces ({}), they form a single compound statement.

• syntax{

Statement_1;

Statement_2;

}

Page 216: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Compound Statements, cont.

• A compound statement can be used wherever a statement can be used.

• exampleif (total > 10)

{

sum = sum + total;

total = 0;

}

Page 217: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Multibranch if-else Statements

• syntaxif (Boolean_Expression_1)

Statement_1

else if (Boolean_Expression_2)

Statement_2

else if (Boolean_Expression_3)

Statement_3

else if …

else

Default_Statement

Page 218: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Multibranch if-else Statements, cont.• class Grader

Page 219: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Multibranch if-else Statements, cont.

• equivalent logicallyif (score >= 90) grade = ‘A’;if ((score >= 80) && (score < 90)) grade = ‘B’;if ((score >= 70) && (score < 80)) grade = ‘C’;if ((score >= 60) && (score < 70)) grade = ‘D’;if (score < 60) grade = ‘F’;

Page 220: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 221: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 222: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 223: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

switch Statement, cont.• class MultipleBirths

Page 224: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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).

Page 225: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

The switch Statement, cont.• syntax

switch (Controlling_Expression){

case Case_Label:Statement(s);break;

case Case_Label:…default:…

}

Page 226: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Switch with char Type

char grade = 'A';switch(grade){ 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");

}

Page 227: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Conditional Operatorif (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

Page 228: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Conditional Operator, cont.

• The conditional operator can be useful with print statements.System.out.print(“You worked “ + hours + “ “ +

((hours > 1) ? “hours” : “hour”));

Page 229: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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 ? :

Page 230: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 231: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Loop Structure

1. Control of loop: ICU

1. Initialization

2. Condition for termination (continuing)

3. Updating the condition

2. Body of loop

Page 232: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Loop Statements

• the while Statement• the do-while Statement• the for Statement

Page 233: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 234: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

while Statement, cont.

• syntaxwhile (Boolean_Expression)

Body_Statement

or

while (Boolean_Expression)

{

First_Statement

Second_Statement

}

Page 235: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

while Statement, cont.

Page 236: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

while Statement, cont.• class WhileDemo

Page 237: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

• syntaxdo

Body_Statement

while (Boolean_Expression);

– don’t forget the semicolon at the end!

Page 238: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 239: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

do-while Statement, cont.

Page 240: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

do-while Statement, cont.• class DoWhileDemo

Page 241: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 242: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Programming Example: Bug Infestation, cont.• class BugTrouble

Page 243: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 244: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

for Statement

• A for statement executes the body of a loop a fixed number of times.

• examplefor (count = 1; count < 3; count++)

System.out.println(count);

System.out.println(“Done”);

Page 245: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

for Statement, cont.

• syntaxfor (Initialization; Condition; Update)

Body_Statement– Body_Statement

• a simple statement or • a compound statement in {}.

• corresponding while statementInitializationwhile (Condition)

Body_Statement_Including_Update

Page 246: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

for Statement, cont.

Page 247: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

for Statement, cont.• class ForDemo

Page 248: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Multiple Initialization, etc.

• examplefor (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

Page 249: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 250: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Summary of loop statements

• while loop

• do-while loop

• for loop

Page 251: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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)

Page 252: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.”

Page 253: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

exit Method

• Sometimes a situation arises that makes continuing the program pointless.

• A program can be terminated normally bySystem.exit(0).

• exampleif (numberOfWinners == 0)

{

System.out.println(“/ by 0”);

System.exit(0);

}

Page 254: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Programming with Loops: Outline

• The Loop Body• Initializing Statements• Ending a Loop• Loop Bugs• Tracing Variables

Page 255: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Loop Body

• To design the loop body, write out the actions the code must accomplish.

• Then look for a repeated pattern.– The pattern need not start with the first

action.– The repeated pattern will form the body of

the loop.– Some actions may need to be done after

the pattern stops repeating.

Page 256: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 257: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 258: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

90010-1

Page 259: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Ending a Loop, cont.

• example - reading a list of scores followed by a sentinel valueint next = keyboard.nextInt();

while (next >= 0)

{

Process_The_Score

next = keyboard.nextInt();

}

Page 260: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Ending a Loop, cont.• class ExamAverager

Page 261: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 262: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Nested Loops

• The body of a loop can have any kind of statements, including another loop.

• Each time the outer loop body is executed, the inner loop body will execute 5 times.

• 20 times total

for (line = 0; line < 4; line++){

for (star = 0; star < 5; star++)System.out.print('*');

System.out.println();}

body of inner loop

body of outer loop

Output:********************

Page 263: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Declaring Variables Outside Loop Bodies

• Declaration of variables inside a loop body is repeated with each execution of the loop body--can be inefficient

• Declaration of variables can generally be moved outside the loop body.

while (…){ int x; …}

Page 264: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 265: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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

Page 266: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Off by One

int i = 0;while (i <= 10){ System.out.println(i); i++;}

Page 267: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 268: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Empty while Statementint 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.

Page 269: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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 !=.

Page 270: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 271: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Tracing Variables, cont.

float creditCardBalance = 9000.0;while (creditCardBalance > 0){ … // input payment creditCardBalance -= payment;

… // calculate penalty creditCardBalance += penalty; system.out.println(creditCardBalance);}

Page 272: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Type boolean

• Boolean Expressions and Variables• Truth Tables and Precedence Rules• Input and Output of Boolean Values

Page 273: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Type boolean, cont.

• The type boolean is a primitive type with only two values: true and false.

• Boolean variables can make programs more readable.if (systemsAreOK)

instead ofif((temperature <= 100) && (thrust >= 12000) && (cabinPressure > 30) && …)

Page 274: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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) ...

Page 275: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Naming Boolean Variables

• Choose names such as isPositive or systemsAreOk.

• Avoid names such as numberSign or systemStatus.

Page 276: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 277: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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).

Page 278: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Precedence Rules, cont.

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

Logical operators: & | && ||

Page 279: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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)

Page 280: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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.

Page 281: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

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 ||.

Page 282: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Short-circuit Evaluation

int count = 1;

if ( … && (++count < 10) )

{

}

System.out.println(count);

Page 283: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Input and Output of Boolean Values

• exampleboolean 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);

Page 284: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Input and Output of Boolean Values, cont.

• dialogfalse

Enter a boolean value: true

true

Page 285: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Using a Boolean Variable to End a Loop

• exampleboolean numbersLeftToRead = true;

while (numbersLeftToRead)

{

next = keyboard.nextInt();

if (next < 0)

numbersLeftToRead = false;

else

Process_Next_Number

}

Page 286: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Using a Boolean Variable to End a Loop, cont• class BooleanDemo

Page 287: Chapter 1 lBackground information »important regardless of programming language lIntroduction to Java Introduction to Computers and Java Objects.

Summary

• You have learned about Java branching statements.

• You have learned about loops.• You have learned about the type boolean.


Recommended