1 / 78

Chapter 3 - PowerPoint PPT Presentation

Chapter 3. Numerical Data. Objectives. Understand n umerical data type . Write arithmetic expressions in Java. Evaluate arithmetic expressions using the precedence rules. Describe how the memory allocation works for objects and primitive data values. Learn to use standard classes

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

PowerPoint Slideshow about ' Chapter 3' - nishi

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Chapter 3

Numerical Data

• Understand numerical data type.

• Write arithmetic expressions in Java.

• Evaluate arithmetic expressions using the precedence rules.

• Describe how the memory allocation works for objects and primitive data values.

• Learn to use standard classes

• Math – for math expressions

• GregorianCalendar - for manipulating date information such as year, month, and day.

• DecimalFormat - for formating numerical data

• Integer, …,Long - Convert input string values to numerical data

• System.in, System.out - Perform input and output.

Data Types supported by Java:

• primitive types

• numeric types

• integer type: byte, char, short, int, long

• floating-point type: float, double

• boolean

• reference types

• class

• interface

• array

Notes:

• Instances of primitive types are values but not objects; only instances of reference types are objects.

• name representation range

• byte8-bit 2's complement -128~127

• short16-bit 2's complement -32768~32767

• int32-bit 2's complement -2147483648 to

2147483647

• long64-bit 2's complement -263~263-1

(19 digits)

• char16-bit Unicode '\u0000' to '\uffff‘

• or 0 ~ 65535

• name representation range

• float 32-bit, IEEE 754 1.40239846e-45 ~

3.40282347e+38

• double 64-bit, IEEE 754 4.94065645841246544e-324

• ~ 1.79769313486231570e+308

Representation:

• non-zero value: v = S x M x 2^E

• For float: S is +/- 1, M is a positive integer less than 2^24, and E is an integer in the inclusive range -149 to 104.

• For double: S is +/- 1, M is a positive integer less than 2^53, and E is an integer in the inclusive range -1045 to 1000.

• special values defined in IEEE 754:

• +0, -0, +infinity, -Infinity, NaN.

• note: 0/0.0 => NaN,

• 1/0.0 => Infinity instead of overflow or divide by zero.

• 0x7f800000 => positive infinity.

• 0xff800000 => negative infinity.

• 0x7f800001 ~ 0x7fffffff or 0xff800001~0xffffffff => NaN.

• Java use 0x7fc00000 as the canonical value of NaN.

• Distinct values of NaN are only accessible by use of the Float.floatToRawIntBits(float)

• In all other cases, let s, e, and m be three values that can be computed from the argument:

• int s = ((bits >> 31) == 0) ? 1 : -1;

• int e = ((bits >> 23) & 0xff); // s bit is ignored by mask of 0xff

• int m = (e == 0) ? (bits & 0x7fffff) << 1 : (bits & 0x7fffff) | 0x800000;

• the floating-point result is s · m · 2 e-150.

s

e

(man’tissa)

b31

b15

b30

b14

b29

b13

b12

b28

b11

b27

b10

b26

b9

b25

b24

b8

b23

b7

b22

b6

b21

b5

b4

b20

b3

b19

b2

b18

b17

b1

b0

b16

m

IEEE 754 float-point single precision layout

• value is determined as follows:

• 0. s = (b31 == 0 ? 1: -1);

• 255> e > 0 => value = s x (1.m)2 x 2 e –127 = s x (1m) x 2 e - 150

• e = 0 => value = s x (b22.b21---b00)2 x 2 e-127 = s x (m 0)2 x 2 e - 127-23

• e=255 && m == 0 => value = ( s == 0 ? Infinity : -Infinity)

• e = 255 && m != 0 => value = NaN; canonical NaN = 0181022

• A literal is the source code representation of a constant value of a primitive type, or some specific object (of the type String, null, array or Class).

• Literal:

• IntegerLiteral : 123, 123l, 12400L

• FloatingPointLiteral: 123.4, 1.2e12, 12f, 12.3d

