Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS1001 Lecture 14.

Similar presentations


Presentation on theme: "CS1001 Lecture 14."— Presentation transcript:

1 CS1001 Lecture 14

2 Overview Java Programming Arrays

3 Goals Understand the basics of Java programming
Control Statements and Arrays

4 Assignments Brookshear: Ch 4, Ch 5 (Read)
Read linked documents on these slides (slides will be posted in courseworks)

5 Arithmetic Operators: +, -, /, * , %
The precedence of operators and parentheses work the same way as in algebra. m % n means the remainder when m is divided by n (e.g. 17 % 5 is 2). % has the same rank as / and * Same-rank binary operators are performed in order from left to right. *, /, and % have the same rank. There is also the unary operator -, e.g. a = -a; All unary operators have a higher rank than binary operators and are executed first.

6 Arithmetic (cont’d) The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions. If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int. If an expression has several binary operators of the same rank with no parentheses, the intermediate results are calculated from left to right. For example: x = a / b * c; is the same as temp = a / b; x = temp * c;

7 Arithmetic (cont’d) Caution: if a and b are ints, then a / b is truncated to an int… 17 / 5 gives 3 3 / 4 gives 0 …even if you assign the result to a double: double ratio = 2 / 3; This is another place to be very careful. Integer truncation can be useful, too. For example, find the whole number of weeks in a given number of days or the number of whole hours in a given number of minutes: int fullWeekCount = dayCount / 7; System.out.println(mins / 60 + " hours and " + mins % 60 + " minutes."); The double type of the result doesn’t help: ratio still gets the value 0.0.

8 Arithmetic (cont’d) To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3; double ratio = 2 / 3.0; double factor = (double) m / (double) n; double factor = m / (double) n; double r2 = k / 2.0; double r2 = (double) k / 2; Another reason for symbolic constants: if you declare a symbolic constant as a double, then casts to double are unnecessary and arithmetic errors are avoided. A few redundant casts are OK, and they make your code self-documenting. Casts

9 Arithmetic (cont’d) Caution: the range for ints is from to (about -2·109 to 2·109) Overflow is not detected by the Java compiler or interpreter n = ^n = n! = n = ^n = n! = n = ^n = n! = n = ^n = n! = n = ^n = n! = n = ^n = n! = n = ^n = n! = 109 is OK, but 1010 is already wrong. When you eventually overflow and hit the leftmost bit in an integer variable, the number becomes negative because this is the sign bit. 12 factorial is OK but 13 factorial is wrong, which is not immediately obvious if you don’t see the preceding factorial values. Java has a type long that uses eight bytes and can hold integer values from -263 to 263‑1.

10 Arithmetic (cont’d) Use compound assignment operators:
a = a + b; a += b; a = a - b; a -= b; a = a * b; a *= b; a = a / b; a /= b; a = a % b; a %= b; Use increment and decrement operators: a = a + 1; a++; a = a - 1; a--; a = a + b; gives away a novice. But so does a += a + b++; Do not use these in larger expressions

11 Review: What is a variable?
What is the type of variable that holds an object? What is a variable? A named container that can hold a value. What is the type of a variable that holds an object? The class to which the object belongs. What is meant by the scope of a variable? The area in the source code where the variable is visible. What is the scope of a field? The whole class. What is the scope of a local variable? From its declaration down to the closing brace of the block in which it is declared. Is it OK to give the same name to variables in different methods? Yes, and moreover it is desirable if their roles are similar. Is it OK to give the same name to a field and to a local variable of the same class? Never.

12 Review (cont’d): What is the range for ints?
When is a cast to double used? Given double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC? When is a cast to int used? Should compound assignment operators be avoided? What is the range for ints? from -231 to When is a cast to double used? When the operands are ints but we want the correct result as a double. (Be sure to cast an individual operand, not the final result.) Given double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC? 0 (5/9 gives 0 first, the rest doesn’t matter). When is a cast to int used? To truncate the double result of a calculation and store it in an int. Should compound assignment operators be avoided? On the contrary, they should be used, but not inside fancy expressions.

13 Objectives: Learn about arrays and when to use them
Learn the syntax for declaring and initializing arrays Learn how to access array’s size and elements This chapter is only an introduction. More on arrays in Section 11.6, “Iterations and Arrays,” and in Chapter 12.

14 What is an Array An array is a block of consecutive memory locations of the same data type. Individual locations are called array’s elements. Sometimes when we say “array’s element” we mean the value stored in that element. There is indeed some confusion in the usage of “element.” In some situations, the word refers to the location in an array, as in “set the value of the k-th element.” In other situations it refers to a value stored in the array, as in “find the smallest element.” This dual usage is somewhat similar to the situation with the term “variable.” This is no big deal, as long as everyone understands the difference between a location and a value stored in it. 1.39 1.69 1.74 0.0 An array of doubles

15 What is an Array (cont’d)
Rather than treating each element as a separate named variable, the whole array gets one name. Specific array elements are referred to by using array’s name and the element’s number, called index or subscript. The idea is not to save names, of course, but to be able to handle an array’s elements uniformly, using algorithms. 1.39 1.69 1.74 0.0 o is array’s name c[0] c[1] c[2] c[3]

