Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

Size: px
Start display at page:

Download "Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)"

Transcription

1 Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types Internal representation of Java arrays and potential pitfalls.. p.1/74. p.2/74 Definition Java arrays An array is a sequence of components (of the same type) with the following properties the length of the array equals the number of components of the array and is fixed when the array is created each component of the array has a fixed and unique index the indices range from a lower index bound to an upper index bound each component of the array can be accessed and modified (in constant time) using its index a... low low+1 low+2 high 2 high 1 high Java arrays have the following specific properties: For an array of length n, the lower index bound is always 0 and the upper index bound is always n 1 The notation for inspecting the length of an array a is a.length Every array is homogeneous, that is, the type of all its components is the same However, if all components are of type T, where T is an object class, then it can store objects of any subclass of T The notation for accessing the component of an array a at index i is a[i]. p.3/74. p.4/74

2 Java arrays: Creation (1) Java arrays: Creation (2) The three steps for creating an array are: 1. Defining an array There are two ways to declare that a variable is an array i n t [ ] Array1 ; i n t Array2 [ ] ; both have exactly the same effect The declaration itself does not allocate memory 2. Allocating memory space for the array Array1 = new i n t [ 3 ] ; Only at this point will memory space be allocated. Remember that Array1 has 3 components with indices 0, 1, and 2. The three steps for creating an array are: 3. Initialising the components of the array If we do not specify the initial values for the components of an array, then the components are initialised with 0 or null as applicable, but it is good practise not to rely on this feature of Java. One way of initialising an array yourself is by specifying the initial values for all the components of an array i n t [ ] Array2 = { 2, 3, 5, 7 } ; Notice that in this case we do not and cannot specify the size of the array. It will automatically be inferred that Array2 has 4 components with indices 0 to 3.. p.5/74. p.6/74 Java arrays: Creation (3) Java arrays: Creation (4) The first two steps of creating an array can be performed as one: i n t [ ] Array3 = new i n t [ 3 ] ; i n t Array4 [ ] = new i n t [ 4 ] ; The third step of initialising an array is optional, but can also be merged with the others: i n t [ ] Array5 = { 1, 2 } ; i n t Array6 [ ] = { 6, 5, 4 } ; In all the examples up to now we have used an integer constant as the size of the array, but this is not necessary: import java. i o. ; cl a ss TestArray { p u b l i c s t a t i c BufferedReader keyboardinput = new BufferedReader ( new InputStreamReader ( System. i n ) ) ; p u b l i c s t a t i c void main ( S t r i n g args [ ] ) throws IOException { } } System. out. p r i n t l n ( " Enter size of array : " ) ; i n t n = new I n t e g e r ( keyboardinput. readline ( ) ). i n t V a l u e ( ) ; i n t [ ] Array1 = new i n t [ n ] ; System. out. p r i n t l n ( " Length of Array1 : " + Array1. length ) ;. p.7/74. p.8/74

3 Java arrays: Creation (5) Here is a transcript of a run of TestArray: Enter size of array : 2 Length of Array1 : 2 The example also illustrates that arrays are allocated dynamically during the run-time of the program What is the minimal size of an array? It turns out that the minimal size of an array is 0 Enter size of array : 0 Length of Array1 : 0 However, an array of size 0 has no components. So, we cannot store anything in it. Java arrays: Creation (6) What happens if we try to create an array of size -1? Enter size of array : 1 Exception i n thread " main " java. lang. NegativeArraySizeException at TestArray3. main ( TestArray3. java : 1 2 ) This leads to a run-time error that causes an exception to be thrown Would it make a difference if we could already see in the program code that a negative array size is used? i n t Array7 [ ] = new i n t [ 1]; No! The Java compiler will not indicate that something is wrong. We still get the same run-time error. p.9/74. p.10/74 Exceptions Java arrays: Access (1) An exception is an event that occurs during program execution and which makes further execution impossible Standard examples are divide by zero error and arithmetic overflow, but there are many more An exception handler is a piece of code that gets invoked when an exception is encountered It allows the program to either fix what ever caused the exception, or abort execution gracefully The default exception handler just outputs an error message and terminates the program execution How you write your own exception handlers will be a subject of COMP 213 One of the standard operations performed on arrays is to loop through all array elements to apply some operation to each of them i n t [ ] Array2 = { 2, 3, 5, 7 } ; f o r ( i n t i = 0 ; i < 4 ; i + + ) { System. out. p r i n t l n ( Array2 [ i ] ) ; } Note that this is an example of coupling: Changing the number of components of Array2 would require us to change the for-loop But this can easily be avoided using the length attribute of arrays f o r ( i n t i = 0 ; i <Array2. l e n g th ; i + + ) { System. out. p r i n t l n ( Array2 [ i ] ) ; }. p.11/74. p.12/74

