java: primitive data types

114
1 Primitive Data Types

Upload: tareq-hasan

Post on 10-May-2015

2.797 views

Category:

Education


0 download

DESCRIPTION

Sub: Java Topic: Primitive Data Types Slide number: 1 Presented by: Mahbubul Islam (MMI) Lecturer, Dept. of CSE University of Rajshahi

TRANSCRIPT

Page 1: Java: Primitive Data Types

1

Primitive Data Types

Page 2: Java: Primitive Data Types

2

Outline

Primitive Data Types Range of Primitive Data Types Literal Constants Scientific Notation Character Literals Primitive Type Wrapper Classes Variables Symbolic Constants Arithmetic Operator Precedence Assignment statement Writing Algebraic Expressions in Java

Page 3: Java: Primitive Data Types

3

Primitive Data Types

Computer memory stores arbitrary bit patterns. A data type is a scheme for using bits to represent values. For example, the 16 bit pattern: 0000000001100111 represents the character 'g' if the data type is char; it represents 103 if the data type is short.

All values in a computer are represented using one data type or another. There are two categories of data in Java: primitive data and objects. Java has eight primitive data types:

A programmer cannot create new primitive data types. Primitive data types are built into

Java.

The data type of an object is called its class. Any Programmer-defined data type will be a type of object.

byte short int long float double char boolean

Page 4: Java: Primitive Data Types

4

Range of Primitive Data Types

Type Size Range

byte 8 bits -128 to +127

short 16 bits -32,768 to +32,767

int 32 bits about –2 billion to +2billion

long 64 bits about –10E18 to +10E18

float 32 bits -3.4E38 to +3.4E38

double 64 bits -1.7E308 to 1.7E308

char 16 bits A single character (0 to 65535)

boolean 8 bits true or false

In Java, 16 bits are used to represent a character. The representation method used is called Unicode. Characters are represented by integer codes ranging from 0000000000000000 (i.e. 0) to 1111111111111111 (i.e. 65535)

Page 5: Java: Primitive Data Types

5

Literal Constants A literal constant is a constant that is referred to by using its actual value.

Example of literals of type int: 125 -32 16 0 -123987

A literal of type long has a upper case 'L' or lower case 'l' suffix. However, NEVER use the lower case 'l' because it is easily confused with the digit '1'. Examples: 125L -32L 16L 0L -123987L

By default, a numeric literal containing a decimal point is of type double. Examples: 123.0 -123.5 -198234.234 0.00000381 A literal of type double may also be suffixed by ‘d’ or ‘D’. Examples: 123.0d -123.5D -198234.234d 0.00000381D 8912D

A literal of type float has upper case ‘F’ or lower case ‘f’ suffix. Examples: 123.0f -123.5F -198234.234f 0.00000381F

Note: A numeric literal must not contain commas.

Page 6: Java: Primitive Data Types

6

Scientific Notation A literal of type float or double can be written in scientific notation: number * 10exponent

In Java a number in scientific notation is expressed in the form:

Where: The sign fields are optional for + The suffix field is optional for literals of type double Number is an integer or a decimal point number that is NOT suffixed by d, D, f, or F

Examples: 1.23E+02 -1.235E+02 -1.98234234E+05 3.81E-06 +12.40e209 23E33 234e+5d 4.45E2F

sign number E or e sign integerExponent

Suffix: d, D, f, of F

Note: The number 52E2.0 is invalid because the exponent is not an integer.

Page 7: Java: Primitive Data Types

7

Character Literals In a program, a character literal is surrounded with an apostrophe on both sides:

Examples: 'm' 'y' 'A'

In a program, control characters are represented with several characters inside the apostrophes.

Examples: '\n' '\t' The first one represents the 16 bit newline character and the second one represents the tabulation

character. Example: The output of the following Java statements: System.out.println("Salaam\nShabaab");

System.out.println("45\t600\n2\t12"); is:

SalaamShabaab45 6002 12

Note: A character enclosed in double quotes like "W" is not a character literal; it is a String literal. String is a built in class of the Java language.

Page 8: Java: Primitive Data Types

8

Primitive Type Wrapper Classes For each primitive type, there is a corresponding wrapper class. A wrapper class can be used to convert a primitive data value into an object, and

some type of objects into primitive data. The table shows primitive types and their wrapper classes:

Primitive type Wrapper class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

Note: Java is a case sensitive language

Page 9: Java: Primitive Data Types

9

Declaration of a Variable A variable is a named memory location in which a value of a particular data type is stored. In Java, a variable cannot be used in a program unless it has been declared. The declaration gives a name and a data type for the variable. It may also initialize the variable to a particular value. A variable can be declared only once. A variable declaration may be made in several ways:

