Download presentation
Presentation is loading. Please wait.
Published byLeslie Ruth Bryant Modified over 9 years ago
1
Rina Zviel-Girshin @ARC1 System development with Java Instructors: Rina Zviel-Girshin Lecture 5
2
Rina Zviel-Girshin @ARC2 Overview Arrays Exceptions
3
Rina Zviel-Girshin @ARC3 Arrays An array is a data structure consisting of a numbered list of items. All the items are of the same type. Types of elements in an array can be: primitive type object references An array contains a number of variables. An empty array is an array with number of variables equal to zero.
4
Rina Zviel-Girshin @ARC4 Indexing The variables contained in an array have no names. They are referenced by array access expressions called index that uses nonnegative integer values. The array variable itself called element of the array.
5
Rina Zviel-Girshin @ARC5 Array length The number of elements in the array is called the length of the array. The array with n elements is called n length array. The element of the array are referenced using integer indices from 0 to n-1. Example:
6
Rina Zviel-Girshin @ARC6 Declaring arrays There are two different methods for declaring arrays. Syntax: type Array_name[]; type[] Array_name; The difference is the place of the brackets.
7
Rina Zviel-Girshin @ARC7 Arrays type Types of an array can be: primitive type objects Examples int grades[]; // array of integers int[] grades; String names[]; // array of strings String[] names;
8
Rina Zviel-Girshin @ARC8 Arrays type double average[]; // array of doubles double[] average; The advantage of the second method is when several arrays of the same type have to be declared. Example int[] array1,array2,array3;
9
Rina Zviel-Girshin @ARC9 Creating arrays After the declaration of an array variable the array object can be created. Java arrays are objects. This has several consequences: arrays are created using the new operator no variable can ever hold an array - a variable can only refer to an array
10
Rina Zviel-Girshin @ARC10 Creating arrays (cont) Syntax: Array_name = new type[size]; Size is an integer that represents the number of elements the array holds (the length of the array). Index of first array element is 0. Index of the last array element is size-1.
11
Rina Zviel-Girshin @ARC11 Creating arrays (cont) Example: int intArray[]; intArray=new int[10]; Once array has been created you can’t change it’s size. The constant called length holds the size of the array. Syntax: arrayName.length The constant intArray.length contains the value 10.
12
Rina Zviel-Girshin @ARC12 Creating arrays (cont) In Java, a newly created array is always filled with a known, default value: zero for numbers false for boolean the character with Unicode number zero for char ‘\0’ null for objects
13
Rina Zviel-Girshin @ARC13 Example int my[]; int my= new int[5]; my holds a reference to an array of 5 integers with default values equal to zero. An array object also contains my.length, which holds the number of items in the array.
14
Rina Zviel-Girshin @ARC14 Example int my[]; int my= new int[5];
15
Rina Zviel-Girshin @ARC15 Declaration Declaration and creation of the array can be done together. Syntax: type[] Array_name = new type[size]; Example int [] grades = new int[10];
16
Rina Zviel-Girshin @ARC16 Array initialization Another way to create an array is to explicitly define the array elements, separated by commas within parentheses. int[] grades = { 90, 78, 80, 95, 89, 80, 69, 93}; String capitals[] = {“London”,“Berlin”, “Jerusalem”}; In this last example: array of String objects was declared and created the array contains 3 elements The explicit definition of an array is also called initialization of the array.
17
Rina Zviel-Girshin @ARC17 Manipulating arrays Array elements are accessed by specifying the name of the array and it’s place. Syntax: ArrayName[index] Example grades[1] In this example we refer to value 78 (which is the second element of the array grades).
18
Rina Zviel-Girshin @ARC18 Manipulating arrays Array manipulations are done through its elements. for (int i = 0; i < Array_name.length; i++) {... // process Array_name[i] } Example int numArray = new int[10]; for(int j=0; j <numArray.length; j++) numArray[j] = j; or: String capitals[] = {“London”, “Berlin”, “Jerusalem”}; for (int i = 0; i < capitals.length; i++) System.out.println(capitals[i] );
19
Rina Zviel-Girshin @ARC19 Manipulating arrays Java has automatic bounds checking to make sure that the bounds of the array are not broken. public class ArrayDemo{ public static void main(String[] args) { int[] a={1,2,3}; try { for(int j=0; j<5; j++)System.out.println(a[j]);} catch(ArrayIndexOutOfBoundsException e) { System.out.print(“Invalid array length");} }} problem
20
Rina Zviel-Girshin @ARC20 Arrays of Objects Type of an array can be object reference. Example String capitals[] = {“London”, “Berlin”, “Jerusalem”}; Each array element holds a reference to the String object.
21
Rina Zviel-Girshin @ARC21 Arrays as Parameters A reference to an array can be passed to method as parameter. As usual a copy of the reference is passed to method. Changing an array element in the method changes the original one. Array element can be passed as parameter as well.
22
Rina Zviel-Girshin @ARC22 Example // public class DArray { public static void doubleArray(int[] array) { for(int j=0;j<array.length;j++) array[j]*=2; } } A reference to an array can be a parameter
23
Rina Zviel-Girshin @ARC23 Example import DArray; public class DArrayTest {public static void main(String[] args) { int[] array={1,2,3,4}; for(int j=0;j<array.length;j++) System.out.print(array[j]+" "); System.out.println("\nAfter doubling :"); DArray.doubleArray(array); for(int j=0;j<array.length;j++) System.out.print(array[j]+" "); } Array element can be passed as parameter A reference to an array can be a parameter
24
Rina Zviel-Girshin @ARC24 Multidimensional arrays Arrays can have several dimensions and called multidimensional arrays. Multidimensional arrays created by declaring arrays of arrays. Brackets are represent each dimension in the array. Syntax: type Array_name[]…[] = new type[size]…[size]; Example: double cube[][][]=new double[5][5][5]; int multiArray[][] = new int[10][8];
25
Rina Zviel-Girshin @ARC25 Two-dimensional arrays Two-dimensional array has values in two dimensions, often called rows and columns. A two-dimensional array can be created as a list of arrays, one for each row in the array. Example int[][] A = { { 1, 0, 12, 11 }, { 7, -3, 2, 5 }, { -5, -2, 2, 9 } };
26
Rina Zviel-Girshin @ARC26 Two-dimensional arrays Access to an array element is made by specifying the name of the array and index of each dimension. Example: int A=new int[5][6]; A[1][3]=2; The multidimensional array is represented as array of references to array objects. The notation int[2][3] can then be taken to describe a grid of integers with 2rows and 3 columns.
27
Rina Zviel-Girshin @ARC27 Example int[] my={{56, 3, -4}, {4, 5, 63}}; my holds a reference to an array of 2 elements Each element is a reference to an array of 3 int
28
Rina Zviel-Girshin @ARC28 Two-dimensional arrays Each dimension has its own length constant. The number of element in the i-th row of the array Name can be found in following way: Name[i-1].length int x=my[1].length;// x is 3 Manipulations can be performed with two- dimensional array.
29
Rina Zviel-Girshin @ARC29 Example public class MDArray { public static void main(String[] args) { int[][] array={{1,2,3},{4,7},{8,9,12}}; for(int row=0;row<array.length;row++) {for(int col=0;col<array[row].length;col++) System.out.print(array[row][col]+" "); System.out.println(); }
30
Rina Zviel-Girshin @ARC30 Example /** * A matrix of real numbers. */ public class Matrix { // The elements of the matrix private double[][] elements; /** * Constructs a new matrix from a table of values */ public Matrix(double[][] elements) { //... }
31
Rina Zviel-Girshin @ARC31 Example /** * Returns the number of rows of the matrix. */ public int numberOfRows() { return elements.length; } /** * Returns the number of columns of the matrix. */ public int numberOfColumns() { return elements[0].length; }
32
Rina Zviel-Girshin @ARC32 Example /** * Returns the matrix resulting from multiplying * this matrix with another. * @exception IllegalArgumentException If the * dimension of the given matrix is not suitable.*/ public Matrix multiply(Matrix a) { int n = numberOfRows(); int m = numberOfColumns(); int l = a.numberOfColumns(); if (m != a.numberOfRows()) { throw new IllegalArgumentException(); }
33
Rina Zviel-Girshin @ARC33 Example double[][] result = new double[n][l]; for (int i=0; i<n; i++) { for (int j=0; j<l; j++) { for (int k=0; k<m; k++) { result[i][j] += elements[i][k]*elements[k][j]; } return new Matrix(result); }
34
Rina Zviel-Girshin @ARC34 Example Matrix a,b,c; a = new Matrix(aElements); b = new Matrix(bElements); c = a.multiply(b); for (int i=0; i<c.numberOfRows(); i++) { for (int j=0; j<c.numberOfColumns(); j++) { System.out.print(c.getElement(i,j)+” ”); } System.out.println(); }
35
Rina Zviel-Girshin @ARC35 Exceptions Run-time errors are an eventuality that all programs may face: – coding errors – erroneous inputs Java provides a sophisticated mechanism called exceptions: – means of communicating run-time errors – means of user-code dealing with such errors
36
Rina Zviel-Girshin @ARC36 Well written programs Well written programs can minimise the occurrence of run-time errors but: – Users are particularly good at finding new ways to break systems (extraordinary inputs) What do we mean by well written programs? Checking all potential errors before each operation. But it is wasteful, painstaking, obscure and error prone itself.
37
Rina Zviel-Girshin @ARC37 Exceptions When a program violates the semantic constraints of the Java programming language JVM signals this error to the program as an exception. The word "exception" is meant to be more general than "error." It includes any circumstance that disturb the normal flow of control of the program. Exception defines erroneous or not in control flow.
38
Rina Zviel-Girshin @ARC38 Exceptions Java provides a method for dealing with possible errors that can occur while a program is running. The method is referred to as exception- handling. An exceptional occurrence in the execution of a program – disrupts the normal flow of execution – can be caught and dealt with by the program
39
Rina Zviel-Girshin @ARC39 Exception examples Some examples Trying to divide an integer by zero. An error occurs in loading or linking part of the program. Trying to read a file that is inaccessible or doesn’t exist. A ccessing outside an array's bounds.
40
Rina Zviel-Girshin @ARC40 Other languages Some programming languages and their implementations react to such errors by peremptorily terminating the program. Other programming languages allow an implementation to react in an arbitrary or unpredictable way. A crashed program will often crash the entire system and freeze the computer until it is restarted.
41
Rina Zviel-Girshin @ARC41 Exceptions Java specifies that an exception will be thrown when semantic constraints are violated. Java will cause a non-local transfer of control from the point where the exception occurred to a point that can be specified by the programmer. When this happens the program is in danger of crashing.
42
Rina Zviel-Girshin @ARC42 Exceptions The crash can be avoided if the exception is caught and handled in some way. Having a program crash simply means that it terminates abnormally and prematurely. The Java interpreter catches any exceptions that are not caught by the program. The interpreter responds by terminating the program.
43
Rina Zviel-Girshin @ARC43 Example public class ArrayDemo{ public static void main(String[] args) { int[] a={1,2,3}; try { for(int j=0; j<5; j++)System.out.println(a[j]);} catch(ArrayIndexOutOfBoundsException e) { System.out.print(“Invalid array length");} }
44
Rina Zviel-Girshin @ARC44 Exception hierarchy example Often exceptions fall into categories or groups. Example of Array exceptions: Exception RuntimeException IlligalArgumentException NegativeArraySizeException ArrayIndexOutOfBoundsException
45
Rina Zviel-Girshin @ARC45 Exception types Exceptions are an object ( instances of a class derived from java.lang.Throwable) ArrayIndexOutOfBoundsException e This object can contain information (in its instance variables) from the point where the exception occurred to the point where it is caught and handled. This information typically includes an error message describing what happened to cause the exception, but it could also include other data and methods. System.out.print(“Invalid array length");
46
Rina Zviel-Girshin @ARC46 Example /** * Constructs a new Rectangle. * @param width The new width. * @param height The new height. * @exception IllegalArgumentException if the given width * and heights have illegal value. */ public Rectangle(int width, int height) { if(width<0 || height<0) { throw new IllegalArgumentException(“Rectangle must have positive width and heights!”);} this.width=width; this.height=height; } Error message
47
Rina Zviel-Girshin @ARC47 Throw keyword throw someThrowableObject; The keyword throw causes a number of relatively magical things to happen. –First an object that represents the error condition is created (usually using new keyword). –The resulting reference is given to throw. –The regular flow of the program stops. –The object is returned from the method, even though that object type isn’t normally what the method is designed to return.
48
Rina Zviel-Girshin @ARC48 Example class RectangleProblem{ public static void main(String[] args) { //… Rectangle r=new Rectangle(-3,5); int p=r.perimeter(); System.out.println(“Perimeter is “+p); //… } Width should be positive Method crashes
49
Rina Zviel-Girshin @ARC49 Example class RectangleProblem{ public static void main(String[] args) { //… Rectangle r=new Rectangle(-3,5); int p=r.perimeter(); System.out.println(“Perimeter is “+p); //… } Width should be positive public Rectangle(int width, int height) { if(width<0 || height<0) { throw new IllegalArgumentException (“Rectangle must have positive width and heights!”);} this.width=width; this.height=height;} width = -3 Method crashes
50
Rina Zviel-Girshin @ARC50 Declaring for Exceptions Before you can catch an exception, some Java code somewhere must throw one. A method can declare exceptions it may throw. The declaration for exceptions a method can throw is done using the throws keyword. The user of the method is warned against possible exceptions this method can throw.
51
Rina Zviel-Girshin @ARC51 Declaring Exceptions Using ‘throws’ public void setTime(int hour, int minute, int second) throws IllegalArgumentException { if (hour 59 || minute 59 || second 59) { throw new IllegalArgumentException(“Invalid time”); } this.hour = hour; //... }
52
Rina Zviel-Girshin @ARC52 The try.. catch block If inside a method or another method within this method an exception is thrown that method will exit in the process of throwing. If you don’t want a throw to exit the method, you can set up a special block within that method to capture the exception. This is called the try/catch block. Syntax: try { // code statements } catch (ExceptionType e) { // handler statements}
53
Rina Zviel-Girshin @ARC53 The try.. catch block The idea is to tell the computer to "try" to execute some statements. If try succeeds catch statements are ignored. But if an exception is thrown by any of the statements within the try block, the rest of the statements are skipped and catch block is executed. Each catch clause has an associated exception type. When an exception occurs, processing continues at the first catch clause that matches the exception type.
54
Rina Zviel-Girshin @ARC54 The try.. catch block With exception handling, you put everything in a try block and capture all the exceptions in one place. try { //some code } catch (ExceptionType1 e1) { // handler code } catch (ExceptionType2 e2) { // handler code } … catch (ExceptionTypeN eN) { // handler code } This means your code is a lot easier to write and easier to read because the goal of the code is not confused with the error checking.
55
Rina Zviel-Girshin @ARC55 Example public static void main(String[] args) { //… try{ Rectangle r=new Rectangle(-3,5); int p=r.perimeter(); System.out.println(“Perimeter is “+p); //… } catch(NoSuchMethodException nsme) { //…} catch(IllegalArgumentException ia) {System.out.println(“Rectangle must have positive width and heights!”);} } Width should be positive
56
Rina Zviel-Girshin @ARC56 Exception propagation After a method throws an exception, the runtime system leaps into action to find someone to handle the exception. The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error occurred. The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate exception handler.
57
Rina Zviel-Girshin @ARC57 Any Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.