4 Java arrays: Access (2) Always remember that in a Java array of size n, indices range from 0 to n 1 and not from 1 to n Executing the following program i n t [ ] Array2 = { 2, 3, 5, 7 } ; f o r ( i n t i = 1 ; i < = 4; i + + ) { System. out. p r i n t l n ( Array2 [ i ] ) ; } results in the following output Exception i n thread " main " java. lang. ArrayIndexOutOfBoundsException : 4 at TestArray. main ( TestArray. java : 8 ) Java arrays: Access (3) Would it make any difference if we could already see in the program code that an illegal array access is tried? i n t [ ] Array2 = { 2, 3, 5, 7 } ; System. out. p r i n t l n ( Array2 [ 4 ] ) ; No! The Java compiler will again not indicate that something is wrong. We still get the same run-time error Exception i n thread " main " java. lang. ArrayIndexOutOfBoundsException : 4 at TestArray. main ( TestArray. java : 8 ). p.13/74. p.14/74 The Array Data Structure and Java array We can see that Java arrays provide all the operations of the Array data structure However, there are number of additional operations that we might want to perform on arrays: E.g. given an array a and a data item d we can define the index of d in a as the smallest index i such that a[i] equals d (the index of d in a is undefined if d is not stored in a) So, in a the index of 3 is 1, the index of 7 is 3, etc. Primitive types and reference types (1) Remember that Java distinguishes between primitive (data) types and reference types The primitive types are: Type Default value integer: byte, short, int, long 0 floating point: float, double +0.0f or +0.0d character: char null character logical: boolean false others: void A variable of a primitive type is directly associated with a memory location storing the value of the variable If a variable is not initialised explicitly, then the default value for its type is used to initialise it implicitly. p.15/74. p.16/74

5 Primitive types and reference types (2) Instead of talking about memory locations we often depict this situation as follows: For primitive types, variable value var1 == var2 is true if the stored values for variables var1 and var2 are identical Primitive types and reference types (3) Remember that Java distinguishes between primitive (data) types and reference types Any data type that is not a primitive type is a reference type A variable of a reference type is not directly associated with a memory location that stores a value Instead it is associated with a memory location that stores the address of the memory location storing the value, that is, it stores a reference to a value This kind of variable is called reference variable. p.17/74. p.18/74 Primitive types and reference types (4) Instead of talking about memory locations and addresses we often depict this situation as follows: variable value(s) The declaration of a reference variable does not initialise the variable with the address of some value(s) Instead, the variable is given the special value null if it is an instance or class variable variable null... Primitive types and reference types (5) For reference types, var1 == var2 is true, if both var1 and var2 store the same address (or they are both null) There is an alternative way to compare variables: equals var1.equals(var2) A number of classes define equals in such a way that it compares the value found at the addresses stored in var1 and var2 However, by default, it returns the same result as var1 == var2 (given that var1 is non-null). p.19/74. p.20/74

6 Internal representation of Java arrays Java arrays are reference types Example: T [ ] a = new T [ n ] Defines an array variable with name a whose components are of type T and allocates memory space for n such components a T[] n class tag length 0 1 n 2 n 1 Equality between array variables A consequence of the fact that Java arrays are reference types is that the == operator compares references not the data stored in arrays So, if we have the following two arrays i n t [ ] Array1 = { 2, 3, 5, 7 } ; i n t [ ] Array2 = { 2, 3, 5, 7 } ; then Array1==Array2 evaluates to false Unfortunately, the equals operator does not compare the data stored in arrays either So, in our example Array1.equals(Array2) again evaluates to false. p.21/74. p.22/74 Assignments Another consequence of the fact that Java arrays are reference types is that an assignment statement like Array1 = Array2 copies the address stored in Array2 to Array1, making both Array1 and Array2 refer to the same object i n t [ ] Array1 = { 2, 3, 5, 7 } ; i n t [ ] Array2 = { 2, 3, 5, 7, 1 1 } ; Array1 = Array2 ; Array2 [ 4 ] = 1 3 ; System. out. p r i n t l n ( " Array1 [ 4 ] = " + Array1 [ 4 ] ) ; prints out Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 4: Arrays (2) Array1 [ 4 ] = 1 3. p.23/74. p.24/74

7 Topics Internal representation of Java arrays Java arrays: Access implementation Arrays: Advantages and disadvantages Enlarging arrays Arrays of reference types Arrays of string objects Arrays of objects Java arrays are reference types Example: T [ ] a = new T [ n ] Defines an array variable with name a whose components are of type T and allocates memory space for n such components a T[] n class tag length 0 1 n 2 n 1. p.25/74. p.26/74 Java arrays: Access implementation a T[] n class tag length 0 1 n 2 n 1 Given an index i how do we work out where to look for the component a[i]? Arrays: Advantages and disadvantages Arrays, including Java arrays, are static data structures since the number of elements they can store is fixed at the time of creation As such they inherit all the advantages and disadvantages of static data structures memory location of a[i] = value of variable a + size of class tag T[] + size of length attribute + (i size of component) This computation can be done in constant time (i.e. the computation is so fast that, approximately, we may say that it takes an amount of time that is independent of the size of the array).. p.27/74. p.28/74

8 Arrays: Advantages Arrays: Disadvantages Easy to specify (declaration, allocation of memory space, initialisation can all be done in one line of code) There is no run-time overhead to allocate/free memory (apart from once at the start and end) Random (direct) access to any element via the index e.g. direct access to a student record via student number (index can be derived from student number) It is usually faster to sequentially access elements than, for example, in linked lists, due to contiguous storage (good locality) and constant time computation of the address of a component A potential disadvantage of arrays (depending on the application) is the need to know the size at the time of allocation. Careful design is required to make sure that the array will be large enough to hold the largest possible group of data but no larger Can we find a workaround for this problem? Yes, if more elements are required than an array is able to store, then a new larger array needs to be created and the data transferred across.. p.29/74. p.30/74 Enlarging arrays Arrays as method arguments (1) Assume that oldarray is an integer array which is too small for the number of elements we want to store in it The following code replaces oldarray by an array of twice the size of the original array i n t oldsize = oldarray. length ; i n t newsize = 2 oldarray. length ; i n t [ ] newarray = new i n t [ newsize ] ; f o r ( i n t i = 0 ; i < oldarray. length ; i ++) newarray [ i ]= oldarray [ i ] ; oldarray = newarray ; oldarray [ oldsize ] = 5 ; Here is an example of how to write a method that takes an array as an argument It simply encapsulates the algorithm for enlarging an array we have just seen in a method p u b l i c s t a t i c i n t [ ] doublesize ( i n t [ ] oldarray ) { } i n t [ ] newarray = new i n t [ 2 oldarray. length ] ; f o r ( i n t i = 0 ; i < oldarray. length ; i ++) newarray [ i ] = oldarray [ i ] ; r e t u r n ( newarray ) ; The last line works now (instead of throwing an exception). p.31/74. p.32/74