dataType variableName;dataType variableName = initialValue ;dataType variableNameOne, variableNameTwo ;dataType variableNameOne = initialValueOne,

variableNameTwo = initialValueTwo ; Examples:

int counter;int numStudents = 583;float batchAverage = 0.406F;char grade = ‘B’;double length, width, area;boolean isEmpty = true;

Page 10: Java: Primitive Data Types

10

The name of a Variable There are several things in programs (including variables) that need to be named. Such a programmer-picked name is called an identifier.

The rules for choosing an identifier are: Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character '_', and character '$'.

A name cannot contain the space character. A name cannot start with a digit. A name can be any length. Java is case sensitive; upper and lower case count as different characters.

So  SUM  and  Sum  are different names. A name can not be a reserved word like int, double, or Character. A name must not already be in use in that part of the program.

Variable naming convention: A variable name is a noun, noun phrase or adjective A variable name starts with small letter and each phrase's first letter capitalized Examples: studentName, color, yearlySalary, quizGrade

Page 11: Java: Primitive Data Types

11

Symbolic Constants

One use of the modifier final is to indicate symbolic constants. By convention, symbolic constants are written in uppercase letters. Underscores

separate words:

final double SPEED_OF_LIGHT = 3.0E+10;

final double CM_PER_INCH = 2.54;

final int MONTH_IN_YEAR = 12;

Page 12: Java: Primitive Data Types

12

Example Program

Here is an example program, containing variable and symbolic constant declarations:

public class CalculateArea{ public static void main(String[] args){ int length = 12; // length in inches int width = 7; // width in inches final double CM_PER_INCH = 2.54; System.out.println(“length = ” + length + “ inches”); System.out.println(“width = ” + width + “ inches”); System.out.println(“area = ” + (length* CM_PER_INCH * width * CM_PER_INCH) + “ square centimeters”); } } The character * means multiply

When it follows a character string, + means to add characters to the end of the

character string.

Page 13: Java: Primitive Data Types

13

Arithmetic Operators

Operator Description

+ Adds op1 and op2

- Subtracts op2 from op1

* Multiplies op1 by op2

/ Divides op1 by op2

% Remainder of dividing op1 by op2

A simple arithmetic expression has the form:

op1 Operator op2

where:

Page 14: Java: Primitive Data Types

14

Arithmetic Operators (Cont’d) The operators give results depending on the type of the operands.

If operand1 and operand2 are integer, then the result is also integer. But if either

operand1 and/or operand2 is double, then the result is double.

Examples:

Arithmetic expression Value

1 / 2 0

86 / 10 8

86 / 10.0 8.6

86.0 / 10 8.6

86.0 / 10.0 8.6

86 % 10 6

Page 15: Java: Primitive Data Types

15

Remainder with Negative Integers

The remainder operator can be used with negative integers. The rule is:

1. Perform the operation as if both operands were positive.

2. If the left operand is negative, then make the result negative.

3. If the left operand is positive, then make the result positive.

4. Ignore the sign of the right operand in all cases.

For example:

17 % 3 is 2 -17 % 3 is -2 17 % -3 is 2 -17 % -3 is -2

Page 16: Java: Primitive Data Types

16

Arithmetic Operator Priority An expression is a sequence of variables, constants, operators, and method calls that

evaluates to a single value.

Arithmetic expressions are evaluated according to the priority rules.

All binary operators are evaluated in left to right order.

In the presence of parenthesis, evaluation starts from the innermost parenthesis.

Operators Priority (Precedence)

+ - (unary) 1

* / % 2

+ - (binary) 3

Expression Value

3 + 7 % 2 4

(2 – 5) * 5 / 2 -7

2 – 5 + 3 0

Page 17: Java: Primitive Data Types

17

Assignment Statement

variable = expression;

The expression in the right is evaluated and the result is assigned to the variable in the left.

The left side must be a variable.

Examples:

a = 5;b = a;b = b + 12; // valid: assignment operator is not equals operatorc = a + b;a + b = c; // invalid: left side not a variable

Syntax:

Page 18: Java: Primitive Data Types

18

Assignment Statement (cont’d)

To exchange (or to swap) the contents of two variables, a third variable must be used.

Example:

double x = 20.5, y = -16.7, temp; temp = x; x = y; y = temp;

Page 19: Java: Primitive Data Types

19

Writing Algebraic Expressions in Java All operators must be explicit especially multiplications.

For a fraction, you must use parenthesis for the numerator or denominator if it has addition or subtraction.

Algebraic expression Java expression

z = (4 * x + y) / x2 – 2 * y

Page 20: Java: Primitive Data Types

20

Example1

public class RemainderExample

{

public static void main(String[] args)

{

int quotient, remainder;

quotient = 17 / 3;

remainder = 17 % 3;

System.out.println("The quotient : " + quotient );

System.out.println("The remainder: " + remainder );

System.out.println("The original : " + (quotient*3 + remainder));

}

}

Page 21: Java: Primitive Data Types

21

Example2 The following example calculates the area and circumference of circle. Algorithm:

» radius = 3» area = pi * radius2 » circumference = 2 * pi * radius» print area, circumference

public class Circle{ public static void main(String[]args){

double area, circumference; int radius = 3;

final double PI = 22 / 7; area = PI * radius * radius; circumference = 2 * PI * radius; System.out.println("Area = " + area + “ square cm”); System.out.println("Circumference = " + circumference + “ cm”);}

}

Page 22: Java: Primitive Data Types

22

Making Decisions

Page 23: Java: Primitive Data Types

23

Objectives

Review Examples

Control flow and its different types

if-statement and its variations

Simple vs. Compound statements

Relational operators

Logical operations and expressions

Operators precedence table

Page 24: Java: Primitive Data Types

24

Review Example 1

import java.io.*;class RestaurantBill{ public static void main (String[] args) throws IOException { String charData; double basicCost; BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) );

System.out.println("Enter the basic cost:"); charData = stdin.readLine(); basicCost = Double.parseDouble( charData ) ;

System.out.println("basic cost: " + basicCost + " total cost: " + (basicCost + basicCost*0.06 + basicCost*0.20)); }}

