Java Programming Lecture 8 Alice E. Fischer

February 14, 2012

Alice E. Fischer

()

Java Programming - L8. . .

1/23

February 14, 2012

1 / 23

Outline

1

A Formal Introduction to Exceptions Definitions

2

Java Strings StringBuilder and StringBuffer

3

Summary and Homework

Alice E. Fischer

()

Java Programming - L8. . .

2/23

February 14, 2012

2 / 23

A Formal Introduction to Exceptions

Exceptions Lecture 7 gave a practical introduction to exceptions in the context of IO. Here, we give a more general introduction to the subject. Purpose and exception types Exception control: throw, catch, finally Handling Exception and returning to execution Learn these exception types

Alice E. Fischer

()

Java Programming - L8. . .

3/23

February 14, 2012

3 / 23

A Formal Introduction to Exceptions

Definitions

The Exception Classes Errors and unchecked exceptions, shown in green, do not need to be declared, but often they should be caught. LinkageError Error

Thrown for Strings, Vectors, arrays, etc. Extend this class to make your own similar exceptions.

VirtualMachineError

Throwable

IndexOutOfBoundsException NullPomterException

OutOfMemoryError

ArithmeticException RuntimeException Exception

IllegalArgumentException IOException Other Exceptions

Alice E. Fischer

()

Java Programming - L8. . .

NumberFormatException

4/23

February 14, 2012

4 / 23

A Formal Introduction to Exceptions

Definitions

CheckedExceptions

The checked exceptions, shown in yellow, must be declared or caught. FileNotFoundException Error Throwable

RuntimeException

EOFException

ClassNotFoundException Exception

IOException

MalformedURLException

GeneralSecurityException

Alice E. Fischer

()

Java Programming - L8. . .

InterruptedIOException

5/23

NoSuchAlgorithmException

February 14, 2012

5 / 23

A Formal Introduction to Exceptions

Definitions

Exceptions are. . . Exceptions are used for handling unexpected errors. They are A way to transfer control to a distant part of the program efficiently without breaking modularity. A way to handle unexpected emergencies. A form of inter-module communication. Exceptions allow for the separation of error processing from the normal logic of the program. They help move control from the function that discovers a problem back to a function that can correct the problem. After handling an exception, control can return to normal processing. An uncaught exception will terminate the program.

Alice E. Fischer

()

Java Programming - L8. . .

6/23

February 14, 2012

6 / 23

A Formal Introduction to Exceptions

Definitions

Exception Control

Throwing an exception transfers control down the stack, through the chain of function calls, possibly as far as main. An exception can be intercepted (“caught”) at any stage between the function that initiates it and main. The exception object can carry data with it, down that chain. As the exception passes back through the chain of function calls, the stack frames are deallocated. After being caught, appropriate actions should be taken. Then the exception can be rethrown or you can return to execution.

Alice E. Fischer

()

Java Programming - L8. . .

7/23

February 14, 2012

7 / 23

A Formal Introduction to Exceptions

Definitions

Throwing Control Down the Stack

he run-time stack contains a stack frame for every function that has been called but has not yet eturned. Each function has called the one above it on the stack. The frames contain parameters, ocal variables, and the function's return address. Suppose func5 tries to open a file an fails. That will cause the stack a FileNotFoundException to be created and thrown. func2 and main have catchers for this type of exception. The frame for func 5 is deallocated. func5 Suppose func4 and func 3 do not catch this type of exception. Two func4 func4 more frames are deallocated. func3

func3

func2

func2

func2

func1

func1

func1

func1

main

main

main

main

Alice E. Fischer

()

Java Programming - L8. . .

Now func2 catches the exception, does something useful, and rethrows it.

8/23

The frame for func1 is deallocated and main catches the exception. February 14, 2012

8 / 23

A Formal Introduction to Exceptions

Definitions

Throw Your Own / Re-Throw