• BooleanLiteral: true, false

• CharacterLiteral: ‘a’, ‘\u123’, ‘\377’,…

• StringLiteral: “a book”,“tab\t and newline \n”

• NullLiteral: null

• ArrayLiteral: new int[]{1,2,3}.

• ClassLiteral: String.class

• An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), or octal (base 8):

• It is of type int unless suffixed with ‘L’ or ‘l’.

• IntegerLiteral:

• DecimalIntegerLiteral

• HexIntegerLiteral

• OctalIntegerLiteral

• DecimalIntegerLiteral:

• 0

• [1-9] [0-9]* [lL]? Ex: 123, 123l, 1243L

• HexIntegerLiteral:

• 0 [xX] [0-9a-fA-F]+ [lL]? Ex: 0X1aB4, 0x23L, 0xffff

• OctalIntegerLiteral:

• 0 [0-7]+[lL]? Ex: 000, 0377, 01177L

• FloatingPointLiteral:

• Digits . Digits? Exp? FloatType?

• . Digits Exp? FloatType?

• Digits Exp FloatType?

• Digits Exp? FloatType

• Exp: [eE] [+ -]? Digits

• FloatType: [fFdD]

• Digits: [0-9]+

• A FP literal is of type double unless it is suffixed with ‘F’ or ‘f’.

• Ex:

• 12.34e12d, 1.23E-2, <= cf: 12.34e12d

• .11, .12E12f,

• 12e-2, 1e12D <= cf: 0x1e12L

• 33e2f, 33D

Space in the literal

not allowed

• The boolean type has two values, represented by the literals true and false, formed from ASCII letters.

• A boolean literal is always of type boolean.

• BooleanLiteral:

• true

• false

• expressed as a character or an escape sequence, enclosed in ASCII single quotes.

• A character literal is always of type char.

• CharacterLiteral:

• ' SingleCharacter '

• ' EscapeSequence '

• SingleCharacter:

• Any Character but not any of ' \ CR LF

• ‘c‘ => compile-time error

• It is a compile-time error for a line terminator to appear after the opening ' and before the closing '.

• The following are examples of char literals:

• 'a' '%' '\t' '\\' '\''

• '\u03a9' '\uFFFF' '\177' '’ ‘‘

• Which of the following are correct literals:

• ‘\u000a’, // this is LF

• ‘\n’, // this is escape seq of LF

• ‘\u000D’, // this is CR

• ‘\r’

• Note: Characters written in unicode escape form ( \uxxxx ) will be converted to real chars before normal lexical analysis.

• consists of zero or more characters enclosed in double quotes.

• Each character may be represented by an escape sequence.

• always of type String

• StringLiteral:

• " StringCharactersopt “ // empty string “” allowed

• StringCharacters:

• StringCharacter

• StringCharacters StringCharacter

• StringCharacter:

• Any Character but not any of " \ CR LF

• EscapeSequence

• “a b c \u000d sd \u000a” // error!!

• “This is a two-line

string“ //err! string can not across multilines

• “ a b c \r sd \n” // OK

• "" // the empty string

• "\"" // a string containing " alone

• "This is a string" // a string containing 16 chars

• "This is a " + // actually a string-valued

• “two-line strings” // constant expression, formed

// from two string literals

cf: we use octal literal 036 to represent int number 0x1e(= 30) but use ‘\36’ or ‘\036’ to represent char ‘\u001e’

Escape Sequences for Character and String Literals

• Escape sequences allow for the representation of

• some nongraphic characters, (TAB, LF, CR, …)

• the single quote(‘), double quote(“), and backslash(\) characters

in character and string literals.

• EscapeSequence:

• \b /* \u0008: backspace BS */

• \t /* \u0009: horizontal tab HT */

• \n /* \u000a: linefeed LF */

• \f /* \u000c: form feed FF */

• \r /* \u000d: carriage return CR */

• \" /* \u0022: double quote " */

• \' /* \u0027: single quote ' */

• \\ /* \u005c: backslash \ */

