Transcript
Page 1: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Data Types, Variables,and Declarations

• A data type refers to a kind of value that a language recognizes

– For example, integers, real numbers, characters, Booleans (true/false), etc.

• Primitive data types represent single values and are built into a language; i.e., theyare given

• Java primitive numeric data types:

1. Integral types

(a) byte

(b) int

(c) short

(d) long

2. Real types (NOTE: The text calls these decimal types)

(a) float

(b) double

• What distinguishes the various data types of a given group is the amount of storageallocated for storage

– The greater the amount of storage, the greater the precision and magnitude ofthe value

– Precision refers to the accuracy with which a value can be represented

– Magnitude refers to the largest (and smallest) value that can be represented

• A variable represents a storage location in memory for a value

– Identifiers are used to represent variables

– By convention, user-defined Java variables start with a lower case letter

1

Page 2: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Data Types,Variables, and Declarations (2)

• Variable declarations

– Java is a strongly typed language

∗ This means that a variable can only store values of a single data type

– Semantics: A variable declaration tells the compiler how much storage to set asidefor the variable, and how values in that memory location are to be interpreted

∗ Remember: Everything stored in memory is binary - zeroes and ones

∗ How the binary code is interpreted depends on what the system expects tofind in a location

– Syntax for primitive variable declaration:

∗ For example:

int radius, length, width;

double circleArea;

– Generally, put one declaration per line

2

Page 3: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Integral Types

• Represent whole numbers: 2, 103, -47

• Stored as binary whole numbers

– 21310 represents 3× 100 + 1× 101 + 2× 102 = 3× 1 + 1× 10 + 2× 100 = 213

– Binary only uses digits 0 and 1

– 110101012 represents 1×20+0×21+1×22+0×23+1×24+0×25+1×26+1×27 =1× 1 + 0× 2 + 1× 4 + 0× 8 + 1× 16 + 0× 32 + 1× 64 + 1× 128 = 213

– Java allocates the following storage

type bytes smallest largest

byte 1 -128 127short 2 -32768 32767int 4 -2147483648 2147483647long 8 -9223372036854775808 9223372036854775807

3

Page 4: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Floating Point Types

• Represent numbers with decimal points: 3.0, 66.667, -32.5

• Internally stored using scientific notation

– 125.3310 represented as 1.2533× 102 = 1.2533× 100

– 0.0041710 represented as 4.17× 10−3 = 4.17× .001

– Reals are known as floating point types because125.3310 = 125.33× 100 = 12.533× 101 = 1.2533× 102 = .12533× 103 = ...

– Java allocates the following storage

type bytes smallest largest

float 4 −3.40282347× 1038 3.40282347× 1038

double 8 −1.797693134862× 10308 1.797693134862× 10308

– Note that while integer values represent exact whole numbers, floating point typesare often approximations to the actual value

∗ While their format allows very large numbers to be represented, it also de-creases the precision of their representation

4

Page 5: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Assignment and NumericExpressions

• Assignment is the most basic instruction

• Syntax:

• For example:

x = 10;

• Left side often referred to as the lvalue of the assignmentRight side often referred to as the rvalue of the assignment

• Semantics:The expression is evaluated and the value is stored in the variable’s storage location

5

Page 6: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Assignment andNumeric Expressions (2)

• Numeric expressions can take a number of forms:

1. Literal

– Literal is an actual value

– Integer syntax:

∗ Note:

· If the first digit is a zero, the integer will be interpreted as an octal integer(base 8)

· If the first digit is an 0x, the integer will be interpreted as a hexadecimalinteger (base 16)

∗ An optional plus or minus may precede the value

– Simple float syntax:

– A floating point literal may also be expressed in scientific notation:

– NOTE: As of Java 7, numeric literals may include underscores for readability(not indicated on the above)E.g., 32 817 423

6

Page 7: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: NumericAssignment (3)

– Suffix

∗ What data type does 3.41457 represent?

· By default, floating point literals are interpreted as type double

· By default, integral literals are interpreted as type int

· To indicate a specific type, Java allows a suffix to be appended to a literal

Suffix Meaning

f floatFd doubleDl longL

· For example: 123L, 13.7F

2. Variable

– The assignment copies the value of the variable on the right into the memoryassociated with the variable on the left

7

Page 8: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: NumericAssignment (4)

3. Named (symbolic) constant

– Value that cannot be changed during program execution

– Represented by an identifier, just like a variable

– MUST be initialized at declaration

– Syntax:

– Convention: use all caps for identifier

– For example:

final double COMMISSION = 0.10;

4. Value-returning method calls

– A method (also called functions or subprograms in other languages) are likemini programs that perform a task

∗ For right now, we will only be concerned with value-returning methods -ones that generate a value

∗ Also, we are only concerned with methods that are supplied by Java

· Later on we’ll discuss how to write your own methods

∗ To use a method, you call the method

∗ Call syntax:

∗– The value produced by such a method will ’take the place’ of the call