9 Arrays as method arguments (2) Arrays as method arguments (3) Now we use this method in a program: import java. i o. ; cl a ss TestArray5 { p u b l i c s t a t i c i n t [ ] doublesize ( i n t [ ] oldarray ) {... } p u b l i c s t a t i c void main ( S t r i n g args [ ] ) { i n t [ ] primes = { 2, 3, 5 } ; i n t oldsize = primes. length ; primes = doublesize ( primes ) ; primes [ oldsize ] = 7 ; f o r ( i n t i = 0 ; i <primes. length ; i ++) System. out. p r i n t l n ( primes [ i ] ) ; } }. p.33/74 The output of program TestArray5 is: Thus, it seems that instead of three integers, our array is now able to store six integers Doesn t that mean that what we said about the disadvantages of static data structures, and Java arrays in particular, is wrong?. p.34/74 Static data structures again Arrays of reference types Static data structures, including Java arrays, are fixed in size at the time of creation The method doublesize seems to allow us to enlarge a Java array However, looking closer, doublesize does not enlarge the array it is given as an argument, but it creates a completely new array Also, using doublesize we now incur the same disadvantage that dynamic data structures have: a memory allocation overhead As a consequence, this approach only makes sense, if the number of times we have to use doublesize is significantly smaller than the number of times we have to access array components (so, that we are still faster than with a dynamic data structure). p.35/74 Apart from arrays of primitive data types we can have arrays of reference types (objects) These arrays of reference types are created and used in much the same way as the arrays we have already seen Note that in an array of reference types not the objects are stored in the array, but references (memory locations) to the objects The objects themselves have to be created and memory space has to be allocated for them separately. p.36/74

10 Arrays of string objects: Creation Arrays of string objects: Storing strings A particular reference type we already know is String So, S t r i n g [ ] words = new S t r i n g [ 4 ] ; creates an array of strings with four components Remember, this declaration does not allocate any memory space for the strings, it only allocates space for an array storing four memory locations (of strings) Also, all the components are initialised with the null reference, not with an empty string Next, let us store strings in our array of strings words [ 1 ] = " tim " ; words [ 2 ] = " tom " ; words [ 3 ] = " tim " ; Remember, "tim" and "tom" are so-called string literals Are words[1] and words[3] equal? Both as well as words[1] == words[3] words[1].equals(words[3]) return true! This is due to the compiler which only creates one internal string object for both occurrences of "tim" in our code. p.37/74. p.38/74 Arrays of objects: Creation Arrays of objects: Storing objects The most general kind of array would have components of type Object The Object class is located at the top of the Java class hierarchy Every Java class is a descendant, direct or indirect, of the Object class, but not the primitive data types We can declare an array with components of type Object as follows: Object [ ] objarray = new Object [ 3 ] ; In the components of objarray we can now store objects of any subclass of Object objarray [ 0 ] = " tim " ; objarray [ 1 ] = new BasicBox ( 1, 2, 3 ) ; Remember that BasicBox is a class that we have defined earlier We assume that the definition of the BasicBox class is extended by p u b l i c S t r i n g t o S t r i n g ( ) { } r e t u r n ( " box ( " + depth + ", " + height + ", " + width + " ) " ) ; which overrides the default method for providing a String representation of an object. p.39/74. p.40/74

11 Arrays of objects: Storing primitive data Arrays of objects: Storing primitive data But, unfortunately, we cannot directly store an element of a primitive data type in it Including the following code objarray [ 2 ] = 5 ; into our program results in the following error message by the compiler: TestObjectArray. java : 1 2 : incompatible types found : i n t required : java. lang. Object objarray [ 2 ] = 5 ; ^ 1 e r r o r To store an integer value like 5 in objarray we have to make use of a wrapper class Each of the primitive data types like char or int has a corresponding wrapper class associated with it, named Character, Integer, etc. Each of these classes wraps a primitive data type into a class which in turn is a subclass of Object So, objarray [ 2 ] = new I n t e g e r ( 5 ) ; wraps the number 5 into an object of class Integer, which can be assigned to a component of objarray. p.41/74. p.42/74 Arrays of objects: Accessing (1) Arrays of objects: Accessing (2) To access all the components of an array of reference types we can use the same code that we have used for integer arrays f o r ( i n t i = 0 ; i < objarray. length ; i ++) System. out. p r i n t l n ( " objarray [ " + i + " ] = " + objarray [ i ] ) ; will produce the following output objarray [ 0 ] = tim objarray [ 1 ] = box ( 1, 2, 3 ) objarray [ 2 ] = 5 objarray [ 3 ] = n u l l objarray [ 4 ] = n u l l However, since we have now turned an integer value into an Integer object, we can no longer use it in the same way as before Adding the line i n t n = 3 + objarray [ 2 ] ; to our program results in the following error message by the compiler: TestObjectArray. java : 1 6 : operator + cannot be applied to 1 e r r o r i n t n = 3 + objarray [ 2 ] ; ^ i n t, java. lang. Object. p.43/74. p.44/74