• OctalEscape/* \u0000 to \u00ff: from octal value */

• OctalEscape:// can represent only the first 256 chars

• \ OctalDigit// [0-7] : \0 ~ \7

• \ OctalDigit OctalDigit// [0-7][0-7]: \00 ~\77

• \ ZeroToThree OctalDigit OctalDigit// [0-3][0-7][0-7]

• // \000~\377

• The null type has one value, the null reference, represented by the literal null, which is formed from ASCII characters.

• A null literal is always of the null type.

• NullLiteral:

• null

Notes:Unlike C, in java

• true ≠ 1

• false ≠ 0 ≠ null

• The following 37 tokens are the operators, formed from ASCII characters:

• > < == <= >= !=// relational

• + - * / %// arithmetic

• ! && ||// conditional logical operations

• ?:// ternary conditional operation

• ++ --// PRE/POST INCR/DECR

• & | ^ ~ << >> >>>// Bit and boolean operation

• = += -= *= /= &= |=// Assignments

^= %= <<= >>= >>>=

• x *= y + zmeans x = x * (y + z) and the like.

• In Java, to add two numbers x and y, we write

x + y

• Before actual addition of the two numbers, we must declare their data type.

• If x and y are integer (variables), we write

int x, y;

or

int x;int y;

• When the declaration is made, memory space is allocated to store the values of x and y.

• x and y are called variables.

• A variable has three properties:

• A memory location to store the value,

• The type of data stored in the memory location, and

• The name used to refer to the memory location.

• Sample variable declarations:

int x;int v, w, y;

Numerical variables

• There are six numerical data types: byte, short, int, long, float, and double.

• Sample variable declarations:

int i, j, k;// default = 0 or no value

float numberOne, numberTwo;

long bigInteger;

double bigNumber;

• At the time a variable is declared, it also can be initialized.

• int count = 10, height = 34;

The six data types differ in the precision of values they can store in memory.

• We assign a value to a variable using an assignment statements.

• The syntax is

<variable> = <expression> ;

• Examples:

sum = firstNumber + secondNumber;avg = (one + two + three) / 3.0;

• The following table summarizes the arithmetic operators available in Java.

• division:

• 10 / 3 = 3; -10 / 3 = -3

• 10 / -3 = -3 ; -10 /-3 = 3.

• 10 / 0  Exception 10.0 /0  +Infinite

This is an integer division where the fractional part is truncated.

• How does the expression

x + 3 * y

• We determine the order of evaluation by following the precedence rules.

• A higher precedence operator is evaluated before the lower one.

• the same precedence,

• evaluated left to right (left association) for most operators.

• Ex: 5 - 3 -2 means (5 – 3 ) – 2 instead of 5 – ( 3 – 2).

• right to left (right association)

• Ex: 2 ^ 3 ^ 4 means 2^(3^4)

• Used with integer types

• Returns the remainder of the division of b by a

• For example:

int a = 57; b = 16 ;

c = a%b;

• c now has the value 9, the remainder of 57 divided by 16

• Integer / and % in java not the same as in normal arithmetic:

• rules:

• x = y (x/y) + x % y --- always hold.

• x / y = sign(x/y) | x/ y| = x/y with fraction part removed;

• x%y = x – (x/y) *y = sign(x) (|x|%|y|) always holds

• ex: -10 / -3 = 3; -10 % -3 = -1; // -10 / 3 = ? ; -10 % 3 = ?

• ex: 10 / -3 = -3; 10 % -3 = 1;

• If x is a float and y is an int, what will be the data type of the following expression?

x * y

• The above expression is called a mixed expression.

• promotionrules for mixed expressions:

• In a mixed expression, operand of low precision is automatically converted (casted; widen) into the high precision type before evaluation.

• ex: 3.2 + 4 promotes to

• 3.2 + (double) 4 or 3.2 + 4d

• Java allows conversions between values of various numeric types.

• Except for boolean, values of all primitive types can be converted.

• Basic types of conversions:

• Widening conversion:

• int  long; float double; char  int; …

• always safe except for int float, double; longdouble.

• automated performed by Java

• Narrowing conversion: long  int; double  float;…

• must use the cast () operators; (except for int literal, which can be downcasted to the required integral type automatically if it is inside the range of the left variable ).

• not always safe.

• Ex:

• int i =13; byte b = i; // compiler error

• short s = 134 ; // ok!! though 134 is int type, it is a literal.

• Ex:

• int i = 13;

• byte b = (byte) i; // force i to be converted to a byte

• i = (int) 13.456 // force double literal 13.456 to int 13

• i = (int) –12.6 // i == -12

• i = Integer.MAX_VALUE // i = 2147483647

• float j = i // need not cast, but data loss; j = 2.14748365E9

• j == i ? true : false // will return true! why ?

• Math.round(), Math.floor(), Math.ceil() perform other types of conversion.

• short v.s. char:

• short s = (short) 0xffff; // s = -1; 2’s comlement

• char c = ‘\uffff’; // char behaves like unsigned short

• int i1 = s; // i1 = -1

• int i2 = c; // i2 = 65535

• precision order of numeric types

• byte < (short ; char) < int < long < float < double

• short and char are incomparable.

• i.e.,

• short s; char c;

• s = c // error! must use (short) c.

• widening conversion

• low precision  high precision

• automatcally done by javac; cast () not needed

• narrowing conversion

• high precision  low precision

• must use cast ()

Type case x to float and then divide it by 3.

Type cast the result of the expression x / y * 3.0 to int.

Explicit Type Casting

• format:

• ( <data type> ) <expression>

• Example

(float) x / 3

(int) (x / y * 3.0)

A higher precision value cannot be assigned to a lower precision variable.

Implicit Type Casting

• Consider the following expression:

double x = 3 + 5;

• The result of 3 + 5 is of type int. However, since the variable x is double, the value 8 (type int) is promoted to 8.0 (type double) before being assigned to x.

• Notice that it is a promotion. Demotion is not allowed.

int x = 3.5;

The reserved word precision variable.final is used to declare constants.

These are constants, also called named constant.

These are called literal constant.

Constants

• We can change the value of a variable. If we want the value to remain the same, we use a constant.

final double PI = 3.14159;final int MONTH_IN_YEAR = 12;final short FARADAY_CONSTANT = 23060;

Primitive vs. Reference precision variable.

• Numerical data are called primitive data types.

• Objects are called reference data types, because the contents are addresses that refer to memory locations where the objects are actually stored.

int firstNumber, secondNumber; precision variable.

A. Variables are allocated in memory.

firstNumber = 234;

secondNumber = 87;

firstNumber

234

secondNumber

A

87

B

B. Values are assigned to variables.

Primitive Data Declaration and Assignments

State of Memory

Code

number precision variable.

237

35

A. The variable is allocated in memory.

A

B

B. The value 237 is assigned to number.

C

number = 35;

C. The value 35 overwrites the previous value 237.

Assigning Numerical Data

int number;

number = 237;

State of Memory

Code

customer precision variable.

Customer

Customer

A

B

A. The variable is allocated in memory.

B. The reference to the new object is assigned to customer.

C

C. The reference to another object overwrites the reference in customer.

Assigning Objects

Customer customer;

customer = new Customer( );

customer = new Customer( );

State of Memory

Code

clemens precision variable.

twain

Customer

A

B

A. Variables are allocated in memory.

B. The reference to the new object is assigned to clemens.

C

C. The reference in clemens is assigned to customer.

Having Two References to a Single Object

Customer clemens, twain,

clemens = new Customer( );

twain = clemens;

State of Memory

Code

int precision variable. age;