Page 25: Java: Primitive Data Types

25

Review Example 2import java.io.*;class SquareRoot{ public static void main (String[] args) throws IOException { String charData; double value;

// read in a double BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); System.out.print ("Enter a double:"); charData = stdin.readLine(); value = Double.parseDouble( charData ) ; // calculate its square root double result = Math.sqrt( value ); // write out the result System.out.println("square root: " + result ); }}

Page 26: Java: Primitive Data Types

26

Control Flow In any program, Control Flow answers the following

question:

“Which statement to execute next??”

There are three types of control flow:

1. Sequential

2. Selective

3. Iterative

Sequential Control Flow:

You have seen that before…!!!

Do we have an option in executing “Statement 2” after “Statement 1”?

Statement 1

Statement 2

Statement 3

Page 27: Java: Primitive Data Types

27

Control Flow (cont.)

Selective Control Flow:

Based on this chart, what are the possibilities?

Can “Statement 2” and “Statement 3” be executed together? Ask a

true/falsequestion

Statement 2 Statement 3

Statement 4

True False

Statement 1

Page 28: Java: Primitive Data Types

28

Control Flow (cont.)

Iterative Control Flow:

Based on this chart, what are the possibilities?

What will happen if the true/false question is always true?

More on iterative control flow later.

Statement 1

Statement 2

Statement 3

Ask atrue/falsequestion

False

True

Page 29: Java: Primitive Data Types

29

The if-else-statement One way to ask the true/false question is the if-else-Statement, which looks as

follows

int x=4;

if(x<0) // A true/false question

System.out.println(“Negative”);

// when the answer is true

else

System.out.println(“Positive”);

// when the answer is false

System.out.println(“Done”);

Identify the flow of execution if x=-4.

The last statement will be always executed…

is x < 0

Print“Negative”

Print“Positive”

Print“Done”

True False

int x=4;

Page 30: Java: Primitive Data Types

30

The if-statement Note that the else-part is optional.

int x=4;

if(x<0) // A true/false question

System.out.println(“Negative”);

// when the answer is true

System.out.println(“Done”);

Identify what is the flow of execution if x=-4.

is x < 0

Print“Negative”

Print“Done”

True

False

int x=4;

Page 31: Java: Primitive Data Types

31

Compound Statements What if more than one statement are to be executed when the condition is true (or

false)..??

Statements that we usually use are called simple statements.» They always end with semi-colon (;).

Simple statements can be grouped to form a compound statement using braces { } .For example, the following code will put the absolute value of x in y.

int x=-4, y;if(x<0){ // the if-block: executed when the condition is true

System.out.println(“Negative”);y=-x;

}else{ // the else-block: executed when the condition is false

System.out.println(“Positive”);y=x;

}

Page 32: Java: Primitive Data Types

32

Nested if-else-statements Sometimes, it is required to ask more than one true/false

question to get the answer.

if(mark<50)

System.out.println(“Very bad”);

else if(mark<70)

System.out.println(“Acceptable”);

else if(mark<85)

System.out.println(“Good”);

else

System.out.println(“Excellent”);

When will “Acceptable” be printed? How about “Excellent”? What is the output if mark=60?

mark<50Print

“Very bad”

Print“Excellent”

True

False

TruePrint

“Acceptable”mark<70

False

TruePrint “Good” mark<85

False

Page 33: Java: Primitive Data Types

33

Different Types of Operators

There are three types of operators:

1. Arithmetic 2. Relational 3. Logical

ArithmeticOperator

numbernumber

number

RelationalOperator

numbernumber

boolean

LogicalOperator

booleanboolean

boolean

Page 34: Java: Primitive Data Types

34

Relational Operators Relational operators determine the relationship between two numbers. The result of a relational operator is boolean (true/false). The operands of a relational operator can be numeric constants, variables or

arithmetic expressions.

Examples: (Determine the result of each relational expression.)» 5 > x (take x=4)» 2+3 == 10/2» 12%5 > Math.sqrt(9)

Operator

Meaning

== equal

!= not equal

> greater than

>= greater than or equal

< less than

<= less than or equal

RelationalOperator

numbernumber

boolean

Page 35: Java: Primitive Data Types

35

Logical Operators Logical operators are used to manipulate boolean values. The result of a logical operator is boolean. The operands of a logical operator can be boolean constants (true/false), boolean

variables, relational expressions or logical expressions.

&& and || are binary operators. They take two operands. ! is a unary operator. It takes one operand only.

The output of a && is true only if both operands are true. The output of a || is true if any (or both) of the operands is true. The output of a ! is true only if its operand is false.

LogicalOperator

booleanboolean

boolean

Operator Meaning

&& Logical and

|| Logical or

! Logical not

Page 36: Java: Primitive Data Types

36

Logical Expressions Examples:

(Determine the result of each expression.)» x < 6 && x > 2 (take x=4)» !(-3*5 > 12)» (5 > 6 || 7-1 != 3) && !(12 < 0)

The result of the condition in the if-statement must be boolean. Then, this condition can be relational expression or boolean expression, but it cannot be an arithmetic expression.

Note that the type of input and output of each of the three types of operators defines their precedence (order of evaluation).

» Arithmetic operators are evaluated first to combine all numbers.» Then, relational operators are used to replace all numbers with boolean values.» Lastly, logical operators are used to combine all of the boolean values into one single boolean

value. This is considered as the result of the expression.

There is only one exception to this rule. Logical not is given the highest precedence.

Page 37: Java: Primitive Data Types

37

Operator Precedence Table

Note: some of these operations haven’t been visited yet. They are included for completeness.

Operator Type Code

Postfix expr++ expr--

Unary ++expr --expr +expr -expr !

Creation or Cast new (type)expr

Multiplicative * / %

Additive + -

Relational < > <= >=

Equality == !=

Logical AND &&

Logical OR ||

Assignment = += -= *= /= %=

Page 38: Java: Primitive Data Types

38

Example

import java.io.*;class CookieChecker{ public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) ); // get the number of cups of flour System.out.println("How much flour do you have?"); String inData = stdin.readLine(); int flour = Integer.parseInt( inData ); // get the number of cups of sugar System.out.println("How much sugar do you have?"); inData = stdin.readLine(); int sugar = Integer.parseInt( inData );

// check that there are enough of both ingredients if ( flour >= 4 && sugar >= 2 ) System.out.println("Enough for cookies!" ); else System.out.println("sorry...." ); }}

Page 39: Java: Primitive Data Types

39

Making Decisions with theif and if...else Structures

if statement» Simplest statement to make decision

» Boolean expression appears within parentheses

» Space between keyword if and opening parentheses

» Statement ends if it evaluates as true» Execution always continues to next independent statement

» Use double equal sign to determine equivalency

Page 40: Java: Primitive Data Types

40

Making Decisions with theif and if...else Structures (continued)

if statement (continued)» Use Boolean expression in parentheses

» Or store Boolean expression’s value in a Boolean variable– If statement similar to English-language statement

Page 41: Java: Primitive Data Types

41

Decision Structure Illustrating an if Statement

Page 42: Java: Primitive Data Types

42

The if...else Structure

Single-alternative if» Only perform action, or not

– Based on one alternative

Dual-alternative if» Two possible courses of action

if...else statement» Performs one action when Boolean expression evaluates true» Performs different action when Boolean expression evaluates false

Page 43: Java: Primitive Data Types

43

The if...else Structure (continued)

if...else statement (continued)» Statement that executes when if is true or false ends with semicolon

» Vertically align keyword if with the keyword else» Illegal to code else without if» Depending on evaluation of Boolean expression following if

– Only one resulting action takes place

Page 44: Java: Primitive Data Types

44

An if...else Structure

Page 45: Java: Primitive Data Types

45

Using Multiple Statementsin an if or if...else Structure

Execute more than one statement» Use pair of curly braces

– Place dependent statements within a block

– Crucial to place curly braces correctly

Block statements to depend if or else– Any variable declared within a block is local to that block

Page 46: Java: Primitive Data Types

46

Erroneous Overtime Pay Calculation with Missing Curly Braces

Page 47: Java: Primitive Data Types

47

Nesting if and if...else Statements

Nested if statements» Statements in which if structure contained inside another if structure

» Use when two conditions must be met before some action taken

Pay careful attention to placement of else clauses else statements

» Always associated with ifs on “first in-last out” basis

Page 48: Java: Primitive Data Types

48

Code for Bonus-Determining Decision Using Nested if Statements

Page 49: Java: Primitive Data Types

49

Using Logical AND and OR Operators

Logical AND operator» Alternative to some nested if statements

» Used between two Boolean expressions to determine whether both are true» Written as two ampersands (&&)

– Include complete Boolean expression on each side

» Both Boolean expressions that surround operator – Must be true before action in statement can occur

Page 50: Java: Primitive Data Types

50

Using Logical AND and OR Operators (continued)

Logical OR operator» Action to occur when at least one of two conditions is true

» Written as ||– Sometimes called pipes

Page 51: Java: Primitive Data Types

51

Code Segment for Bonus-Determining Decision Using the || Operator

Page 52: Java: Primitive Data Types

52

Avoiding Common ErrorsWhen Making Decisions

Frequent errors» Assignment operator instead of

– Comparison operator when testing for equality

» Insert semicolon – After Boolean expression in if statement

» Failing to– Include complete Boolean expression on each side of && or || operator

– Block set of statements with curly braces

Page 53: Java: Primitive Data Types

53

Avoiding Common ErrorsWhen Making Decisions (continued)

Errors with if statements occur at certain times» When

– Performing range check Incorrectly Inefficiently

– Using wrong operator with AND and OR

Page 54: Java: Primitive Data Types

54

Performing Accurate and Efficient Range Checks

Range check» Series of if statements that determine whether

– Value falls within specified range

» Java programmers commonly place each else– of subsequent if on same line

» Within nested if...else– Most efficient to ask most likely question first

– Avoid asking multiple questions

Page 55: Java: Primitive Data Types

55

Improved and Efficient Commission-Determining Logic

Page 56: Java: Primitive Data Types

56

Using AND and OR Appropriately

Beginning programmers’ errors » Use AND operator when meant to use OR

» No payRate value can ever be – Both below 5.65 and over 60 at same timeif(payRate < 5.65 && payRate > 60)

System.out.println("Error in pay rate");

– Use pipes “||” operator instead

» Use single ampersand or pipe– To indicate logical AND or OR

Page 57: Java: Primitive Data Types

57

Using the switch Statement

switch statement» Alternative to

– Series of nested if statements

» Test single variable against series of exact Integer Or character values

Page 58: Java: Primitive Data Types

58

Using the switch Statement (continued)

Switch structure keywords» switch

– Starts structure

– Followed by test expression

– Enclosed in parentheses

» case – Followed by one of the possible values for test expression and colon

Page 59: Java: Primitive Data Types

59

Using the switch Statement (continued) Switch structure keywords (continued)

» break – Optionally terminates switch structure at end of each case

» default – Used prior to any action if test variable does not match any case– Optional

Page 60: Java: Primitive Data Types

60

Determining Class Status Using a switch Statement

Page 61: Java: Primitive Data Types

61

Using the switch Statement (continued)

break statements in switch structure» If break statement omitted

– Program finds match for test variable

– All statements within switch statement execute from that point forward

case statement» No need to write code for each case

» Evaluate char variables– Ignore whether uppercase or lowercase

Page 62: Java: Primitive Data Types

62

Using the switch Statement (continued)

Why use switch statements?» Convenient when

– Several alternative courses of action depend on single integer or character variable

» Only when there are– Reasonable number of specific matching values to be tested

Page 63: Java: Primitive Data Types

63

Using the Conditionaland NOT Operators

Conditional operator» Requires three expressions

– Separated with question mark and colon

» Used as abbreviated version of if...else structure

» Never required to use

Syntax of conditional operatortestExpression ? trueResult : falseResult;

Page 64: Java: Primitive Data Types

64

Using the Conditionaland NOT Operators (continued)

Boolean expression evaluated as true or false » If testExpression value true

– Entire conditional expression takes on value of expression following question mark

» If value false– Entire expression takes on value of false result

Advantage of using conditional operator » Conciseness of statement

Page 65: Java: Primitive Data Types

65

Using the NOT Operator

NOT operator» Written as exclamation point (!)

» Negates result of any Boolean expression

» When preceded by NOT operator – Any expression evaluates as

true becomes false false becomes true

Statements with NOT operator» Harder to read

» Require double set of parentheses

Page 66: Java: Primitive Data Types

66

Understanding Precedence

Combine as many AND or OR operators as needed Operator’s precedence

» How expression evaluated

» Order agrees with common algebraic usage– Arithmetic done first

– Assignment done last

– AND operator evaluated before OR operator

– Statements in parentheses evaluated first

Page 67: Java: Primitive Data Types

67

Operator Precedence for Operators Used So Far

Page 68: Java: Primitive Data Types

68

Understanding Precedence (continued)

Two important conventions» Order in which operators used

» Always use parentheses – Change precedence

– Or make your intentions clearer

Page 69: Java: Primitive Data Types

69

You Do It

Using an if...Else Creating an event class to use in a decision-making application Writing an application containing multiple statements depending on

an if...else Nesting if statements Using the switch statement

Page 70: Java: Primitive Data Types

70

Iteration (Looping)

Page 71: Java: Primitive Data Types

71

Iterative Control Flow In iterative control flow, some statements are repeated as

long as the value of a condition is true.

This idea can be represented by the next graph (flowchart).

By looking at this chart:» Can you describe the order of execution in this program?

» What is the least number of times Statement 2 will be executed?

Statement 1

Statement 2

Statement 3

Ask atrue/falsequestion

False

True

Page 72: Java: Primitive Data Types

72

while-statement One of the iterative statements in Java is the while-statement. Its general form is:

while(condition) // a true/false questionstatements

The while condition can be any relational or logical expression. For example

int x=0;while(x<10){

System.out.println(x);x++; // same as (x = x + 1)

} System.out.println(“Done”);

What is the output of this code? What would happen if x started as 15?

Page 73: Java: Primitive Data Types

73

while-statement (cont)

Usually, a counter is used with the while-statement.

» This counter has to be initialized outside the loop.

» Also, it has to be updated inside the loop.

int count = 1; // start count out at one while ( count <= 3 ) // loop while count is <= 3 { System.out.println( "count is:" + count ); count = count + 1; // add one to count } System.out.println( "Done with the loop" );

Page 74: Java: Primitive Data Types

74

A Complete Example 1import java.io.*;class loopExample { public static void main (String[] args ) throws IOException {

BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));

System.out.println( "Enter initial value:" ); String inputData = stdin.readLine(); int count = Integer.parseInt( inputData ); System.out.println( "Enter limit value:" ); inputData = stdin.readLine(); int limit = Integer.parseInt( inputData ); while ( count <= limit ) {

System.out.println( "count is:" + count ); count = count + 1;

} System.out.println( "Done with the loop" ); }

}

