M C6java7

51
1 String and StringBuilder Part I: String

Transcript of M C6java7

Page 1: M C6java7

1

String and StringBuilder

Part I: String

Page 2: M C6java7

2

About Strings Strings are objects, but there is a special syntax for writing

String literals:"Hello"

Strings, unlike most other objects, have a defined operation (as opposed to a method):

" This " + "is String " + "concatenation"" Strings can contain any character, but some of them must be

“escaped” in order to write them in a literal– \" stands for the double-quote (") character– \n stands for the newline character– \\ stands for the backslash (\)character– Each of these is written as a two-character sequence, but represents a

single character in the string

Page 3: M C6java7

3

Useful String methods I

char charAt(int index)– Returns the character at the given index position (0-

based)

boolean startsWith(String prefix)– Tests if this String starts with the prefix String

boolean endsWith(String suffix)– Tests if this String ends with the suffix String

Page 4: M C6java7

4

Useful String methods II

boolean equals(Object obj)– Tests if this String is the same as the obj (which may

be any type; false if it’s not a String)

boolean equalsIgnoreCase(String other)– Tests if this String is equal to the other String, where

case does not matter

int length()– Returns the length of this string; note that this is a

method, not an instance variable

Page 5: M C6java7

5

Useful String methods III int indexOf(char ch)

– Returns the position of the first occurrence of ch in this String, or -1 if it does not occur

int indexOf(char ch, int fromIndex)– Returns the position of the first occurrence of ch, starting at (not

after) the position fromIndex

There are two similar methods that take a String instead of a char as their first argument

Page 6: M C6java7

6

Useful String methods IV

int lastIndexOf(char ch)– Returns the position of the last occurrence of ch in this

String, or -1 if it does not occur

int lastIndexOf(char ch, int fromIndex)– Returns the position of the last occurrence of ch,

searching backward starting at position fromIndex

There are two similar methods that take a String instead of a char as their first argument

Page 7: M C6java7

7

Useful String methods V

String substring(int beginIndex)– Returns a new string that is a substring of this string,

beginning with the character at the specified index and extending to the end of this string.

String substring(int beginIndex, int endIndex)

– Returns a new string that is a substring of this string, beginning at the specified beginIndex and extending to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex

Page 8: M C6java7

8

Understanding “index” With charAt(index), indexOf(x), and lastIndexOf(x),

just count characters (starting from zero)

With substring(from) and substring(from, to), it works better to count positions between characters

So, for example, substring(4, 8) is "said", andsubstring(8, 12) is ", \"H"

"She said, \"Hi\"" 0 1 2 3 4 5 6 7 8 9 10 11 12 13

"She said, \"Hi\""0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

If indexOf(',') is 8, then substring(0, indexOf(',')) is "She said"and substring(indexOf(',') + 1) is " \"Hi\""

Page 9: M C6java7

9

Useful String methods VI String toUpperCase()

– Returns a new String similar to this String, in which all letters are uppercase

String toLowerCase()– Returns a new String similar to this String, in which all

letters are lowercase

String trim()– Returns a new String similar to this String, but with

whitespace removed from both ends

Page 10: M C6java7

10

Useful String methods VII String[] split(String regex)

– Breaks the string up into an array of strings– The parameter is a regular expression that defines what

separates the strings– For example,

String s = "one, two, three"; String[] ss = s.split(", ");

This assigns the array {"one", "two", "three"} to ss– Regular expressions are complex expressions that