age = JOptionPane.showInputDialog(

Type Mismatch

• Suppose we want to input an age. Will this work?

• No. String value cannot be assigned directly to an int variable.

int precision variable. age;

String inputStr;

inputStr = JOptionPane.showInputDialog(

age = Integer.parseInt(inputStr);

Type Conversion

• Wrapper classesare used to perform necessary type conversions, such as converting a String object to a numerical value.

Other Conversion Methods precision variable.

Sample Code Fragment precision variable.

//code fragment to input radius and output

//area and circumference

//compute area and circumference

circumference = 2.0 * PI * radius;

JOptionPane.showMessageDialog(null,

"Area: " + area + "\n" +

"Circumference: " + circumference);

• The plus operator + can mean two different operations, depending on the context.

• <val1> + <val2> is an addition if both are numbers. If either one of them is a String, the it is a concatenation.

• Evaluation goes from left to right.

output = “test” + 1 + 2;

output = 1 + 2 + “test”;

double num = 123.45789345; precision variable.

DecimalFormat df = new DecimalFormat(“0.000”);

//three decimal places

123.45789345

123.458

System.out.print(num);

System.out.print(df.format(num));

The DecimalFormat Class

• Use a DecimalFormat object to format the numerical output.

3.5 Standard Output precision variable.

• The showMessageDialog method is intended for displaying short one-line messages, not for a general-purpose output mechanism.

• UsingSystem.out, we can output multiple lines of text to the standard output window.

Standard Output Window precision variable.

• A sample standard output window for displaying multiple lines of text.

• The exact style of standard output window depends on the Java tool you use.

The print Method precision variable.

• We use the print method to output a value to the standard output window.

• The print method will continue printing from the end of the currently displayed output.

• Example

System.out.print( “Hello, Dr. Caffeine.” );

• int precision variable. x = 123, y = x + x;

• System.out.println( "Hello, Dr. Caffeine.“ );

• System.out.print( " x = “ );

• System.out.println( x );

• System.out.print( " x + x = “ );

• System.out.println( y );

• System.out.println( " THE END“ );

The println Method

• We use println instead of print to skip a line.

Static imports precision variable.

• static import

• importstaticjava.lang.System.out ;

• // import static java.lang.System.*;

• //  All static fields & methods in System are // imported!!

• int x = 123, y = x + x;

• System.out.println( "Hello, Dr. Caffeine.“ );

• out.print( " x = “ );

• out.println( x );

• out.print( " x + x = “ );

• out.println( y );

• out.println( " THE END“ );

Standard Input precision variable.

• The technique of using System.in to input data is called standard input.

• We can only input a single byte using System.in directly.

• int in = System.in.read() ; // read a byte from System.in

• To input primitive data values, we use the Scanner class (from Java 5.0).

• Scanner scanner;

• scanner = new Scanner(System.in);

• int num = scanner.nextInt();

Common Scanner Methods: precision variable.

Method Example

nextByte( ) byte b = scanner.nextByte( );

nextDouble( ) double d = scanner.nextDouble( );

nextFloat( ) float f = scanner.nextFloat( );

nextInt( ) int i = scanner.nextInt( );

nextLong( ) long l = scanner.nextLong( );

nextShort( ) short s = scanner.nextShort( );

next() String str = scanner.next();

double precision variable. num, x, y;

x = …;

y = …;

num = Math.sqrt(Math.max(x,y)+12.4);

The Math class

• The Math class in the java.lang package contains class methods for commonly used mathematical functions.

Some Math Class Methods precision variable.

• Table 3.8 page 113 in the textbook contains a list of class methods defined in the Math class.

/

Computing the Height of a Pole

Import static precision variable.

import static java.lang.Math.*;

// then all “Math” name can be skipped!

GregorianCalendar today, independenceDay; precision variable.

today = new GregorianCalendar();

independenceDay

= new GregorianCalendar(1776, 6, 4);

//month 6 means July; 0 means January

The GregorianCalendar Class

• Use a GregorianCalendar object to manipulate calendar information

Retrieving Calendar Information precision variable.

• This table shows the class constants for retrieving different pieces of calendar information from Date.

GregorianCalendar cal = precision variable.new GregorianCalendar();

//Assume today is Nov 9, 2003

System.out.print(“Today is ” +

(cal.get(Calendar.MONTH)+1) + “/” +

cal.get(Calendar.DATE) + “/” +

cal.get(Calendar.YEAR));

Output

Today is 11/9/2003

Sample Calendar Retrieval

Problem Statement precision variable.

• Problem statement:

Write a loan calculator program that computes both monthly and total payments for a given loan amount, annual interest rate, and loan period.

Overall Plan precision variable.

• Get three input values: loanAmount, interestRate, and loanPeriod.

• Compute the monthly and total payments.

• Output the results.

Find the monthly payment precision variable.

• L: loan amount; R: monthly rate;

• N :number of payments.

• Suppose we must pay X per month.

• Let yn be the amount of debt at month n.

• Then

• y0 = L ; y1 = y0(1+R) – X = L(1+R) - X

• y2 = y1(1+R) – X = [L(1+R) – X] (1+R) – X

• = L(1+R)2 –X( 1 + (1+R) )

• yN = yN-1 (1+R) – X = L(1+R)N – X[ 1 + (1+R) + … + (1+R)N-1 ]= 0

• Hence :

• L(1+R)N = X [(1+R) N – 1 ] / [ (1+R) - 1 ]

• X = LR / ( 1 – [1/(1+R)]N ).

Required Classes precision variable.

Development Steps precision variable.

We will develop this program in four steps:

• Add code to output the results.

• Add code to compute the monthly and total payments.

• Update or modify code and tie up any loose ends.

Step 1 Design precision variable.

• Call the showInputDialog method to accept three input values:

• loan amount,

• annual interest rate,

• loan period.

• Data types are

Step 1 Code precision variable.

• Directory: Chapter3/Step1

• Source File: Ch3LoanCalculator.java

Program source file is too big to list here. From now on, we ask

you to view the source files using your Java IDE.

Step 1 Test precision variable.

• In the testing phase, we run the program multiple times and verify that

• we can enter three input values

• we see the entered values echo-printed correctly on the standard output window

Step 2 Design precision variable.

• We will consider the display format for out.

• Two possibilities are (among many others)

Step 2 Code precision variable.

• Directory: Chapter3/Step2

• Source File: Ch3LoanCalculator.java

Step 2 Test precision variable.

• We run the program numerous times with different types of input values and check the output display format.

• Adjust the formatting as appropriate

Step 3 Design precision variable.

• The formula to compute the geometric progression is the one we can use to compute the monthly payment.

• The formula requires the loan period in months and interest rate as monthly interest rate.

• So we must convert the annual interest rate (input value) to a monthly interest rate (per the formula), and the loan period to the number of monthly payments.

• (1 + month_rate )12 = 1+ year_rate

-> month_rate = log(1+year_rate) /log 12 -1.

Step 3 Code precision variable.

• Directory: Chapter3/Step3

• Source File: Ch3LoanCalculator.java

Step 3 Test precision variable.

• We run the program numerous times with different types of input values and check the results.

Step 4: Finalize precision variable.

• We will add a program description

• We will format the monthly and total payments to two decimal places using DecimalFormat.

• DecimalFormat df = new DecimalFormat( “0.00” );

Directory: Chapter3/Step4

Source File: Ch3LoanCalculator.java

Programming Assignment 1 precision variable.

• Chapter 3, Exercise 24 (p147)

• Develop an application that reads a purchase price and an amount tendered and then displays the change in dollars, quarteres, dimes, nickles, and pennies.

• Two input values areentered in cents, for example, 3480 for \$34.80 and 70 for \$0.70.

• Use any appropriate techniques for input and output.

• Name your class : HW1

• Remember to give your name & register number in the program.

• due : 4/13.

The format of the output precision variable.

Purchase Price: \$ 34.80

Amount Tendered: \$ 40.00

Your change is : \$ 5.20

5 one-dollar bill(s)

0 quarter(s)

2 dime(s)

0 nuckel(s)

0 penn(y/ies)