Page 75: Java: Primitive Data Types

75

Counting Upward/Downward

int count = 0; // count is initialized

while ( count <= 6 ) // count is tested

{

System.out.println( "count is:" + count );

count = count + 2; // count is increased by 2

}

System.out.println( "Done counting by two's." );

» How can we count downward?

Page 76: Java: Primitive Data Types

76

Infinite Loop

What happens when we run the following code?

int count = 13;

int decrement = -1;

while ( count >= 0 ) // GREATER-than-or-equal operator

{

System.out.println( "count is:" + count );

count = count - decrement;

}

System.out.println( "Count was " + count + " when it failed the test");

Page 77: Java: Primitive Data Types

77

A Complete Example 2import java.io.*;class addUpIntegers { public static void main (String[] args ) throws IOException {

BufferedReader userin = new BufferedReader (new InputStreamReader(System.in));int N, sumAll = 0, sumEven = 0, sumOdd = 0;

System.out.println( "Enter limit value:" ); String inputData = userin.readLine(); N = Integer.parseInt( inputData ); int count = 0 ; while ( count <= N ) {

sumAll = sumAll + count ; if ( count % 2 == 0 ) sumEven = sumEven + count ; else sumOdd = sumOdd + count ; count = count + 1 ;

} System.out.print ( "all : " + sumAll + "\teven: " + sumEven + "\todd : " + sumOdd );

}}

