the interdisciplinary center, herzelia lecture 5, introduction to cs - information technologies...

68
The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies Slide #1 More Programming Constructs -- Introduction In this lecture: internal data representation conversions between one data type and another more operators more selection statements more repetition statements array declaration and use arrays of objects parameters and arrays multidimensional arrays

Upload: elfrieda-terry

Post on 02-Jan-2016

217 views

Category:

Documents


2 download

TRANSCRIPT

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #1

More Programming Constructs -- Introduction

• In this lecture:– internal data representation

– conversions between one data type and another

– more operators

– more selection statements

– more repetition statements

– array declaration and use

– arrays of objects

– parameters and arrays

– multidimensional arrays

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #2

Internal Data Representation

• We discussed earlier that every piece of information stored on a computer is represented as binary values

• What is represented by the following binary string?

01100001001010• You can't tell just from the bit string itself.

• We take specific binary values and apply an interpretation to them

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #3

Representing Integers

• There are four types of integers in Java, each providing a different bits to store the value

• Each has a sign bit. If it is 1, the number is negative; if it is 0, the number is positive

byte

short

int

long

s 7 bits

s 15 bits

s 31 bits

s 63 bits

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #4

Two's Complement

• Integers are stored in signed two's complement format

• A positive value is a straightforward binary number

• A negative value is represented by inverting all of the bits of the corresponding positive value, then adding 1

• To "decode" a negative value, invert all of the bits and add 1

• Using two's complement makes internal arithmetic processing easier

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #5

Two's Complement

• The number 25 is represented in 8 bits (byte) as

00011001• To represent -25, first invert all of the bits

11100110

then add 1

11100111• Note that the sign bit reversed, indicating the number is

negative

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #6

Overflow and Underflow

• Storing numeric values in a fixed storage size can lead to overflow and underflow problems

• Overflow occurs when a number grows too large to fit in its allocated space

• Underflow occurs when a number shrinks too small to fit in its allocated space

• Example:int num = Integer.MAX_VALUE; // 2,147,483,647

num = num + 1; // -2,147,483,648

// which is Integer.MIN_VALUE

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #7

Representing Floating Point Values

• A decimal (base 10) floating point value can be defined by the following equation

sign * mantissa * 10 exponent

• where– sign is either 1 or -1

– mantissa is a positive value that represents the significant digits of the number

– exponent is a value that indicates how the decimal point is shifted relative to the mantissa

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #8

Representing Floating Point Values

• For example, the number -843.977 can be represented by

-1 * 843977 * 10 -3

• Floating point numbers can be represented in binary the same way, except that the mantissa is a binary number and the base is 2 instead of 10

sign * mantissa * 2 exponent

• Floating point values are stored by storing each of these components in the space allotted

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #9

Representing Characters

• As described earlier, characters are represented according to the Unicode Character Set

• The character set matches a unique number to each character to be represented

• Storing the character is therefore as simple as storing the binary version of the number that represents it

• For example, the character 'z' has the Unicode value 122, which is represented in 16 bits as

0000000001111010

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #10

Representing Characters

• Because they are stored as numbers, Java lets you perform some arithmetic processing on characters

• For example, because 'A' is stored as Unicode value 65, the statement

char ch = 'A' + 5;

will store the character 'F' in ch (Unicode value 70)

• This relationship is occasionally helpful

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #11

Conversions

• Each data value and variable is associated with a particular data type

• It is sometimes necessary to convert a value of one data type to another

• Not all conversions are possible. For example, boolean values cannot be converted to any other type and vice versa

• Even if a conversion is possible, we need to be careful that information is not lost in the process

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #12

Widening Conversions

• Widening conversions are generally safe because they go from a smaller data space to a larger one

• The widening conversions are:

From

byteshortcharintlongfloat

To

short, int, long, float, or doubleint, long, float, or doubleint, long, float, or doublelong, float, or doublefloat or doubledouble

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #13

Narrowing Conversions

• Narrowing conversions are more dangerous because they usually go from a smaller data space to a larger one

• The narrowing conversions are:

From

byteshortcharintlongfloatdouble

To

charbyte or charbyte or shortbyte, short, or charbyte, short, char, or intbyte, short, char, int or longbyte, short, char, int, long, or float

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #14

Performing Conversions

• In Java, conversion between one data type and another can occur three ways

• Assignment conversion - when a value of one type is assigned to a variable of another type

• Arithmetic promotion - occurs automatically when operators modify the types of their operands

• Casting - an operator that forces a value to another type

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #15