16 Indices (Subscripts) In Java, an index is written within square brackets following array’s name (e.g., a[k]). Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1]. An index can have any int value from 0 to array’s length - 1. The convention of starting indices from 0 comes from C. It is easy to get used to.

17 Indices (cont’d) We can use an int variable or any expression that evaluates to an int value as an index: a [3] a [k] a [k - 2] a [ (int) (6 * Math.random()) ] That’s the beauty of it: the index may be a variable calculated at run time; it can be used in algorithms.

18 Indices (cont’d) In Java, an array is declared with fixed length that cannot be changed. Java interpreter checks the values of indices at run time and throws IndexOutOfBoundsException if an index is negative or if it is greater than the length of the array - 1. arr = new int[newSize]; does not really resize arr: it simply throws away the old array and allocates a new one with default values. “Throws an exception” means reports a run-time error with rather detailed information about where in the code it occurred and aborts the program.

19 Why Do We Need Arrays? The power of arrays comes from the fact that the value of a subscript can be computed and updated at run time. Before (no arrays): After (with arrays): int sum = 0; sum += score0; sum += score1; sum += score999; int n = 1000; int sum = 0, k; for (k = 0; k < n; k++) sum += scores[k]; Without arrays it would be difficult to process a collection of items algorithmically. Difficult but possible: with linked lists (one of the subjects in Java Methods AB). 1000 times!

20 Why Arrays? (cont’d) Arrays give direct access to any element — no need to scan the array. Before (no arrays): After (with arrays): if (k == 0) display (score0); else if (k == 1) display (score1); else … // etc. display (scores[k]); “Direct access” means you can go directly to where the item is stored (like a particular track on a CD), as opposed to scanning from the beginning to find an item (as on a tape).

21 Arrays as Objects In Java, an array is an object. If the type of its elements is anyType, the type of the array object is anyType[ ]. There are two ways to declare an array: The difference becomes significant only when several variables are declared in one statement: int [ ] a, b; // both a, b are arrays int a [ ], b; // a is an array, b is not anyType [ ] arrName; This has several implications: you have to create (initialize) it before you can use it, it is passed to methods as a reference, etc. You can pass an array to any method that expects an Object type of argument. If you want to test it, try: Object x = new int[100]; or anyType arrName [ ];

22 Arrays as Objects (cont’d)
As with other objects, the declaration creates only a reference, initially set to null. An array must be created before it can be used. There are two ways to create an array: arrName = new anyType [ length] ; Brackets, not parens! The second form, with a list of initial values, is not in the AP subset. or arrName = new anyType [ ] { val1, val2, …, valN };

23 Declaration and Initialization
When an array is created, space is allocated to hold its elements. If a list of values is not given, the elements get the default values. scores = new int [10] ; // length 10, all values set to 0 words = new String [10000]; // length 10000, all values set to null As for fields: 0 for numbers, false for booleans, null for objects. The elements get default values even if an array is a local variable. You can think of an array’s elements as sort of like its “fields.”

24 Initialization (cont’d)
An array can be declared an initialized in one statement: int scores [ ] = new int [10] ; // length 10 private double gasPrices [ ] = { 1.49, 1.69, 1.74 }; String words [ ] = new String [10000]; String cities [ ] = {"Atlanta", "Boston", "Cincinnati" }; Nothing new here: this is true for any object.

25 Initialization (cont’d)
Otherwise, initialization can be postponed until later: String words [ ]; // not yet initialized ... words = new String [ console.readInt() ]; private double gasPrices [ ]; // not yet initialized gasPrices = new double [ ] { 1.52, 1.69, 1.75 }; If you try to use it, (e.g., arr.length or arr[k]), you’ll get a null reference exception.

26 Array’s Length The length of an array is determined when that array is created. The length is either given explicitly or comes from the length of the {…} initialization list. The length of an array arrName is referred to in the code as arrName.length. length appears like a public field (not a method) in an array object. As opposed to String, where length() is a method.

27 Review: Why are arrays useful?
What types of elements can an array have? How do we refer to an array’s element in Java? What happens if an index has an invalid value? How do we refer to the length of an array? Why are arrays useful? They allow a program to process a collection of related values algorithmically. What types of elements can an array have? Any data type that a variable can have. How do we refer to an array element in Java? whateverArrayName[index]. What happens if an index has an invalid value? The program reports a run-time error (throws IndexOutOfBoundsException). How do we refer to the length of an array? whateverArrayName.length

28 Sorting

29 Alternate Sorting Algorithm (Selection Sort)
main(String[] args) { int inputSize = args.length; int[] sortedArray = new int[inputSize]; for (i=0; i < inputSize; i++) { (1) Loop through args, find largest element and remember its index (ie for (int j = 0; …)) (2) Put the largest element into the ith location of sortedArray; (3) Delete (set to -1) the ith element of args }


Download ppt "CS1001 Lecture 14."

Similar presentations


Ads by Google