Page 78: Java: Primitive Data Types

78

Nested Loops

What will the following program fragment print out?

int numRows = 4, numStars = 3; int row = 1; while ( row <= numRows ) {

int star = 1; while ( star <= numStars ) {

System.out.print("*"); star = star + 1;

} System.out.println(); // need to do this to end each line row = row + 1;

}

Page 79: Java: Primitive Data Types

79

Sentinel Controlled Loops

Add up a user-input sequence of integers terminated by a zero. ……. // get the first value System.out.println( "Enter first integer (enter 0 to quit):" ); inputData = userin.readLine(); value = Integer.parseInt( inputData ); // "fresh" value, while ( value != 0 ) {

sum = sum + value; //add value to sum System.out.println( "Enter next integer (enter 0 to quit):" ); //get the next

value inputData = userin.readLine(); value = Integer.parseInt( inputData ); // "fresh" value,

} System.out.println( "Sum of the integers: " + sum );

Improve the code so that the prompt says: “Enter the 1st integer”, “Enter the 2nd integer”, “Enter the 3rd integer”, and so on.

Page 80: Java: Primitive Data Types

80

Sentinel Controlled Loops, Cont’d

sum = sum + value; // add current value to the sum

count = count + 1; // one more integer has gone into the sum

if ( count+1 == 2 )