Assignment Conversion

• For example, if money is a float variable and dollars is an int variable (storing 82), then

money = dollars;

converts the value 82 to 82.0 when it is stored

• The value in dollars is not actually changed

• Only widening conversions are permitted through assignment

• Assignment conversion can also take place when passing parameters (which is a form of assignment)

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #16

Arithmetic Promotion

• Certain operators require consistent types for their operands

• For example, if sum is a float variable and count is an int variable, then the statement

result = sum / count;

internally converts the value in count to a float then performs the division, producing a floating point result

• The value in count is not changed

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #17

Casting

• A cast is an operator that is specified by a type name in parentheses

• It is placed in front of the value to be converted

• The following example truncates the fractional part of the floating point value in money and stores the integer portion in dollars

dollars = (int) money;• The value in money is not changed

• If a conversion is possible, it can be done through a cast

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #18

Arithmetic Operators

• The Java Virtual Machine can only perform integer, long, float and double operations

• Therefore byte and short operations are performed as integer

• for example:

byte c = 4, d = 5;

byte e = (byte) c + d;

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #19

More Operators

• We've seen several operators of various types: arithmetic, equality, relational

• There are many more in Java to make use of:– increment and decrement operators

– logical operators

– assignement operators

– the conditional operator

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #20

The Increment and Decrement Operators

• The increment operator (++) adds one to its integer or floating point operand

• The decrement operator (--) subtracts one

• The statement

count++;

is essentially equivalent to

count = count + 1;

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #21

The Increment and Decrement Operators

• The increment and decrement operators can be applied in prefix (before the variable) or postfix (after the variable) form

• When used alone in a statement, the prefix and postfix forms are basically equivalent. That is,

count++;

is equivalent to

++count;

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #22

The Increment and Decrement Operators

• When used in a larger expression, the prefix and postfix forms have a different effect

• In both cases the variable is incremented (decremented)

• But the value used in the larger expression depends on the form

Expression

count++++countcount----count

Operation

add 1add 1

subtract 1subtract 1

Value of Expression

old valuenew valueold valuenew value

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #23

The Increment and Decrement Operators

• If count currently contains 45, then

total = count++;

assigns 45 to total and 46 to count

• If count currently contains 45, then

total = ++count;

assigns the value 46 to both total and count

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #24

The Increment and Decrement Operators

• If sum contains 25, then the statement

System.out.println (sum++ + " " + ++sum +

" " + sum + " " + sum--);

prints the following result: 25 27 27 27

and sum contains 26 after the line is complete

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #25

Logical Operators

• There are three logical operators in Java:

• They all take boolean operands and produce boolean results

• Logical NOT is unary (one operand), but logical AND and OR are binary (two operands)

Operator

!&&||

Operation

Logical NOTLogical ANDLogical OR

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #26

Logical NOT

• The logical NOT is also called logical negation or logical complement

• If a is true, !a is false; if a is false, then !a is true

• Logical expressions can be shown using truth tables

a

falsetrue

!a

truefalse

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #27

Logical AND

• The expression a && b is true if both a and b are true, and false otherwise

• Truth tables show all possible combinations of all terms

a

falsefalsetruetrue

b

falsetruefalsetrue

a && b

falsefalsefalsetrue

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #28

Logical OR

• The expression a || b is true if a or b or both are true, and false otherwise

a

falsefalsetruetrue

b

falsetruefalsetrue

a || b

falsetruetruetrue

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #29

Assignment Operators

• Often we perform an operation on a variable, then store the result back into that variable

• Java provides assignment operators that simplify that process

• For example, the statement

num += count;

is equivalent to

num = num + count;

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #30

Assignment Operators

• There are many such assignment operators, always written as op= , such as:

Operator

+=-=*=/=%=

Example

x += yx -= yx *= yx /= yx %= y

Equivalent To

x = x + yx = x - yx = x * yx = x / yx = x % y

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #31

Assignment Operators

• The right hand side of an assignment operator can be a complete expression

• The entire right-hand expression is evaluated first, then combined with the additional operation

• Therefore result /= (total-MIN) % num;

is equivalent to result = result / ((total-MIN) % num);

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #32

The Conditional Operator

• Java has a conditional operator that evaluates a boolean condition that determines which of two expressions is evaluated

• The result of the chosen expression is the result of the entire conditional operator

• Its syntax is: condition ? expression1 : expression2

• If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #33

The Conditional Operator

• It is similar to an if-else statement, except that it is an expression that returns a value

• For example: larger = (num1 > num2) ? num1 : num2;