Keyword: throw File tos = new File ("demoOut.txt"); if(tos.exists()) throw new IOException("File already exists.

Aborting");

The JVM throws exceptions for many diverse reasons. When you throw an exception yourself, you may provide the message to display. A catch block may partially respond to an exception then throw it again. a particular exception.

Alice E. Fischer

()

Java Programming - L8. . .

9/23

February 14, 2012

9 / 23

A Formal Introduction to Exceptions

Definitions

Cleaning Up Keyword: finally A finally clause is used to free resources before leaving the block that created them. You need a try block, but it does not have to have anycatch blocks. Here is what you need for the Logon program: public void doMenu( ) ... { try{ // Display the menu and process requests } finally { // Write all the user data to the output file. // close the output file. } Alice E. Fischer

()

Java Programming - L8. . .

10/23

February 14, 2012

10 / 23

A Formal Introduction to Exceptions

Definitions

How to catch.

A catch clause is called an exception handler. The catch clause names the exception type and provides a parameter name for accessing the exception object. catch (IOException e) {...} The parameter name, e, may be used in the body of the catch clause to process the exception. You must declare a parameter name whether or not you use it.. To catch all possible exceptions and errors, catch (Throwable e) {...}

Alice E. Fischer

()

Java Programming - L8. . .

11/23

February 14, 2012

11 / 23

A Formal Introduction to Exceptions

Definitions

When to try and catch. Put the try and catch in the part of the code that is able to correct the problem. This could be where the problem occurred. double safeDivide (double a, double b) { try { result = a / b; } catch(ArithmeticException ex) { result = 0; } return result; } EOF handling might be done where the condition happened, or partway up the chain of calls. For errors in interactive input, the exception should be processed at the level where the code interacts with the human user.

Alice E. Fischer

()

Java Programming - L8. . .

12/23

February 14, 2012

12 / 23

Java Strings

Strings StringBuffer and StringBuilder toString functions and String.format() Scanner: next and nextLine; Today’s date

Alice E. Fischer

()

Java Programming - L8. . .

13/23

February 14, 2012

13 / 23

Java Strings

The String Class

java.lang.String All string literals, such as ”Hello”, are implemented as Strings. A String variable can point at any String: String s = "Hi"; Once a String is created, it is immutable. That is, it cannot be modified. The + operator concatenates two strings by copying the first string into new memory then copying the second string after it. Neither of the original strings are changed.

Alice E. Fischer

()

Java Programming - L8. . .

14/23

February 14, 2012

14 / 23

Java Strings

String Constructors

String() String(byte[] bytes) String(char[] value) String(String original) String(StringBuffer b) String(StringBuilder b)

Alice E. Fischer

()

The new object is the empty string. The new string is the contents of the byte array, in the local default charset. A new string is built that contains the sequence of chars. A copy of the original string is made in new storage. The new string contains the chars contained in the StringBuffer. The new string contains the chars contained in the StringBuilder.

Java Programming - L8. . .

15/23

February 14, 2012

15 / 23

Java Strings

Important String Functions

charAt( int k ): Return the char value at subscript k. compareTo(String s2): Like strcmp() in C. Return value is negative if this precedes s2 in lexicographic order, 0 if they are equal, of positive if this follows s2. compareToIgnoreCase(String s2): Case differences are ignored in the comparison. equals(String s2): Returns true if this equals s2, false otherwise. format(String f, Object...): Returns a formatted string using the format f and arguments. indexOf(int ch): Returns the subscript of the 1st occurrence of ch. Several related methods exist.

Alice E. Fischer

()

Java Programming - L8. . .

16/23

February 14, 2012

16 / 23

Java Strings

Important String Functions lastIndexOf(int ch) : Returns the index within this string of the last occurrence of the specified character. startsWith(String prefix) : Tests if this string starts with the specified prefix; returns a true/false answer. length(): Returns the number of chars in the String. toLowerCase(): Returns a new string with all letters of this converted to lower case. toUpperCase(): Returns a new string with all letters of this converted to upper case. trim(): Returns a copy of the string, with leading and trailing whitespace omitted. There are also several methods for pattern matching, string parsing, and converting primitive values to Strings. Alice E. Fischer

()

Java Programming - L8. . .

17/23

February 14, 2012

17 / 23

Java Strings

String Concatenation Wastes Time and Space. String w0 = "Do "; String w1 = "dogs "; String w2 = "cats " String w3 = "run away from " String w4 = w0 + w2 + w3 + w1 + "?";

((((w0 + w2) + w3) + w1) + "?") This computation is done in four stages. The 3 intermediate strings become garbage. The first word is copied 4 times. Do cats

w0 w1

"Do " "dogs "

w2

"cats "

w3

"run away from "

8 chars

Do cats run away from

22 chars

Do cats run away from dogs Do cats run away from dogs ?

w4

27 chars 28 chars

This process is very inefficient. It is an n-squared operation. The colored areas become garbage.

Alice E. Fischer

()

Java Programming - L8. . .

18/23

February 14, 2012

18 / 23

Java Strings

StringBuilder and StringBuffer

StringBuilder and StringBuffer

These two classes exist to allow you to build up a string, piece by piece, efficiently. They do the same job, with the same interface. StringBuffer has synchronized methods and should be used in programs with threads. StringBuilder is more efficient but not thread-safe. Both will “grow”, as necessary, to hold as much as needed. The two most useful constructors are: StringBuilder(): Construct an empty string builder with an initial capacity of 16 chars. StringBuilder(String s): Construct a string builder whose contents begins with s.

Alice E. Fischer

()

Java Programming - L8. . .

19/23

February 14, 2012

19 / 23

Java Strings

StringBuilder and StringBuffer

Use StringBuilder to construct Strings piece by piece. String w0 = "Do "; String w1 = "dogs "; String w2 = "cats " String w3 = "run away from "

w0 w1

"Do " "dogs "

w2

"cats "

w3 "run away from " StringBuilder sb = new StringBuilder( w0 ); sb.append( w2 ); sb Do cats run away 16 chars sb.append( w3 ); sb.append( w1 ); Do cats run away from dogs ? sb.append( "?" ); String w4 = sb.toString();

w4

32 chars

"Do cats run away from dogs ?"

The data is copied efficiently into the StringBuilder’s storage. The Builder grows, if necessary, and the old area becomes garbage.

Alice E. Fischer

()

Java Programming - L8. . .

20/23

February 14, 2012

20 / 23

Java Strings

StringBuilder and StringBuffer

Useful StringBuilder Functions

append(Object ob): Store the String value of ob on the end of the current contents of the StringBuilder. Lengthen the allocation area if necessary. Append methods exist for all the primitive types, for a char array, a String or a StringBuffer. length(): The current character count. reverse(): Causes this character sequence to be replaced by the reverse of the sequence. toString(): Returns the String inside the builder. Many methods exist to search a StringBuilder and do substring manipulation and replacement.

Alice E. Fischer

()

Java Programming - L8. . .

21/23

February 14, 2012

21 / 23

Summary and Homework

Java Summary

We have used the following packages and classes today: Throwable: Exception, and Error throw Any class: constructor, toString() String: charAt(), +, equals(), startsWith() StringBuilder: append() Scanner: next(), nextLine()

Alice E. Fischer

()

Java Programming - L8. . .

22/23

February 14, 2012

22 / 23

Summary and Homework

Homework This Week

Vending Machine Read Chapters 9 and 10 in the text. P3. A Simple Lottery – Due Feb, 19. Details are given at http://eliza.newhaven.edu/javaG/attach/p3Lottery.pdf.

Alice E. Fischer

()

Java Programming - L8. . .

23/23

February 14, 2012

23 / 23