suffix = "nd";

else if ( count+1 == 3 )

suffix = "rd";

else suffix = "th";

System.out.println( "Enter the " + (count+1) + suffix + " integer (or 0 to quit):" );

//get the next value from the user

inputData = userin.readLine();

value = Integer.parseInt( inputData );

Page 81: Java: Primitive Data Types

81

Result-controlled Loops

class SquareRoot {

public static void main( String[] args ) {

final double smallValue = 1.0E-14 ;

double N;

N = 3;

double guess = 1.00 ;

while ( Math.abs( N/(guess*guess) - 1.0 ) > smallValue ) {

// calculating a new guess as follows

// gets us closer to the square root according to “Newton’s Method”

guess = N/(2*guess) + guess/2 ; // calculate a new guess

}

System.out.println("The square root of " + N + " is " + guess ) ;

}

}

Computing the root of 3.0

Page 82: Java: Primitive Data Types

82

Learning About the Loop Structure

Loop» Structure allows repeated execution of a block of statements

Loop body» Block of statements

» Executed repeatedly

Page 83: Java: Primitive Data Types

83

Learning About the Loop Structure (continued)

Three types of loops» while » for» do...while

Page 84: Java: Primitive Data Types

84

Flowchart of a Loop Structure

Page 85: Java: Primitive Data Types