• If num1 is greater that num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger

• The conditional operator is ternary, meaning it requires three operands

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #34

The Conditional Operator

• Another example:

System.out.println ("Your change is " + count +

(count == 1) ? "Dime" : "Dimes");

• If count equals 1, "Dime" is printed, otherwise "Dimes" is printed

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #35

Another Selection Statement

• The if and the if-else statements are selection statements, allowing us to select which statement to perform next based on some boolean condition

• Another selection construct, called the switch statement, provides another way to choose the next action

• The switch statement evaluates an expression, then attempts to match the result to one of a series of values

• Execution transfers to statement list associated with the first value that matches

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #36

The switch Statement

• The syntax of the switch statement is:

switch (expression) {

case value1:

statement-list1

case value2:

statement-list2

case …

}

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #37

The switch Statement

• The expression must evaluate to an integral value, such as an integer or character

• The break statement is usually used to terminate the statement list of each case, which causes control to jump to the end of the switch statement and continue

• A default case can be added to the end of the list of cases, and will execute if no other case matches

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #38

int acount = 0, ecount = 0, icount = 0, ocount = 0;int ucount = 0, other = 0, index = 0;String quote = "We are the Borg. Resistance is futile.";

while (index < quote.length()) {

switch (quote.charAt (index)) { case 'a': acount++; break; case 'e': ecount++; break; // other cases come here... default: other++; } index++;

}

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #39

More Repetition Constructs

• In addition to while loops, Java has two other constructs used to perform repetition:

• the do statement

• the for statement

• Each loop type has its own unique characteristics

• You must choose which loop type to use in each situation

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #40

The do Statement

• The do statement has the following syntax:

do

statement

while (condition);

• The statement is executed until the condition becomes false

• It is similar to a while statement, except that its termination condition is evaluated after the loop body

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #41

The do Statement

statement

condition

false

true

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #42

The do Statement

• The key difference between a do loop and a while loop is that the body of the do loop will execute at least once

• If the condition of a while loop is false initially, the body of the loop is never executed

• Another way to put this is that a while loop will execute zero or more times and a do loop will execute one or more times

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #43

The for Statement

• The syntax of the for loop is

for (intialization; condition; increment)

statement;

which is equivalent to

initialization;

while (condition) {

statement;

increment;

}

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #44

The for Statement

• Like a while loop, the condition of a for statement is tested prior to executing the loop body

• Therefore, a for loop will execute zero or more times

• It is well suited for executing a specific number of times, known in advance

• Note that the initialization portion is only performed once, but the increment portion is executed after each iteration

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #45

The for Statement

statement

conditionfalse

true

initialization

increment

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #46

The for Statement

• Examples:

for (int count=1; count < 75; count++)

System.out.println (count);

for (int num=5; num <= total; num *= 2) {

sum += num;

System.out.println (sum);

}

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #47

The for Statement

• Each expression in the header of a for loop is optional– If the initialization is left out, no initialization is performed

– If the condition is left out, it is always considered to be true, and therefore makes an infinite loop

– If the increment is left out, no increment operation is performed

• Both semi-colons are always required

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #48

Arrays

• An array is an ordered list of values

• Each value has a numeric index

• An array of size N is indexed from zero to N-1

• The following array of integers has a size of 10 and is indexed from 0 to 9

0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #49

Arrays

• A particular value in an array is referenced using the array name followed by the index in brackets

• For example, the expression

scores[4]

refers to the value 67 (which is the 5th value in the array)

• That expression represents a place to store a single integer, can can be used wherever an integer variable can

• For example, it can be assigned a value, printed, used in a calculation

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #50

Arrays

• An array stores multiple values of the same type

• That type can be primitive types or objects

• Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc.

• In Java, the array itself is an object

• Therefore the name of the array is an object reference variable, and the array itself is instantiated separately

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #51

Declaring Arrays

• The scores array could be declared as follows:

int[] scores = new int[10];• Note that the type of the array does not specify its size, but

each object of that type has a specific size

• The type of the variable scores is int[] (an array of integers)

• It is set to a newly instantiated array of 10 integers

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #52

Declaring Arrays

• Some examples of array declarations:

float[] prices = new float[500];

boolean[] flags;

flags = new boolean[20];

char[] codes = new char[1750];

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #53

Bounds Checking

• Once an array is created, it has a fixed size

• An index used in an array reference must specify a valid element

• That is, they must be in bounds (0 to N-1)

• The Java interpreter will throw an exception if an array index is out of bounds

• This is called automatic bounds checking

• Its common to inadvertently introduce off-by-one errors when using arrays

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #54

Bounds Checking

• Each array object has a public constant called length that stores the size of the array

• It is referenced through the array name (just like any other object):

scores.length• Note that length holds the number of elements, not the

largest index

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #55

final int STUDENTS = 100;InputReader in = new InputReader();float[] test = new float[STUDENTS], shifted = new

float[STUDENTS];float sum = 0, bonus;float average; for (int i = 0; i < STUDENTS; i++) { test[I] = in.readFloat(“Enter grade “ + i); sum += test[i];}

average = sum / STUDENTS;

for (int i = 0; i < STUDENTS; i++) shifted[i] = (float) Math.sqrt((double) (10 * test[i])); // print shifted[] and test[]...

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #56

Array Declarations Revisited

• The brackets of the array type can be associated with the element type or with the name of the array

• Therefore

float[] prices;

and

float prices[];

are essentially equivalent

• The first format is usually more readable

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #57

Initializer Lists

• An initializer list can be used to instantiate and initialize an array in one step

• The values are delimited by braces and separated by commas

• Examples: int[] units = {147, 323, 89, 933, 540,

269, 97, 114, 298, 476};

char[] letter_grades = {'A', 'B', 'C',

'D', 'F'};

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #58

Initializer Lists

• Note that when an initializer list is used:– the new operator is not used

– no size value is specified

• The size of the array is determined by the number of items in the initializer list

• An initializer list can only be used in the declaration of an array

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #59

Arrays of Objects

• The elements of an array can be object references

• The declaration

String[] words = new String[25];

reserves space to store 25 references to String objects

• It does NOT create the String objects themselves

• Each object stored in an array must be instantiated separately

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #60

class Children {

public static void main (String[] args) {

String[] name_list =

{"Joshua", "Bethany", "Megan", "Eric"};

for (int name = 0; name < name_list.length; name++)

System.out.println (name_list[name]);

} // method main

} // class Children

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #61

class Reverse {

public static void main (String[] args) {

InputReader in = new InputReader(); String[] names = new String[5]; for (int name = 0; name < names.length; name++) names[name] = in.readString(“Enter string “ + i); System.out.println ("The strings you entered, in reverse:");

for (int name = names.length-1; name >= 0; name--) System.out.println (names[name]);

} // method main

} // class Reverse

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #62

Arrays as Parameters

• An entire array can be passed to a method as a parameter

• Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other

• Changing an array element in the method changes the original

• An array element can be passed to a method as well, and follow the parameter passing rules of that element's type

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #63

class ArrayExample { public static void copy(int[] a1, int[] a2) { for (int i = 0; i < a1.length; i++) a1[i] = a2[i]; } public static void referenceCopy(int[] a1, int[] a2) { a1 = a2; } public static void multiply(int[] a, int c) { for (int i = 0; i < a.length; i++) a[i] *= c; } public static int minElement(int[] a) { int min = Integer.MAX_VALUE; for (int i = 0; i < a.length; i++) if (a[i] < min) min = a[i]; return min; }}

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #64

class ArrayExample { // … continued from previous slide public static int[] clone(int[] a) { int[] clone = new int[a.length]; for (int i = 0; i < a.length; i++) clone[i] = a[i]; return clone; }}

int[] a1 = {11, 22, 11, 33, 44, 55};int[] a2 = {99, 99, 99, 105, -3};

ArrayExample.copy(a2,a1);ArrayExample.copy(a1,a2); // what happens here?

ArrayTools.referenceCopy(a1,a2);

int[] a3 = ArrayExample.clone(a1);

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #65

Multidimensional Arrays

• A one-dimensional array stores a simple list of values

• A two-dimensional array can be thought of as a table of values, with rows and columns

• A two-dimensional array element is referenced using two index values

• To be precise, a two-dimensional array in Java is an array of arrays, therefore each row can have a different length

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #66

Multidimensional Arrays

• An initializer list can be used to create and set up a multidimensional array

• Each element in the list is itself an initializer list

• Note that each array dimension has its own length constant

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #67

class Table2D {

private int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} };

public void print() { for (int row=0; row < table.length; row++) { for (int col=0; column < table[row].length; col++) System.out.print (table[row][column] + " "); System.out.println(); } } // method print

// … method sumColumn in next slide …

} // class Table2D

The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies

Slide #68

public int sumColumn (int column) { int sum = 0;

for (int row=0; row < table.length; row++) if (column < table[row].length) sum += table[row][column];

return sum; }