12 Arrays of objects: Accessing (3) Arrays of objects: Accessing (4) Instead, we have to unwrap the Integer object first, to get the integer value back Unfortunately, the straightforward approach i n t n = 3+ objarray [ 2 ]. i n t V a l u e ( ) ; produces again an error message by the compiler: TestObjectArray. java : 1 7 : cannot resolve symbol symbol : method i n t V a l u e ( ) l o c a t i o n : class java. lang. Object i n t n = 3 + objarray [ 2 ]. i n t V a l u e ( ) ; One way of solving this problem is to use typecasting: We typecast objarray[2] from the Object class to its subclass Integer Once this is done, we can use the intvalue method of the Integer class to retrieve the actual integer value i n t n = 3 + ( ( I n t e g e r ) objarray [ 2 ] ). i n t V a l u e ( ) ; System. out. p r i n t l n ( " n = " + n ) ; produces the output n = 8 The compiler only knows that the components of objarray belong to class Object It does not know that objarray[2] belongs to Integer. p.45/74. p.46/74 Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 5: Multi-dimensional arrays Multi-dimensional arrays: Examples of applications Multi-dimensional array, definition 2-dimensional arrays in Java Access implementation Creation Cloning Access 2-dimensional arrays as method arguments Higher-dimensional arrays in Java Example: Train departure information. p.47/74. p.48/74

13 (Linear) Arrays 2-D organisation: Examples (1) An array is a sequence of indexed components. a... low low+1 low+2 high 2 high 1 high In many applications it is more logical to think of the data in a table form instead of a linear list: timetable chess board distances between cities theatre seating layout Other, perhaps less obvious applications: Crosswords O R T H O D O X Y C O N N E R D E H O L A N C E D I S D A I N Y S E T O P C I R C U S E A S E L O O T R U L A N I M A E D I C T S A P T A L R E E V E H O Y D E N A X L E A G C H A B L I S E L V E R H C E I T E I. p.49/74 S E T D E S P A I R E D. p.50/74 2-D organisation: Examples (2) 3-D organisation: Examples Images rows of columns of pixels (picture elements) each pixel has a value binary images: black - 0, white - 1 greyscale: from black to white each pixel is identifiable by its 2-D coordinates (row number and column number) 3-D graphics e.g., location of objects within a room 3-D medical imaging a stack of 2-D slices (images) Colour images three two-dimensional arrays (one array storing the red value of each pixel in its components, the other two arrays do the same for the green and blue value) or one two-dimensional array where each component is a one-dimensional array (storing the red, green, and blue value of a single pixel). p.51/74. p.52/74

14 Multi-dimensional array A multi-dimensional array is a collection of components indexed by unique integer sequences of fixed length with the following properties: the length of an index sequence is the rank or number of dimensions of a multi-dimensional array for each dimension d there is a lower index bound l d and a higher index bound h d for an array of dimension n, an index is an integer sequence written [i 1 ]...[i n ] such that for every dimension d, l d i d h d any component of the array can be accessed and modified in constant time using its index. p.53/74 Multi-dimensional arrays: Example Here is an example of a 2-dimensional array: a l 2 l h 2 1 h 2 l 1 a[l 1 ][l 2 ] a[l 1 ][h 2 ] l h 1 1 h 1 a[h 1 ][l 2 ] a[h 1 ][h 2 ] The fact that we have drawn the first dimension in vertical direction and the second dimension in horizontal direction has no particular importance. p.54/74 2-dimensional arrays in Java Java does not actually support 2-dimensional (or higher dimensional) arrays as such We can achieve the same effect, though, using a 1-dimensional array whose components are 1-dimensional arrays i n t [ ] [ ] a = new i n t [ 3 ] [ 4 ] a class tag length class tag length a[0] is a 1-dimensional array a[0][0]is an integer component Access implementation (1) How does Java find the memory location of a component a[i][j] in a 2-dimensional array a? 1. Locate a[i] using the function memory location of a[i] = value of variable a + size of class tag of a + size of length attribute + (i size of an address) 2. Retrieve the value of a[i] We know that a[i] stores the memory location (address) of the 1-dimensional array storing a[i][j]. p.55/74. p.56/74