85

Using a while Loop To Createa Definite Loop

while loop» Executes body of statements continually

» As long as Boolean expression that controls entry into loop continues to be true

Consists of keyword while » Followed by Boolean expression within parentheses

» Followed by body of loop – Can be single statement or block of statements surrounded by curly braces

Page 86: Java: Primitive Data Types

86

A while Loop that Prints the Integers 1 through 10

Page 87: Java: Primitive Data Types

87

Using a while Loop To Createa Definite Loop (continued)

Definite loop» Performs task predetermined number of times

» Also called counted loop

Write a definite loop» Initialize loop control variable

– Variable whose value determines whether loop execution continues

» While loop control variable does not pass limiting value – Program continues to execute body of while loop

Page 88: Java: Primitive Data Types

88

Using a while Loop To Createa Definite Loop (continued)

Write a definite loop (continued)» Body of loop

– Must include statement that alters loop control variable

Infinite loop» Loop that never ends

» Can result from mistake in while loop

» Don’t intentionally write

Page 89: Java: Primitive Data Types

89

A Loop that Displays “Hello” Infinitely

Page 90: Java: Primitive Data Types

90

Using a while Loop To Createa Definite Loop (continued)

Suspect infinite loop» Same output displayed repeatedly

» Screen remains idle for extended period of time

Exit from infinite loop» Press and hold Ctrl

– Press C or Break

Page 91: Java: Primitive Data Types

91

Using a while Loop To Createa Definite Loop (continued)

Prevent while loop from executing infinitely Named loop control variable initialized to starting value Loop control variable tested in while statement If test expression true

» Body while statement takes action – Alters value of loop control variable

» Test of while statement must eventually evaluate to false

Page 92: Java: Primitive Data Types

92

A while Loop that Prints “Hello” Infinitely Because loopCount is Not Altered in the Loop

Body

Page 93: Java: Primitive Data Types

93

Using a while Loop To Createa Definite Loop (continued)

Loop control variable» Variable altered and stored with new value

loopCount = loopCount + 1– Equal sign assigns value to variable on left

» Variable should be altered within body of loop

Empty body» Body with no statements

