Week10 Array List Java Exceptions and Java IO

  • Slides: 62
Download presentation
Week-10 Array List, Java Exceptions, and Java I/O 1

Week-10 Array List, Java Exceptions, and Java I/O 1

Lecture Outline • Array. List – What is it – How it works •

Lecture Outline • Array. List – What is it – How it works • Java Exceptions – What is it – Error-handling overview – Try-catch • Java I/O – Data storage – I/O overview – Flies and Streams 2

What is an Array List? • Array. List is – a class in the

What is an Array List? • Array. List is – a class in the standard Java libraries that can hold a sequence of objects of any type – an object that can grow and shrink while your program is running – In general, an Array. List serves the same purpose as an array, except that an Array. List can change length while the program is running (normal arrays have a fixed length once they have been created) 3

How Array. List Class works? • The Array. List class is implemented using an

How Array. List Class works? • The Array. List class is implemented using an array as a private instance variable – Once this hidden array becomes full, a new larger hidden array is created and the data is transferred to this new array 4

How to create an Array. List? • The following must be imported first import

How to create an Array. List? • The following must be imported first import java. util. Array. List; • An Array. List is then created and named in the same way as object of any class, but we need to specify the type of the object as follows: Array. List<Type> a = new Array. List<Type>(); • E. g. , Array. List<String> s = new Array. List<String>(); Array. List<Integer> i = new Array. List<Integer>(); 5

Creating an Array. List of type String • When creating an Array. List, an

Creating an Array. List of type String • When creating an Array. List, an initial capacity can also be specified • The following code creates an Array. List that stores objects of type String with an initial capacity of 10 items Array. List<String> s = new array. List<String>(10); • Note that, specifying an initial capacity does not limit the size to which an Array. List can eventually grow 6

Some Array. List methods boolean void boolean Type int boolean add(Type e) Appends the

Some Array. List methods boolean void boolean Type int boolean add(Type e) Appends the specified element to the end of this list. add(int index, Type element) Inserts the specified element at the specified position in this list. clear() Removes all of the elements from this list. contains(Type e) Returns true if this list contains the specified element. get(int index) Returns the element at the specified position in this list. index. Of(Type e) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. is. Empty() Returns true if this list contains no elements. 7