– java.lang.Math provides a number of useful class methods for performing stan-dard math functions

8

Page 9: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: NumericAssignment (5)

– The table below lists a number of useful Math methods grouped by function-ality;

∗ If arguments are labeled as numeric, they could be int, long, float, or double(all the same type for a given version)

∗ All calls are preceded by Math.

Method** Function

numeric abs(numeric x) absolute value of x

numeric max(numeric x, numeric y) larger of x and ynumeric min(numeric x, numeric y) smaller of x and y

double ceil(double x) smallest whole number ≥ x

double floor(double x) largest whole number ≤ xint round(float x) x rounded to the nearest whole numberlong round(double x) ”

double sin(double x) sine of xdouble cos(double x) cosine of xdouble tan(double x) tangent of xdouble toDegrees(double x) x converted to degreesdouble toRadians(double x) x converted to radians

double pow(double x, double y) xy

double sqrt(double x)√x

double cbrt(double x) 3√x

double random() 0.0 ≤ value < 1.0

** NOTE: trig functions are based on radians

(And constants:

∗ Math.E

∗ Math.PI)

– This package does not need to be imported to be used

– For example:

int x, y, larger;

x = 25;

y = 13;

larger = Math.max(x, y);

9

Page 10: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: NumericAssignment (6)

5. Math.random() needs some explanation

– As indicated, it returns a value between 0.0 and 1.0, but will never be exactlyone

– To generate an integer between m and n,

(a) Call Math.random()

(b) Multiply the result by the number of possible values between m and n

(c) Add m to the result

– For example, to generate a value between one and six (e.g., to simulate a dieroll)

double result;

result = Math.random();

result = 6 * result;

result = 1 + result;

– The general formula is result = m + (m− n + 1) ∗Math.random()

6. Arithmetic expressions

– These involve a calculation involving arithmetic operators

– Unary operators (1 operand):

(a) +

(b) -

– Binary operators (2 operands):

(a) +

(b) -

(c) * (multiplication)

(d) / (division)

(e) % (remainder)

10

Page 11: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: NumericAssignment (7)

7. Compound expressions

– Involve more than one operator

– Evaluation determined by associativity and precedence

– Associativity

∗ Pertains to the direction a given operator evaluates

∗ Can be left or right

– Precedence

∗ Pertains to order in which different operators are evaluated

11

Page 12: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: NumericAssignment (8)

– Associativity and precedence chart

Operator Type Precedence Operators Associativity

Subexpression 16 ()

Postfix increment 15 ++ Land decrement −−Prefix increment 14 ++ Rand decrement −−Unary 14 ! R

+-

Type cast 13 (type) R

Multiplicative 12 * L/%

Additive 11 + L-

+ (string catenation)

Relational 9 < L>

≤≥

Equality 8 == L!=

Boolean AND 4 && L

Boolean OR 3 || L

conditional 2 ?: R

Assignment 1 = R+= (etc)

Operator types listed from highest to lowest precedence.L indicates left-to-right; R indicates right-to-left.

12

Page 13: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: NumericAssignment (9)

8. Increment and decrement operators

– Operators:

(a) ++

(b) −−– There are actually 4 of them

∗ 2 are postfix:

(a) operand + +

(b) operand−−∗ 2 are prefix:

(a) + + operand

(b) −− operand

– Postfix semantics:

(a) operand = operand± 1

(b) return value of operand

– Prefix semantics:

(a) return value of operand

(b) operand = operand± 1

9. ”Special” assignment operators

– These are shortcuts:

(a) +=

(b) -=

(c) *=

(d) /=

(e) %=

– They all work in the same way

∗ Each combines an arithmetic operation with assignment

∗ Semantics of variable op = value:variable = variable op value

13

Page 14: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Mixed-Mode Expressionsand Data Conversions

• Operator overloading

– Expression 5 + 2 uses integer addition

– Expression 7.35 + 15.333 uses floating point addition

– There are actually several versions of the ’+’ operatorThis is called operator overloading

– How does Java handle 23.98 + 10?

• Mixed-mode expressions involve 2 different data types

• In order to perform the operation, the arguments must be made compatible so Javaknows which version of ’+’ to use

• Such changes in type are called type conversions

• Java provides 2 approaches: implicit and explicit

• Implicit

– Java performs the conversion automatically

– Argument of lesser precision is converted to the type of the argument with greaterprecision

– Unary operator algorithm:

1. If type byte or short, ⇒ int

2. Else, do nothing

– Binary operator algorithm:

1. If either type is double, other ⇒ double

2. Else if either type is float, other ⇒ float

3. Else if either type is long, other ⇒ long

4. Else, both ⇒ int

– These called widening conversions, as no information is lost

14

Page 15: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Mixed-ModeExpressions and Data Conversions (2)

– Assignment conversion

∗ Refers to situation when lvalue and rvalue of assignment statement are ofdifferent types

∗ Algorithm:

1. If lvalue of equal or greater precision, convert rvalue to data type of lvalue