» Caused by misplaced semicolons

Page 94: Java: Primitive Data Types

94

A while Loop that Loops Infinitely with No Output Because the Loop Body is Empty

Page 95: Java: Primitive Data Types

95

Using a while Loop To Createa Definite Loop (continued)

Increment variable» Alter value of loop control variable by adding 1

Decrement variable» Subtract 1 from loop control variable

Clearest and best method » Start loop control variable at 0 or 1

» Stop when loop control variable reaches limit

» Increment by 1 each time through loop

Page 96: Java: Primitive Data Types

96

A while Loop that Prints “Hello” Twice, Decrementing the loopCount Variable in the Loop

Body

Page 97: Java: Primitive Data Types

97

Using a while Loop to Createan Indefinite Loop

Indefinite loop» Event controlled

– Controlled by user

– Executed any number of times

Validating data » Ensures value falls within specified range

» Use indefinite loops to validate input data

» If user enters incorrect data – Loop repeats

Page 98: Java: Primitive Data Types

98

Using Shortcut Arithmetic Operators

Accumulating» Repeatedly increasing value by some amount

Java provides shortcuts for incrementing and accumulating» += adds and assigns result

– Also use -=, *=, and /=

» Prefix and postfix operator– ++someValue, someValue++– Use only with variables

Page 99: Java: Primitive Data Types

99

Using Shortcut Arithmetic Operators (continued)

Prefix and postfix increment operators » Unary operators

– Use with one value

» Arithmetic operators– Binary operators

– Operate on two values

» To increase variable’s value by 1– No difference between operators (unless other operations in same expression)

Page 100: Java: Primitive Data Types

100

Four Ways to Add 1 to a Value

Page 101: Java: Primitive Data Types

101

Using Shortcut Arithmetic Operators (continued) Prefix and postfix increment operators (continued)

» Prefix ++– Result calculated and stored– Then variable used

» Postfix ++ – Variable used– Then result calculated and stored

Prefix and postfix decrement operators--someValuesomeValue--

» Similar logic to increment operators

Page 102: Java: Primitive Data Types

102

Using a for Loop

for Loop» Used when definite number of loop iterations required

» One convenient statement– Starting value for loop control variable

– Test condition that controls loop entry

– Expression that alters loop control variable

Page 103: Java: Primitive Data Types

103

A for Loop that Prints the Integers 1 through 10

Page 104: Java: Primitive Data Types

104

Using a for Loop (continued)

Other uses for three sections of for loop» Initialize more than one variable

– Place commas between separate statements

for(g = 0, h = 1; g < 6; ++g)

» Perform more than one test using AND or ORfor(g = 0; g < 3 && h > 1; ++g)

» Decrement or other taskfor(g = 5; g >= 1; --g)

Page 105: Java: Primitive Data Types

105

Using a for Loop (continued)

Leave one or more portions of for loop empty» Two semicolons still required

for(; x < 10; ++x)...

Use same loop control variable in all three parts of for statement

Page 106: Java: Primitive Data Types

106

Using a for Loop (continued)

To pause program» Use for loop that contains no body

for(x = 0; x < 100000; ++x);

» Or built-in sleep() method

Page 107: Java: Primitive Data Types

107

Learning How and When to Usea do...while Loop

do...while loop » Posttest loop

» Checks value of loop control variable – At bottom of loop

– After one repetition has occurred

» Performs task at least one time

» Never required to use this type of loop

» Use curly brackets to block statement– Even with single statement

Page 108: Java: Primitive Data Types

108

General Structure of a do...while Loop

Page 109: Java: Primitive Data Types

109

Learning About Nested Loops

Inner and outer loops» Inner loop must be entirely contained in outer loop

» Loops can never overlap

» Outer loop – All encompassing loop

Page 110: Java: Primitive Data Types

110

Learning About Nested Loops (continued)

To print three mailing labels for each of 20 customersfor(customer = 1; customer <= 20; ++customer)

for(label = 1; label <= 3; ++label)

printLabelMethod();

Page 111: Java: Primitive Data Types

111

Nested Loops

Page 112: Java: Primitive Data Types

112

Improving Loop Performance

Make sure loop does not include unnecessary operations or statements Expression calculated each time loop runs

while (x < a + b)

// loop body

Page 113: Java: Primitive Data Types

113

Improving Loop Performance (continued)

Calculation occurs only onceint sum = a + b;

while(x < sum)

// loop body

Page 114: Java: Primitive Data Types

114

You Do It

Writing a loop to validate data entries Working with prefix and postfix increment operators Working with definite loops Working with nested loops Using a do-nothing loop to pause program execution