assign meanings to many common punctuation marks, such as +, *, period, and [

Hence, regular expressions are powerful, but can be treacherous if you aren’t very familiar with them

Page 11: M C6java7

11

Finally, a useless String method String toString()

– Returns this String

Why do we have this method?– Consistency--Every Object has a toString() method

Page 12: M C6java7

12

Strings are immutable A String, once created, cannot be changed None of the preceding methods modify the

String, although several create a new String Statements like this create new Strings:

myString = myString + anotherCharacter; Creating a few extra Strings in a program is

no big deal Creating a lot of Strings can be very costly

Page 13: M C6java7

13

More about equals If you write

String s = "abc"; String t = "abc";the compiler only creates the string "abc" once, and makes s and t both refer to this one string

– It can do this because strings are immutable– Hence, the test s == t will be true

However, if you now write String u = "a" + "bc";the test s == u will be false

– This is because they are different strings Moral: Use equals for strings, not ==

Page 14: M C6java7

14

Still more about equals Suppose you want to test whether a variable

name has the value "Dave"– Here’s the obvious way to do it:

if (name.equals("Dave")) { ... }– But you could also do it this way:

if ("Dave".equals(name)) { ... } It turns out that the second way is usually

better Why?

– If name == null, the first way will cause a NullPointerException, but the second way will just return false

Page 15: M C6java7

15

Strings, Etc.

Part II: StringBuilder

Page 16: M C6java7

16

About StringBuilders A StringBuilder has a capacity (the number of characters

it can hold) and a length (the number of characters it is currently holding)

If the capacity is exceeded, the StringBuilder is copied to a new location with more room

StringBuilder is a reimplementation of StringBuffer– The API (collection of methods) is the same– StringBuffers are threadsafe, but StringBuilders are more efficient

StringBuilders are used to implement String concatenation

– Whenever you say String s = "ab" + "cd", Java creates a StringBuffer containing the characters a and b, appends the characters c and d to it, and converts the result back to a String

– As you might guess, this isn’t terribly efficient, but it’s fine if you don’t overdo it

Page 17: M C6java7

17

StringBuilder constructors

StringBuilder()– Constructs a StringBuilder with a capacity of 16

characters

StringBuilder(int capacity)– Constructs a StringBuilder with the requested capacity

StringBuilder(String str)– Constructs a StringBuilder containing the String str

Page 18: M C6java7

18

Useful StringBuilder methods I StringBuilder append(X)

– Appends X to the end of this StringBuilder; also (as a convenience) returns this StringBuilder

The append method is so heavily overloaded that it will work with any argument; if the argument is an object, its toString() method is used

Page 19: M C6java7

19

Useful StringBuilder methods II int length()

– Returns the number of characters in this StringBuilder

void setLength(int newLength)– Sets the number of characters in this StringBuilder;

this may result in truncation of characters at the end, or addition of null characters

Page 20: M C6java7

20

Useful StringBuilder methods III char charAt(int index)

– Returns the character at the location index

void setCharAt(int index, char ch)– Sets the character at location index to ch

StringBuilder reverse()– The sequence of characters in this StringBuilder is

replaced by the reverse of this sequence, and also returned as the value of the method

Page 21: M C6java7

21

Useful StringBuilder methods IV StringBuilder insert(int offset, X)

– Insert X starting at the location offset in this StringBuilder, and also return this StringBuilder as the value of the method. Like append, this method is heavily overloaded

StringBuilder deleteCharAt(int index)– Deletes the character at location index

StringBuilder delete(int start, int end)– Deletes chars at locations start through end-1

Page 22: M C6java7

22

Useful StringBuilder methods V

String substring(int start)– Returns a new String of characters from this

StringBuilder, beginning with the character at the specified index and extending to the end of this string.

String substring(int start, int end)– Returns a new String of characters from this

StringBuilder, beginning at location start and extending to the character at index end-1. Thus the length of the substring is end-begin

String toString()– Returns the characters of this StringBuilder as a String

Page 23: M C6java7

23

When to use StringBuilders If you make a lot (thousands) of changes or

additions to a String, it is much more efficient to use a StringBuilder

If you are simply examining the contents of a String, then a String is at least as efficient as a StringBuilder

For incidental use (such as creating output lines), use Strings; they are more convenient

Page 24: M C6java7

24

Strings, etc.

Part III: Characters

Page 25: M C6java7

25

The Character class char is a primitive type, not an object,

therefore… …there are no methods you can call on a

char This is why we need a Character class!

There are a lot of methods in the Character class

– They are all static– Do you see why?

Page 26: M C6java7

26

Some Character methods static boolean isDigit(char ch) static boolean isLetter(char ch) static boolean isLetterOrDigit(char ch) static boolean isLowerCase(char ch) static boolean isUpperCase(char ch) static boolean isWhitespace(char ch) static char toLowerCase(char ch) static char toUpperCase(char ch) For more methods, see java.lang.Character

Page 27: M C6java7

27

Exceptions

Page 28: M C6java7

28

Errors and Exceptions An error is a bug in your program

– dividing by zero– going outside the bounds of an array– trying to use a null reference

An exception is a problem whose cause is outside your program

– trying to open a file that isn’t there– running out of memory

Page 29: M C6java7

29

What to do about errors and exceptions

An error is a bug in your program– It should be fixed

An exception is a problem that your program may encounter

– The source of the problem is outside your program– An exception is not the “normal” case, but...– ...your program must be prepared to deal with it

This is not a formal distinction–it isn’t always clear whether something should be an error or an exception

Page 30: M C6java7

30

Dealing with exceptions Most exceptions arise when you are handling

files– A needed file may be missing– You may not have permission to write a file– A file may be the wrong type

Exceptions may also arise when you use someone else’s classes (or they use yours)

– You might use a class incorrectly– Incorrect use should result in an exception

Page 31: M C6java7

31

The problem with exceptions Here’s what you might like to do:

– open a file– read a line from the file

But here’s what you might have to do:– open a file– if the file doesn’t exist, inform the user– if you don’t have permission to use the file, inform the user– if the file isn’t a text file, inform the user– read a line from the file– if you couldn’t read a line, inform the user– etc., etc.

All this error checking really gets in the way of understanding the code

Page 32: M C6java7

32

Three approaches to error checking

1. Ignore all but the most important errors The code is cleaner, but the program will misbehave when it

encounters an unusual error

2. Do something appropriate for every error The code is cluttered, but the program works better You might still forget some error conditions

3. Do the normal processing in one place, handle the errors in another (this is the Java way) The code is at least reasonably uncluttered Java tries to ensure that you handle every error

Page 33: M C6java7

33

The try statement Java provides a new control structure, the try

statement (also called the try-catch statement) to separate “normal” code from error handling: try {

do the “normal” code, ignoring possible exceptions}

catch (some exception) { handle the exception}

catch (some other exception) { handle the exception}

Page 34: M C6java7

34

Exception handling is not optional

As in other languages, errors usually just cause your program to crash

Other languages leave it up to you whether you want to handle exceptions

– There are a lot of sloppy programs in the world– It’s normal for human beings to be lazy

Java tries to force you to handle exceptions– This is sometimes a pain in the neck, but...– the result is almost always a better program

Page 35: M C6java7

35

Error and Exception are Objects

In Java, an error doesn’t necessarily cause your program to crash

When an error occurs, Java throws an Error object for you to use

– You can catch this object to try to recover– You can ignore the error (the program will crash)

When an exception occurs, Java throws an Exception object for you to use

– You cannot ignore an Exception; you must catch it– You get a syntax error if you forget to take care of any possible

Exception

Page 36: M C6java7

36

The exception hierarchy Throwable: the superclass of

“throwable” objects– Error: Usually should not be caught (instead, the

bug that caused it should be fixed)– Exception: A problem that must be caught

RuntimeException: A special subclass of Exception that does not need to be caught

Hence, it is the Exceptions that are most important to us (since we have to do something about them)

Page 37: M C6java7

37

The Exception hierarchy II

Throwable

Error Exception

RuntimeExceptionMust be caughtNeed not

be caught

Page 38: M C6java7

38

A few kinds of Exceptions

IOException: a problem doing input/output– FileNotFoundException: no such file– EOFException: tried to read past the End Of File

NullPointerException: tried to use a object that was actually null (this is a RuntimeException)

NumberFormatException: tried to convert a non-numeric String to a number (this is a RuntimeException)

OutOfMemoryError: the program has used all available memory (this is an Error)

There are about 200 predefined Exception types

Page 39: M C6java7

39

What to do about Exceptions You have two choices:

– You can “catch” the exception and deal with it For Java’s exceptions, this is usually the better choice

– You can “pass the buck” and let some other part of the program deal with it

This is often better for exceptions that you create and throw

Exceptions should be handled by the part of the program that is best equipped to do the right thing about them

Page 40: M C6java7

40

What to do about Exceptions II You can catch exceptions with a try statement

– When you catch an exception, you can try to repair the problem, or you can just print out information about what happened

You can “pass the buck” by stating that the method in which the exception occurs “throws” the exception

– Example: void openFile(String fileName) throws IOException { ... }

Which of these you do depends on whose responsibility it is to do something about the exception

– If the method “knows” what to do, it should do it– If it should really be up to the user (the method caller) to decide

what to do, then “pass the buck”

Page 41: M C6java7

41

How to use the try statement

Put try {...} around any code that might throw an exception

– This is a syntax requirement you cannot ignore

For each Exception object that might be thrown, you must provide a catch phrase: catch (exception_type name) {...}– You can have as many catch phrases as you need– name is a formal parameter that holds the exception object– You can send messages to this object and access its fields

Page 42: M C6java7

42

finally After all the catch phrases, you can have an

optional finally phrase try { ... }

catch (AnExceptionType e) { ... }catch (AnotherExceptionType e) { ... }finally { ... }

Whatever happens in try and catch, even if it does a return statement, the finally code will be executed

– If no exception occurs, the finally will be executed after the try code

– In an exception does occur, the finally will be executed after the appropriate catch code

Page 43: M C6java7

43

How the try statement works The code in the try {...} part is executed

If there are no problems, the catch phrases are skipped

If an exception occurs, the program jumps immediately to the first catch clause that can handle that exception

Whether or not an exception occurred, the finally code is executed

Page 44: M C6java7

44

Ordering the catch phrases A try can be followed by many catches

– The first one that can catch the exception is the one that will catch the exception

Bad: catch(Exception e) { ... }

catch(IOException e) { ... } This is bad because IOException is a

subclass of Exception, so any IOException will be handled by the first catch

– The second catch phrase can never be used

Page 45: M C6java7

45

Using the exception

When you say catch(IOException e), e is a formal parameter of type IOException

– A catch phrase is almost like a miniature method– e is an instance (object) of class IOException– Exception objects have methods you can use

Here’s an especially useful method that is defined for every exception type:e.printStackTrace();– This prints out what the exception was, and how you got

to the statement that caused it

Page 46: M C6java7

46

printStackTrace() printStackTrace() does not print on

System.out, but on another stream, System.err– From BlueJ: If it doesn’t show up in the output window, look

in the DOS window that BlueJ opens– From the command line: both System.out and System.err

are sent to the terminal window printStackTrace(stream) prints on the given

stream– printStackTrace(System.out) prints on System.out, and

this output is printed along with the “normal” output

Page 47: M C6java7

47

Throwing an Exception If your method uses code that might throw

an exception, and you don’t want to handle the exception in this method, you can say that the method “throws” the exception

Example: String myGetLine( ) throws IOException { ... }

If you do this, then the method that calls this method must handle the exception

Page 48: M C6java7

48

Constructing an Exception Exceptions are classes; you can create your

own Exception with new– Exception types have two constructors: one with no

parameters, and one with a String parameter

You can subclass Exception to create your own exception type

– But first, you should look through the predefined exceptions to see if there is already one that’s appropriate

Page 49: M C6java7

49

Throwing an Exception

Once you create an Exception, you can throw it– throw new UserException("Bad data");

You don’t have to throw an Exception; here’s another thing you can do with one:– new UserException("Bad

data").printStackTrace();

Page 50: M C6java7

50

Why create an Exception? If you are writing methods for someone else

to use, you want to do something reasonable if they use your methods incorrectly

Just doing the wrong thing isn’t very friendly Remember, error messages are a good thing

—much better than not having a clue what went wrong

– Exceptions are even better than error messages, because they allow the user of your class to decide what to do

Page 51: M C6java7

51