Array. List example import java. util. *; public class Test. Array. List { public

Array. List example import java. util. *; public class Test. Array. List { public static void main(String args[]) { Array. List<String> s = new Array. List<String>(3); /*Elements are added to the array list*/ s. add("Timothy"); s. add("Tomas"); s. add("Bob"); s. add("Ann"); s. add("Susan"); /* Displaying array list elements */ System. out. println("The array list contains: "+s); } } Output: The array list contains: [Timothy, Tomas, Bob, Ann, Susan] 8

Array. List example contd. import java. util. *; public class Test. Array. List {

Array. List example contd. import java. util. *; public class Test. Array. List { public static void main(String args[]) { Array. List<String> s = new Array. List<String>(3); /*Elements are added to the array list*/ s. add("Timothy"); s. add("Tomas"); s. add("Bob"); s. add("Ann"); s. add("Susan"); s. add(0, "Adrian"); //Adding element at the given index /* Displaying array list elements */ System. out. println("The array list contains: "+s); } } Output: The array list contains: [Adrian, Timothy, Tomas, Bob, Ann, Susan] 9

Array. List example contd. import java. util. *; public class Test. Array. List {

Array. List example contd. import java. util. *; public class Test. Array. List { public static void main(String args[]) { Array. List<String> s = new Array. List<String>(3); /*Elements are added to the array list*/ s. add("Timothy"); s. add("Tomas"); s. add("Bob"); s. add("Ann"); s. add("Susan"); s. add(7, "Adrian"); //Adding element at the given index /* Displaying array list elements */ System. out. println("The array list contains: "+s); } } 10

Array. List example contd. import java. util. *; public class Test. Array. List {

Array. List example contd. import java. util. *; public class Test. Array. List { public static void main(String args[]) { Array. List<String> s = new Array. List<String>(3); /*Elements are added to the array list*/ s. add("Timothy"); s. add("Tomas"); s. add("Bob"); s. add("Ann"); s. add("Susan"); s. add(7, "Adrian"); //Adding element at the given index /* Displaying array list elements */ System. out. println("The array list contains: "+s); } } Output: Exception in thread "main" java. lang. Index. Out. Of. Bounds. Exception: Index: 7, Size: 5 11

Array. List example contd. import java. util. *; public class Test. Array. List {

Array. List example contd. import java. util. *; public class Test. Array. List { public static void main(String args[]) { Array. List<String> s = new Array. List<String>(3); /*Elements are added to the array list*/ s. add("Timothy"); s. add("Tomas"); s. add("Bob"); s. add("Ann"); s. add("Susan"); s. add(0, "Adrian"); //Adding element at the given index System. out. println("The array list contains: "+s); s. remove(2); //Removing the element at position 2 System. out. println("After removing an element"); System. out. println("The array list contains: "+s); } Output: } The array list contains: [Adrian, Timothy, Tomas, Bob, Ann, Susan] After removing an element The array list contains: [Adrian, Timothy, Bob, Ann, Susan] 12

Java Exceptions 13

Java Exceptions 13

Exception • Exception—an indication of a problem that occurs during a program’s execution. –

Exception • Exception—an indication of a problem that occurs during a program’s execution. – The name “exception” implies that the problem occurs infrequently. • With exception handling, a program can continue executing (rather than terminating) after dealing with a problem. • Mission-critical or business-critical computing. • Robust and fault-tolerant programs (i. e. , programs that can deal with problems asthey arise and continue executing). 14

Exception Handling • Java has a predefined set of exceptions and errors that can

Exception Handling • Java has a predefined set of exceptions and errors that can occur during execution • A program can deal with an exception in one of three ways: – Simply ignore it – Handle it where it occurs – Handle it an another place in the program • The manner in which an exception is processed is an important design consideration 15

Exception Handling • Array. Index. Out. Of. Bounds. Exception occurs when an attempt is

Exception Handling • Array. Index. Out. Of. Bounds. Exception occurs when an attempt is made to access an element past either end of an array. • Class. Cast. Exception occurs when an attempt is made to cast an object that does not have an is-a relationship with the type specified in the cast operator. • A Null. Pointer. Exception occurs when a null reference is used where an object is expected. • Only classes that extend Throwable (package java. lang) directly or indirectly can be used with exception handling. 16

Error-handling overview • One way to handle program errors is to test conditions to

Error-handling overview • One way to handle program errors is to test conditions to determine how program execution should proceed. • Consider the following pseudocode: Perform a task If the preceding task did not execute correctly Perform error processing Perform next task • Intermixing program and error-handling logic in this manner can make programs difficult to read, modify, maintain and debug—especially in large applications. 17

Error-handling overview contd. • Exception handling enables us to remove errorhandling code from the

Error-handling overview contd. • Exception handling enables us to remove errorhandling code from the “main line” of program execution – Improves program clarity – Enhances modifiability • Handle any exceptions we choose – All exceptions of a certain type – All exceptions of a group of related types (i. e. , related through a superclass). • Such flexibility reduces the likelihood that errors will be overlooked, thus making programs more robust. 18

Exceptions are thrown • Exceptions are thrown (i. e. , the exception occurs) when

Exceptions are thrown • Exceptions are thrown (i. e. , the exception occurs) when a method detects a problem and is unable to handle it. • Stack trace—information displayed when an exception occurs and is not handled. • Information includes: – The name of the exception in a descriptive messagethat indicates the problem that occurred – The method-call stack (i. e. , the call chain) at the time it occurred. Represents the path of execution that led to the exception method by method. • This information helps us debug the program. 19

Example: divide by zero • Java does not allow division by zero in integer

Example: divide by zero • Java does not allow division by zero in integer arithmetic. – throws an Arithmetic. Exception. • However, Java does allow division by zero with floatingpoint values. – Such a calculation results in the value positive or negative infinity – If 0. 0 is divided by 0. 0, the result is Na. N (not a number), which is represented as a floating-point value that displays as Na. N 20

import java. util. Scanner; public class Test. Divide. By. Zero { public static int

import java. util. Scanner; public class Test. Divide. By. Zero { public static int quotient(int numerator, int denominator){ //possibly division by zero return numerator/denominator; } public static void main(String []args){ Scanner s = new Scanner (System. in); //keyboard input System. out. println("Enter an integer numerator: "); int numerator = s. next. Int(); System. out. println("Enter an integer denominator: "); int denominator = s. next. Int(); int result = quotient(numerator, denominator); System. out. println("Result: "+numerator+"/"+denominator+ " = "+result); } } 21

Enter an integer numerator: 200 Enter an integer denominator: 10 Result: 200/10 = 20

Enter an integer numerator: 200 Enter an integer denominator: 10 Result: 200/10 = 20 22

Enter an integer numerator: 200 Enter an integer denominator: 0 Exception in thread "main"

Enter an integer numerator: 200 Enter an integer denominator: 0 Exception in thread "main" java. lang. Arithmetic. Exception: / by zero at OOSD 1. Test. Divide. By. Zero. quotient(Test. Divide. By. Zero. java: 16) at OOSD 1. Test. Divide. By. Zero. main(Test. Divide. By. Zero. java: 25) C: UsersrzaApp. DataLocalNet. BeansCache8. 2executorsnippetsrun. xml: 53: Java returned: 1 BUILD FAILED (total time: 7 seconds) 23

Enter an integer numerator: 200 Enter an integer denominator: oosd Exception in thread "main"

Enter an integer numerator: 200 Enter an integer denominator: oosd Exception in thread "main" java. util. Input. Mismatch. Exception at java. util. Scanner. throw. For(Scanner. java: 864) at java. util. Scanner. next(Scanner. java: 1485) at java. util. Scanner. next. Int(Scanner. java: 2117) at java. util. Scanner. next. Int(Scanner. java: 2076) at OOSD 1. Test. Divide. By. Zero. main(Test. Divide. By. Zero. java: 24) C: UsersrzaApp. DataLocalNet. BeansCache8. 2executorsnippetsrun. xml: 53: Java returned: 1 BUILD FAILED (total time: 12 seconds) 24

Output observation • Last “at” line in the stack trace started the call chain.

Output observation • Last “at” line in the stack trace started the call chain. • Each line contains the class name and method followed by the file name and line number. • The top “at” line of the call chain indicates the throw point—the initial point at which the exception occurs. • As you read a stack trace top to bottom, the first “at” line that contains your class name and method name is typically the point in the program that led to the exception. 25

Exception handling example (1) import java. util. Scanner; import java. util. Input. Mismatch. Exception;

Exception handling example (1) import java. util. Scanner; import java. util. Input. Mismatch. Exception; public class Test. Divide. By. Zero { public static int quotient(int numerator, int denominator) throws Arithmetic. Exception { //possibly division by zero return numerator/denominator; } public static void main(String []args){ Scanner s = new Scanner (System. in); boolean looping = true; //keyboard input 26

do{ try{ System. out. println("Enter an integer numerator: "); int numerator = s. next.

do{ try{ System. out. println("Enter an integer numerator: "); int numerator = s. next. Int(); System. out. println("Enter an integer denominator: "); int denominator = s. next. Int(); int result = quotient(numerator, denominator); System. out. println("Result: "+numerator+"/"+denominator+ " = "+result); looping = false; } 27

catch(Arithmetic. Exception ex 1){ System. err. printf("n. Exception: %sn", ex 1); s. next. Line();

catch(Arithmetic. Exception ex 1){ System. err. printf("n. Exception: %sn", ex 1); s. next. Line(); //discard input so user can try again System. out. println("Enter non-zero denominator, try again"); } catch(Input. Mismatch. Exception ex 2){ System. err. printf("n. Exception: %sn", ex 2); s. next. Line(); //discard input so user can try again System. out. println("Enter integer, try again"); } }while(looping); } } 28

Enter an integer numerator: 200 Enter an integer denominator: 0 Enter non-zero denominator, try

Enter an integer numerator: 200 Enter an integer denominator: 0 Enter non-zero denominator, try again Exception: java. lang. Arithmetic. Exception: / by zero Enter an integer numerator: 200 Enter an integer denominator: 10 Result: 200/10 = 20 29

Enter an integer numerator: 200 Enter an integer denominator: oosd Enter integer, try again

Enter an integer numerator: 200 Enter an integer denominator: oosd Enter integer, try again Exception: java. util. Input. Mismatch. Exception Enter an integer numerator: 200 Enter an integer denominator: 10 Result: 200/10 = 20 30

Try/catch blocks try block encloses – code that might throw an exception – code

Try/catch blocks try block encloses – code that might throw an exception – code that should not execute if an exception occurs Consists of the keyword try followed by a block of code enclosed in curly braces. 31

Try/catch blocks contd. • catch block catches and handles an exception. – begins with

Try/catch blocks contd. • catch block catches and handles an exception. – begins with the keyword catch and is followed by an exception parameter in parentheses and a block of code enclosed in curly braces. • At least one catch block must immediately follow the try block. • The exception parameter identifies the exception type the handler can process. – The parameter’s name enables the catch block to interact with a caught exception object. 32

Try/catch blocks contd. • When an exception occurs in a try block, the catch

Try/catch blocks contd. • When an exception occurs in a try block, the catch block that executes is the first one whose type matches the type of the exception that occurred. • Use the System. err (standard error stream) object to output error messages. – By default, displays data to the command prompt. 33

Try/catch blocks contd. • Uncaught exception—one for which there are no matching catch blocks.

Try/catch blocks contd. • Uncaught exception—one for which there are no matching catch blocks. • Recall that previous uncaught exceptions caused the application to terminate early. – This does not always occur as a result of uncaught exceptions. • Java uses a multithreaded model of program execution. – Each thread is a parallel activity. – One program can have many threads. – If a program has only one thread, an uncaught exception will cause the program to terminate. – If a program has multiple threads, an uncaught exception will terminate only the thread where the exception occurred 34

Try/catch blocks contd. • If an exception occurs in a try block, the try

Try/catch blocks contd. • If an exception occurs in a try block, the try block terminates immediately and program control transfers to the firstmatching catch block. • After the exception is handled, control resumes after the last catch block. 35

Try/catch blocks contd. • If no exceptions are thrown in a try block, the

Try/catch blocks contd. • If no exceptions are thrown in a try block, the catch blocks are skipped and control continues with the first statement after the catch blocks – We’ll learn about another possibility when we discuss the finally block in the later slides. • The try block and its corresponding catch and/or finally blocks form a try statement. 36

finally block • The finally block is used for resource deallocation. – Placed after

finally block • The finally block is used for resource deallocation. – Placed after the last catch block. ©Abdur Rakib 2017 try{ statements resource-acquisition statements } catch{ } … catch{ } finally{ statements resource-release statements } 37

finally block • finally block will execute whether or not an exception is thrown

finally block • finally block will execute whether or not an exception is thrown in the corresponding try block. • finally block will execute if a try block exits by using a return, break or continue statement or simply by reaching its closing right brace. • finally block will not execute if the application terminates immediately by calling method System. exit. 38

Exception handling example (2) import java. util. Scanner; import java. util. Input. Mismatch. Exception;

Exception handling example (2) import java. util. Scanner; import java. util. Input. Mismatch. Exception; public class Test. Divide. By. Zero { public static int quotient(int numerator, int denominator) throws Arithmetic. Exception { return numerator/denominator; //possibly division by zero } public static void main(String []args){ Scanner s = new Scanner (System. in); //keyboard input boolean looping = true; 39

do{ try{ System. out. println("Enter an integer numerator: "); int numerator = s. next.

do{ try{ System. out. println("Enter an integer numerator: "); int numerator = s. next. Int(); System. out. println("Enter an integer denominator: "); int denominator = s. next. Int(); int result = quotient(numerator, denominator); System. out. println("Result: "+numerator+"/"+denominator+ " = "+result); looping = false; } 40

catch(Arithmetic. Exception ex 1){ System. err. printf("n. Exception: %sn", ex 1); s. next. Line();

catch(Arithmetic. Exception ex 1){ System. err. printf("n. Exception: %sn", ex 1); s. next. Line(); //discard input so user can try again System. out. println("Enter non-zero denominator, try again"); } catch(Input. Mismatch. Exception ex 2){ System. err. printf("n. Exception: %sn", ex 2); s. next. Line(); //discard input so user can try again System. out. println("Enter integer, try again"); } finally{ System. out. println("Finally block has been executed!"); } }while(looping); } } 41

Enter an integer numerator: 200 Enter an integer denominator: 10 Result: 200/10 = 20

Enter an integer numerator: 200 Enter an integer denominator: 10 Result: 200/10 = 20 Finally block has been executed! 42

Enter an integer numerator: 200 Enter an integer denominator: 0 Enter non-zero denominator, try

Enter an integer numerator: 200 Enter an integer denominator: 0 Enter non-zero denominator, try again Exception: java. lang. Arithmetic. Exception: / by zero Finally block has been executed! Enter an integer numerator: 200 Enter an integer denominator: 10 Result: 200/10 = 20 Finally block has been executed! 43

Java I/O 44

Java I/O 44

Data storage • Data stored in variables and arrays is temporary – It’s lost

Data storage • Data stored in variables and arrays is temporary – It’s lost when a local variable goes out of scope or when the program terminates • For long-term retention of data, computers use files. • Computers store files on secondary storage devices – hard disks, optical disks, flash drives and magnetic tapes. • Data maintained in files is persistent data because it exists beyond the duration of program execution. 45

Personel file Database Department file (Project database) Payroll file Files Peter Miller 10 -7

Personel file Database Department file (Project database) Payroll file Files Peter Miller 10 -7 -2012 Reinhard Wilhelm 15 -09 -2000 Rowan Atkinson 17 -5 -1997 Records Peter Miller 10 -7 -2012 Fields Miller Characters (bytes) 01001101 1 Bit (Personnel file) (Record containing last name, first name, date of hire) (Last name field) (Letter ‘M’ in ASCII 077) Data hierarchy 46

Data representation terminology • Database management system (DBMS) a collection of programs designed to

Data representation terminology • Database management system (DBMS) a collection of programs designed to create and manage databases • Database a collection of integrated and related files • File a collection of related records • Record a collection of related fields • Field a group of characters • Character basic building block of information, represented by a byte • Bit the smallest data item in a computer can assume the value 0 or the value 1. 47

I/O Overview • I/O = Input/Output – In this context it is input to

I/O Overview • I/O = Input/Output – In this context it is input to and output from programs – Input could be from a keyboard or any other sources (e. g. , a file) – Output could be to display on screen or write to a file • Advantages of file I/O – permanent copy – output from one program can be input to another – input can be automated (rather than entered manually) 48

Streams • Stream is an object that – either sends data to its destination

Streams • Stream is an object that – either sends data to its destination (e. g. , screen, file, etc. ) – or that receives data from a source (e. g. , keyboard, file, etc. ) • It acts as a buffer between the data source and destination • Input stream is a stream that provides input to a program – System. in is an input stream • Output stream: a stream that accepts output from a program – System. out is an output stream • A stream connects a program to an I/O object – System. out connects a program to the screen – System. in connects a program to the keyboard 49

Flies and Streams • Java views a file as a stream of bytes •

Flies and Streams • Java views a file as a stream of bytes • File ends with end-of-file marker or aspecific byte number • File as a stream of bytes associated with an object – Java also associates streams with devices • System. in, System. out, and. System. err 50

Byte streams and Char streams Object Input. Stream Output. Stream Reader Writer Byte Stream

Byte streams and Char streams Object Input. Stream Output. Stream Reader Writer Byte Stream Char Stream • General-purpose input and output. • Primitive data types or raw bytes. • Intended for character data. • Input and output for 16 -bit Unicode char. 51

Class hierarchies for the Input. Stream 52

Class hierarchies for the Input. Stream 52

Class hierarchies for the Output. Stream 53

Class hierarchies for the Output. Stream 53

Class hierarchies for the Reader 54

Class hierarchies for the Reader 54

Class hierarchies for the Writer 55

Class hierarchies for the Writer 55

Byte Streams Example import java. io. *; public class File. Copy { public static

Byte Streams Example import java. io. *; public class File. Copy { public static void main(String args[]) throws IOException { File. Input. Stream input = null; File. Output. Stream output = null; try { input = new File. Input. Stream("source. txt"); output = new File. Output. Stream("destination. txt"); int ch; while ((ch = input. read()) != -1) { output. write(ch); } 56

Byte Stream Example } finally { if (input != null) { input. close(); }

Byte Stream Example } finally { if (input != null) { input. close(); } if (output != null) { output. close(); } } 57

output Life is short! Smile while you still have teeth. Don't give up your

output Life is short! Smile while you still have teeth. Don't give up your dreams! Keep sleeping. source. txt Life is short! Smile while you still have teeth. Don't give up your dreams! Keep sleeping. destination. txt 58

Character Streams Example import java. io. *; public class File. Copy { public static

Character Streams Example import java. io. *; public class File. Copy { public static void main(String args[]) throws IOException { File. Reader input = null; File. Writer output = null; try { input = new File. Reader ("source. txt"); output = new File. Writer ("destination. txt"); int ch; while ((ch = input. read()) != -1) { output. write(ch); } 59

Byte Stream Example } finally { if (input != null) { input. close(); }

Byte Stream Example } finally { if (input != null) { input. close(); } if (output != null) { output. close(); } } 60

output Life is short! Smile while you still have teeth. Don't give up your

output Life is short! Smile while you still have teeth. Don't give up your dreams! Keep sleeping. source. txt Life is short! Smile while you still have teeth. Don't give up your dreams! Keep sleeping. destination. txt 61

Reference • Chapters 11&13, Introduction to Java Programming, Liang. 62

Reference • Chapters 11&13, Introduction to Java Programming, Liang. 62