2. Else, generate type-mismatch error

∗ The following chart lists numeric data types from greatest to least precision

Type Precision

double highestfloatlongintcharshortbyte

∗ Thus, Java will promote a type lower in the chart to one higher

∗ Java will NOT implicitly perform a narrowing conversion (demotion);i.e., one in which a type higher in the chart is converted to a type lower

· Dangerous: will lose precision, fractions, or may cause run-time error

∗ The following is legal

int x = 25;

float y;

y = x;

but this is not

int x;

float y = 25.0;

x = y;

15

Page 16: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Mixed-ModeExpressions and Data Conversions (3)

• Explicit (type casting)

– Programmer’s code forces the conversion

– Achieved using a typecast operator

∗ Syntax:

∗ Semantics: Evaluate expression and convert result to type

∗ May be either widening or narrowing conversion

∗ Note that narrowing casts may lose precision

int x;

float y = 25.643;

x = (int) y; //x stores integer 25

∗ Java allows explicit narrowing conversions because it demonstrates that theprogrammer intends for this type of conversion to take place

16

Page 17: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Assignment Cautions

• Assignment is an instruction, not an equality as in algebrax = x + 1 is valid assignment

• Operators are not assumedx = 5(y + 10) is not valid

• Be careful of integer divisionint x, yfloat zx = 10y = 4z = x/yValue of z is ???

17

Page 18: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Initialization

• Initialization assigns an initial value to a variable when it is declared

• Syntax:

• For example:

int x, y = 10, z, w = -2;

18

Page 19: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Characters - Intro

• The java data type for characters is charE.g.,

char c;

• A char literal is a single character enclosed within single quotesE.g., ’a’, ’7’, ’ !’

• Special characters are represented by escape sequences

– An escape sequence is a sequence of characters indicated by a backslash (\)– Commonly used escape sequences:

Character escape sequence

single quote \’double quote \”backslash \\alert (bell) \abackspace \bformfeed \fnewline \nreturn \rtab \tvertical tab \v

– An escape sequence is considered a single character by the compiler

19

Page 20: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Characters -Representation

• Characters are represented internally as integers

– ASCII (American Standard Code for Information Interchange)

∗ Standard encoding using 8 bits

– Unicode

∗ What ASCII evolved into, using 16 bits

∗ More bits allows representation of a greater number of characters (i.e., inter-national character sets)

– Both codes can be found online (see resources page)

– Given this, you can represent characters as types char or int

For example:

char c;

int i;

c = ’A’;

i = (int) c; //or just i = c;

i += 1;

c = (char) i; //c now stores char ’B’

//must use cast for this assignment

20

Page 21: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: Random Numbers -Revisited

• Earlier, we looked at Math.random()

– This allowed us to generate doubles in the range 0.0 ≤ x < 1.0

– What if we want an integer?

– The example used in the earlier discussion for a die roll produced a value 1.0 ≤result ≤ 6.0

– To remedy this we would need to cast the final result to an int

• Another issue with Math.random() is

– Suppose we have a program that uses random numbers, but our program has abug in it

– How can we track down the problem if every time we run the program, it usesdifferent input values?

– We can never repeat a situation

• The solution is class java.util.Random

– To use this class, we need to import it:

import java.util.Random;

– We then need to create an instance of the class:

Random rand;

rand = new Random();

(Or you can combine the above into a single line:

Random rand = new Random();

)

21

Page 22: Java Primitive Numeric Types, Assignment, and Expressions ...djmoon/cs1/cs1-notes/numeric-dts.pdf · To indicate a speci c type, Java allows a su x to be appended to a literal Su

Java Primitive Numeric Types, Assignment, and Expressions: RandomNumbers - Revisited (2)

– Once we have an instance of class Random, we can use its methods to generaterandom values

– Methods:

Method Value returned

nextFloat() 0.0 ≤ value < 1.0nextDouble() 0.0 ≤ value < 1.0nextInt() 0 ≤ value < max int representednextInt(int n) 0 ≤ value < nsetSeed(long s) Set seed value to s

∗ nextFloat() and nextDouble() do what Math.random() does

∗ nextInt() with no parameter returns a value that can be as large as the largestint that Java can represent

∗ setSeed() is used for replicating a set of random values each time yoou runyour program

· When you create a new instance of Random, it is automatically initiallizedusing the current system time

· This is how you always get a different series of random values each timeyou run your program

· To always initialize the generator with the same value, call setSeed() withthe same seed every time

· Generally, you would call setSeed() right after you create your instance

∗ There is a second constructor for Random: Random(long seed)

· This constructor both creates a new instance and sets its seed value all atone time

∗ So we might use Random something like this:

int x;

double f, g;

Random r = new Random();

x = r.nextInt(6) + 1; //1 <= x <= 6

f = r.nextDouble(); //0.0 <= f < 1.0

g = r.nextDouble(); //0.0 <= f < 1.0

22


Top Related