15 Access implementation (2) Access implementation: Properties How does Java find the memory location of a component a[i][j] of a 2-dimensional array a? 3. Locate a[i][j] using the function memory location of a[i][j] = value of variable a[i] + size of class tag of a[i] + size of length attribute + (j size of component) This algorithm can easily be generalised to arrays of arbitrary dimensionality For example, for a 3-dimensional array we have to perform 5 steps to locate a[i][j][k]: 1. Locate a[i] 2. Retrieve a[i] 3. Locate a[i][j] 4. Retrieve a[i][j] 5. Locate a[i][j][k] The algorithm is executed during run-time each time we need a[i][j][k]. Note that if a[i][j] is of reference type, then the size of a component is again the size of an address. p.57/74. p.58/74 2-dimensional arrays in Java: Creation (1 2-dimensional arrays in Java: Creation (2 Just as for 1-dimensional arrays, the three steps for creating a 2-dimensional array are: (1) Defining an array, (2) Allocating memory space for an array, and (3) Initialising an array 1. Defining a 2-dimensional array There are two ways to declare that a variable is a 2-dimensional array i n t [ ] [ ] Array1 ; i n t Array2 [ ] [ ] ; both have exactly the same effect The declaration itself does not allocate memory 2. Allocating memory space for a 2-dimensional array Array1 = new i n t [ 3 ] [ 4 ] ; Only at this point will memory space be allocated. Array1 is a 1-dimensional array with three components, each component itself is (a reference to) a 1-dimensional array with four components of type int Alternatively, we can view Array1 as a 2-dimensional array which has 3 rows (0, 1, and 2) and 4 columns (0, 1, 2, 3) and each component has type int However, always remember that this is an abstraction of the true internal structure of 2-dimensional arrays in Java. p.59/74. p.60/74

16 2-dimensional arrays in Java: Creation (3 2-dimensional arrays in Java: Creation (4 3. Initialising the components of a 2-dimensional array Unless we specify initial values for the components of a 2-dimensional array ourselves, then the component are initialised with 0 or null Remember that S t r i n g [ ] [ ] Array3 = new S t r i n g [ 2 ] [ 3 ] ; creates a 2-dimensional array with components of type String which are initialised to null, not to the empty string One way of initialising an array ourselves is by specifying the initial values for all the components of an array: i n t [ ] [ ] Array2 = { { 1 0, 1 2, 1 4 }, { 2 0, 2 2, 2 4 } } ; The result will be Array2[0][0] = 10 Array2[0][1] = 12 Array2[0][2] = 14 Array2[1][0] = 20 Array2[1][1] = 22 Array2[1][2] = 24 or, in form of a diagram: p.61/74. p.62/74 2-dimensional arrays in Java: Creation (5 2-dimensional arrays in Java: Creation (6 Instead of i n t [ ] [ ] Array2 = { { 1 0, 1 2, 1 4 }, { 2 0, 2 2, 2 4 } } ; we could also use existing arrays for initialisation: i n t [ ] Array4 = { 1 0, 1 2, 1 4 } ; i n t [ ] Array5 = { 2 0, 2 2, 2 4 } ; Array2 = { Array4, Array5 } ; However, this might not have the effect you want Note that Array2 now does not store copies of Array4 and Array5 in Array2[0] and Array2[1], respectively Instead it stores references to the already existing Array4 and Array5 in Array2[0] and Array2[1], respectively Consequently, if we change, for example, Array4[1], we also change Array2[0][1]: Array4 [ 1 ] = 5 1 ; System. out. p r i n t l n ( " Array2 [ 0 ] [ 1 ] = " + Array2 [ 0 ] [ 1 ] ) ; prints out Array2 [ 0 ] [ 1 ] = 5 1 To create copies of already existing 1-dimensional arrays, we can use the clone method: i n t [ ] Array4 = { 1 0, 1 2, 1 4 } ; i n t [ ] Array5 = { 2 0, 2 2, 2 4 } ; i n t [ ] [ ] Array2 = { ( i n t [ ] ) Array4. clone ( ), ( i n t [ ] ) Array5. clone ( ) } ;. p.63/74. p.64/74

17 2-dimensional arrays in Java: Cloning Be careful: It is possible to clone multi-dimensional arrays as well, but the clone is shallow Remember that multi-dimensional arrays in Java are arrays of arrays of arrays... Cloning only generates a copy of the root array For example, in a 2-dimensional array i n t [ ] [ ] Array2 = { { 1 0, 1 2, 1 4 }, { 2 0, 2 2, 2 4 } } ; Array2[0] and Array2[1] form an 1-dimensional array that stores the memory locations m 0 and m 1 of two 1-dimensional arrays If we clone Array2, then we only create a new 1-dimensional array that again stores m 0 and m 1 2-dimensional arrays in Java: Access (1) While we have used a single for-loop to access all the components of an 1-dimensional array, we can use two nested for-loops to do the same for a 2-dimensional array: f o r ( i n t i = 0 ; i < Array2. length ; i + + ) { } f o r ( i n t j = 0 ; j < Array2 [ i ]. length ; j ++) System. out. p r i n t ( " Array2 [ " + i + " ] [ " + j + " ] = " System. out. p r i n t ( " \ n " ) ; prints out + Array2 [ i ] [ j ] + ", " ) ; Array2 [ 0 ] [ 0 ] = 1 0, Array2 [ 0 ] [ 1 ] = 1 2, Array2 [ 0 ] [ 2 ] = 1 4, Array2 [ 1 ] [ 0 ] = 2 0, Array2 [ 1 ] [ 1 ] = 2 2, Array2 [ 1 ] [ 2 ] = 2 4,. p.65/74. p.66/74 2-dimensional arrays in Java: Access (2) 2-dimensional arrays as method argument f o r ( i n t i = 0 ; i < Array2. length ; i + + ) { } f o r ( i n t j = 0 ; j < Array2 [ i ]. length ; j ++) System. out. p r i n t ( " Array2 [ " + i + " ] [ " + j + " ] = " System. out. p r i n t ( " \ n " ) ; + Array2 [ i ] [ j ] + ", " ) ; Note that we use Array2.length to determine the number of rows of Array2 in the outer for-loop And we use Array2[i].length to determine the number of columns of the 1-dimensional array stored in Array2[i] in the inner for-loop Note also, the use of i in Array2[i].length means that there is no easy way to swap the two loops Initialising the component with index [i][j] in a 2-dimensional array with (i+1)*(j+1) In Java this is a trivial exercise: p u b l i c s t a t i c void i n i t A r r a y ( i n t Array [ ] [ ] ) { f o r ( i n t i = 0 ; i < Array. l e n g th ; i ++) f o r ( i n t j = 0 ; j < Array [ i ]. l e n g th ; j ++) Array [ i ] [ j ] = ( i +1) ( j + 1 ) ; } This method works since Any argument will be passed to this method using call-by-reference Java will only compute at run-time what the memory location of Array[i][j] is. p.67/74. p.68/74

18 Higher-dimensional arrays in Java Example: Train departure information Java permits arrays of three, four or more dimensions The way these arrays are created is a straightforward generalisation of the way 2-dimensional arrays are created Here is an example of the creation of a 3-dimensional array: class F i l l 3 D A r r a y { p u b l i c s t a t i c void main ( S t r i n g args [ ] ) { i n t [ ] [ ] [ ] M = new i n t [ 3 ] [ 4 ] [ 2 ] ; We want to develop a very simple information system for train departure information at Liverpool Lime Street Station The information is given in form of a table Time Destination Track 9:10 Manchester 6 9:15 Leeds 10 9:20 Nottingham 7 } } f o r ( i n t row = 0 ; row < M. length ; row++) f o r ( i n t c o l = 0 ; c o l < M[ row ]. length ; c o l ++) f o r ( i n t ver = 0 ; ver < M[ row ] [ c o l ]. length ; ver ++) M[ row ] [ c o l ] [ ver ] = row+ c o l +ver ; The only kind of query we deal with is When and where does the next train to X leave?. p.69/74. p.70/74 Train departure information: The code (1 Train departure information: The code (2 import java. i o. ; class TDI { s t a t i c S t r i n g [ ] [ ] t d i = { { " 9 : 1 0 ", " Manchester ", " 6 " }, { " 9 : 1 5 ", " Leeds ", " 1 0 " }, { " 9 : 2 0 ", " Nottingham ", " 7 " } } ; p u b l i c s t a t i c S t r i n g [ ] searchdest ( S t r i n g dest ) { S t r i n g [ ] r e s u l t = n u l l ; f o r ( i n t i = 0 ; i < t d i. length ; i ++) i f ( t d i [ i ] [ 1 ]. equals ( dest ) ) { r e s u l t = new S t r i n g [ 2 ] ; r e s u l t [ 0 ] = t d i [ i ] [ 0 ] ; r e s u l t [ 1 ] = t d i [ i ] [ 2 ] ; r e t u r n r e s u l t ; } ; r e t u r n r e s u l t ; }. p.71/74 p u b l i c s t a t i c void main ( S t r i n g args [ ] ) throws IOException { InputStreamReader i n p u t = new InputStreamReader ( System. i n ) ; BufferedReader keyboardinput = new BufferedReader ( i n p u t ) ; System. out. p r i n t l n ( " Where do you want to go? " ) ; S t r i n g [ ] i n f o = searchdest ( keyboardinput. readline ( ) ) ; i f ( i n f o = = n u l l ) System. out. p r i n t l n ( " Sorry, no t r a i n to t h i s d e s t i n a t i o n " ) ; else System. out. p r i n t l n ( i n f o [ 0 ] + " departing at t r a c k " + i n f o [ 1 ] ) ; } }. p.72/74

19 Train departure information: Script Here are two runs of the program: Information successfully retrieved Where do you want to go? Leeds 9:15 departing at track 10 No information found Where do you want to go? York Sorry, no train to this destination. p.73/74

Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists.

Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists. Announcements MODULE WEB-SITE: http://www.csc.liv.ac.uk/ michele/teaching/comp102/comp102.html FIRST ASSIGNMENT DEADLINE: Wednesday, February 1st, 14.30, LAB 7 Boxes (late submissions to be left in the

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

OCA Java SE 7 Programmer I Certification Guide By Mela Gupta. Arrays

OCA Java SE 7 Programmer I Certification Guide By Mela Gupta. Arrays 1 OCA Java SE 7 Programmer I Certification Guide By Mela Gupta In the OCA Java SE 7 programmer exam, you ll be asked many questions on how to create, modify, and delete String, StringBuilder, arrays, and

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Bh Solution Sheet 4 Software Engineering in Java This is a solution set for CS1Bh Question Sheet 4. You should only consult these solutions after attempting the exercises. Notice that the solutions

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Lecture Notes on Memory Layout

Lecture Notes on Memory Layout Lecture Notes on Memory Layout 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 11 1 Introduction In order to understand how programs work, we can consider the functions,

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC Java Programming, Fall Java Data Types and Control Constructs CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference

More information

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

Special Topics: Programming Languages

Special Topics: Programming Languages Lecture #23 0 V22.0490.001 Special Topics: Programming Languages B. Mishra New York University. Lecture # 23 Lecture #23 1 Slide 1 Java: History Spring 1990 April 1991: Naughton, Gosling and Sheridan (

More information

PIC 20A Number, Autoboxing, and Unboxing

PIC 20A Number, Autoboxing, and Unboxing PIC 20A Number, Autoboxing, and Unboxing Ernest Ryu UCLA Mathematics Last edited: October 27, 2017 Illustrative example Consider the function that can take in any object. public static void printclassandobj

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7 CPS109 Course Notes 7 Alexander Ferworn Unrelated Facts Worth Remembering The most successful people in any business are usually the most interesting. Don t confuse extensive documentation of a situation

More information

VARIABLES AND TYPES CITS1001

VARIABLES AND TYPES CITS1001 VARIABLES AND TYPES CITS1001 Scope of this lecture Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Primitive types Every piece of data

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Lecture Notes on Arrays

Lecture Notes on Arrays Lecture Notes on Arrays 15-122: Principles of Imperative Computation July 2, 2013 1 Introduction So far we have seen how to process primitive data like integers in imperative programs. That is useful,

More information

Java Threads and intrinsic locks

Java Threads and intrinsic locks Java Threads and intrinsic locks 1. Java and OOP background fundamentals 1.1. Objects, methods and data One significant advantage of OOP (object oriented programming) is data encapsulation. Each object

More information

CPSC 3740 Programming Languages University of Lethbridge. Data Types

CPSC 3740 Programming Languages University of Lethbridge. Data Types Data Types A data type defines a collection of data values and a set of predefined operations on those values Some languages allow user to define additional types Useful for error detection through type

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data

More information

1.00 Lecture 4. Promotion

1.00 Lecture 4. Promotion 1.00 Lecture 4 Data Types, Operators Reading for next time: Big Java: sections 6.1-6.4 Promotion increasing capacity Data Type Allowed Promotions double None float double long float,double int long,float,double

More information

Design Patterns: State, Bridge, Visitor

Design Patterns: State, Bridge, Visitor Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

Computer Science 1 Ah

Computer Science 1 Ah UNIVERSITY OF EDINBURGH course CS0077 COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS Computer Science 1 Ah Resit Examination Specimen Solutions Date: Monday 1st September 2003 Time: 09:30 11:00

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

Exercise 4: Loops, Arrays and Files

Exercise 4: Loops, Arrays and Files Exercise 4: Loops, Arrays and Files worth 24% of the final mark November 4, 2004 Instructions Submit your programs in a floppy disk. Deliver the disk to Michele Zito at the 12noon lecture on Tuesday November

More information

6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

More information

About this exam review

About this exam review Final Exam Review About this exam review I ve prepared an outline of the material covered in class May not be totally complete! Exam may ask about things that were covered in class but not in this review

More information

Compaq Interview Questions And Answers

Compaq Interview Questions And Answers Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not

More information

TOPICS TO COVER:-- Array declaration and use.

TOPICS TO COVER:-- Array declaration and use. ARRAYS in JAVA TOPICS TO COVER:-- Array declaration and use. One-Dimensional Arrays. Passing arrays and array elements as parameters Arrays of objects Searching an array Sorting elements in an array ARRAYS

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

More on Objects in JAVA TM

More on Objects in JAVA TM More on Objects in JAVA TM Inheritance : Definition: A subclass is a class that extends another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

3.1 Class Declaration

3.1 Class Declaration Chapter 3 Classes and Objects OBJECTIVES To be able to declare classes To understand object references To understand the mechanism of parameter passing To be able to use static member and instance member

More information

ISY00245 Principles of Programming. Module 7

ISY00245 Principles of Programming. Module 7 ISY00245 Principles of Programming Module 7 Module 7 Loops and Arrays Introduction This week we have gone through some of the concepts in your lecture, and will be putting them in to practice (as well

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

9 Working with the Java Class Library

9 Working with the Java Class Library 9 Working with the Java Class Library 1 Objectives At the end of the lesson, the student should be able to: Explain object-oriented programming and some of its concepts Differentiate between classes and

More information

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017 Your Name: Exam 2. CSC 121 MW Class Lecturer: Howard Rosenthal April 26, 2017 The following questions (or parts of questions) in numbers 1-7 are all worth 3 points each. 1. Answer the following as true

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

Goals of this Lecture

Goals of this Lecture C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing

More information

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS Computers process information and usually they need to process masses of information. In previous chapters we have studied programs that contain a few variables

More information

(Refer Slide Time: 06:01)

(Refer Slide Time: 06:01) Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 28 Applications of DFS Today we are going to be talking about

More information

int a; int b = 3; for (a = 0; a < 8 b < 20; a++) {a = a + b; b = b + a;}

int a; int b = 3; for (a = 0; a < 8 b < 20; a++) {a = a + b; b = b + a;} 1. What does mystery(3) return? public int mystery (int n) { int m = 0; while (n > 1) {if (n % 2 == 0) n = n / 2; else n = 3 * n + 1; m = m + 1;} return m; } (a) 0 (b) 1 (c) 6 (d) (*) 7 (e) 8 2. What are

More information

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper

More information

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming Exam 1 Prep Dr. Demetrios Glinos University of Central Florida COP3330 Object Oriented Programming Progress Exam 1 is a Timed Webcourses Quiz You can find it from the "Assignments" link on Webcourses choose

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

The Sun s Java Certification and its Possible Role in the Joint Teaching Material The Sun s Java Certification and its Possible Role in the Joint Teaching Material Nataša Ibrajter Faculty of Science Department of Mathematics and Informatics Novi Sad 1 Contents Kinds of Sun Certified

More information

Answer Key. 1. General Understanding (10 points) think before you decide.

Answer Key. 1. General Understanding (10 points) think before you decide. Answer Key 1. General Understanding (10 points) Answer the following questions with yes or no. think before you decide. Read the questions carefully and (a) (2 points) Does the interface java.util.sortedset

More information

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS These are sample pages from Kari Laitinen s book "A Natural Introduction to Computer Programming with Java". For more information, please visit http://www.naturalprogramming.com/javabook.html CHAPTER 5

More information

Array. Array Declaration:

Array. Array Declaration: Array Arrays are continuous memory locations having fixed size. Where we require storing multiple data elements under single name, there we can use arrays. Arrays are homogenous in nature. It means and

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and

More information

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 142 Su 04 Computer Programming 1 - Java. Objects Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request

More information

Introduction Unit 4: Input, output and exceptions

Introduction Unit 4: Input, output and exceptions Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.

More information

1007 Imperative Programming Part II

1007 Imperative Programming Part II Agenda 1007 Imperative Programming Part II We ve seen the basic ideas of sequence, iteration and selection. Now let s look at what else we need to start writing useful programs. Details now start to be

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

Chapter 6. Arrays. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays

Chapter 6. Arrays. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays Chapter 6 Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays Chapter 6 Java: an Introduction to Computer Science & Programming

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #34 Function with pointer Argument (Refer Slide Time: 00:05) So, here is the stuff that we have seen about pointers.

More information

Arrays and ArrayLists. Ananda Gunawardena

Arrays and ArrayLists. Ananda Gunawardena Arrays and ArrayLists Ananda Gunawardena Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages Arrays allow us to store arbitrary sized sequences

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved. Chapter 12 Pointers and Arrays 1 Introduction C allows us to perform arithmetic addition and subtraction on pointers to array elements. This leads to an alternative way of processing arrays in which pointers

More information

Exception-Handling Overview

Exception-Handling Overview م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the

More information

Points To Remember for SCJP

Points To Remember for SCJP Points To Remember for SCJP www.techfaq360.com The datatype in a switch statement must be convertible to int, i.e., only byte, short, char and int can be used in a switch statement, and the range of the

More information

CSCI 355 Lab #2 Spring 2007

CSCI 355 Lab #2 Spring 2007 CSCI 355 Lab #2 Spring 2007 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

More information

Goal. Generic Programming and Inner classes. Minor rewrite of linear search. Obvious linear search code. Intuitive idea of generic linear search

Goal. Generic Programming and Inner classes. Minor rewrite of linear search. Obvious linear search code. Intuitive idea of generic linear search Goal Generic Programming and Inner classes First version of linear search Input was array of int More generic version of linear search Input was array of Comparable Can we write a still more generic version

More information

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

Intermediate Code Generation

Intermediate Code Generation Intermediate Code Generation In the analysis-synthesis model of a compiler, the front end analyzes a source program and creates an intermediate representation, from which the back end generates target

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch

More information

M/s. Managing distributed workloads. Language Reference Manual. Miranda Li (mjl2206) Benjamin Hanser (bwh2124) Mengdi Lin (ml3567)

M/s. Managing distributed workloads. Language Reference Manual. Miranda Li (mjl2206) Benjamin Hanser (bwh2124) Mengdi Lin (ml3567) 1 M/s Managing distributed workloads Language Reference Manual Miranda Li (mjl2206) Benjamin Hanser (bwh2124) Mengdi Lin (ml3567) Table of Contents 1. Introduction 2. Lexical elements 2.1 Comments 2.2

More information

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of dynamic memory allocation of variables and objects in a C++ program.

More information

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

More information

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

COMP-202: Foundations of Programming. Lecture 26: Image Manipulation; Wrap-Up Jackie Cheung, Winter 2015

COMP-202: Foundations of Programming. Lecture 26: Image Manipulation; Wrap-Up Jackie Cheung, Winter 2015 COMP-202: Foundations of Programming Lecture 26: Image Manipulation; Wrap-Up Jackie Cheung, Winter 2015 Announcements Assignment 6 due Tue Apr 14 at 11:59pm Final is scheduled for Apr 29, 6pm 9pm Please

More information

Nested Loops. A loop can be nested inside another loop.

Nested Loops. A loop can be nested inside another loop. Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

ADTs, Arrays, Linked Lists

ADTs, Arrays, Linked Lists 1 ADTs, Arrays, Linked Lists Outline and Required Reading: ADTs ( 2.1) Using Arrays ( 3.1) Linked Lists ( 3.2, 3.3, 3.4) CSE 2011, Winter 2017 Instructor: N. Vlajic Data Type 2 A data type is a classification

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

Programming for Electrical and Computer Engineers. Pointers and Arrays

Programming for Electrical and Computer Engineers. Pointers and Arrays Programming for Electrical and Computer Engineers Pointers and Arrays Dr. D. J. Jackson Lecture 12-1 Introduction C allows us to perform arithmetic addition and subtraction on pointers to array elements.

More information

Computer Science 1 Bh

Computer Science 1 Bh UNIVERSITY OF EDINBURGH course CS0077 FACULTY OF SCIENCE AND ENGINEERING DIVISION OF INFORMATICS SCHOOL OF COMPUTER SCIENCE Computer Science 1 Bh Degree Examination Date: Saturday 25th May 2002 Time: 12:00

More information

Computer Science is...

Computer Science is... Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic

More information

6.001 Notes: Section 17.5

6.001 Notes: Section 17.5 6.001 Notes: Section 17.5 Slide 17.5.1 Now, let's look at one example in which changing the evaluation model allows us to explore a very different kind of computational problem. Our goal is to show how

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Arrays. Chapter Arrays What is an Array?

Arrays. Chapter Arrays What is an Array? Chapter 8 Arrays 81 Arrays 811 What is an Array? To motivate why we might be interested in using arrays, let us implement an app that creates a collection of doubles We will keep track of the number of

More information