570 likes | 698 Views
System development with Java. Instructors: Rina Zviel-Girshin Lecture 5. Overview. Arrays Exceptions. 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
E N D
System development with Java Instructors: Rina Zviel-Girshin Lecture 5 Rina Zviel-Girshin @ARC
Overview • Arrays • Exceptions Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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: Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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; Rina Zviel-Girshin @ARC
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; Rina Zviel-Girshin @ARC
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 Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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 Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
Example int my[]; int my= new int[5]; Rina Zviel-Girshin @ARC
Declaration • Declaration and creation of the array can be done together. Syntax: type[] Array_name = new type[size]; Example int [] grades = new int[10]; Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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). Rina Zviel-Girshin @ARC
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] ); Rina Zviel-Girshin @ARC
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 Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
Example A reference to an array can be a parameter // public class DArray { public static void doubleArray(int[] array) { for(int j=0;j<array.length;j++) array[j]*=2; } } Rina Zviel-Girshin @ARC
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 Rina Zviel-Girshin @ARC
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]; Rina Zviel-Girshin @ARC
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 } }; Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
Example Each element is a reference to an array of 3 int int[] my={{56, 3, -4}, {4, 5, 63}}; my holds a reference to an array of 2 elements Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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(); } } } Rina Zviel-Girshin @ARC
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) { // ... } Rina Zviel-Girshin @ARC
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; } Rina Zviel-Girshin @ARC
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(); } Rina Zviel-Girshin @ARC
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); } Rina Zviel-Girshin @ARC
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(); } } } Rina Zviel-Girshin @ARC
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 Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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 Rina Zviel-Girshin @ARC
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. • Accessing outside an array's bounds. Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC
Exceptions • The crash can be avoided if the exception is caught and handled in some way. • Having a program crashsimply 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. Rina Zviel-Girshin @ARC
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");} } } Rina Zviel-Girshin @ARC
Exception RuntimeException IlligalArgumentException NegativeArraySizeException ArrayIndexOutOfBoundsException Exception hierarchy example • Often exceptions fall into categories or groups. • Example of Array exceptions: Rina Zviel-Girshin @ARC
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"); Rina Zviel-Girshin @ARC
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 Rina Zviel-Girshin @ARC
Throw keyword throw someThrowableObject; • The keyword throwcauses 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. Rina Zviel-Girshin @ARC
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 Rina Zviel-Girshin @ARC
Example Width should be positive 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 = -3 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;} Method crashes Rina Zviel-Girshin @ARC
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. Rina Zviel-Girshin @ARC