string methods in java

32
String class and some of its methods. We also introduce the StringBuffer , StringBuilder, and StringTokenizer classes that provide additional string handling and processing tools. String Methods The String class contains a large number of other useful methods. Here we briefly examine a sample of these methods. int length () This method returns the number of characters in the string as in String str = "A string"; int x = str.length (); This results in variable x holding the value 8. String trim () Removes whitespace from the leading and trailing edges of the string. String string = "� 14 units� "; String str = string.trim (); This results in the variable str referencing the string "14 units". int indexOf (int ch) int lastIndexOf (int ch) This method returns the index, starting from 0, for the location of the given character in the string. (The char value will be widened to int.) For example, � String string = "One fine day"; � int x = string.indexOf (�f�); This results in a value of 4 in the variable x. If the string holds no such character, the method returns -1.� To continue searching for more instances of the character, you can use the method � indexOf(int ch, int fromIndex) This will� start the search at the fromIndex location in the string and search to the end of the string. The methods indexOf (String str) indexOf (String str, int fromIndex) provide similar functions but search for a sub-string �rather than just for a single character.� Similarly, the methods lastIndexOf (int ch) lastIndexOf (int ch, int fromIndex) lastIndexOf (String str) lastIndexOf (String str, int fromIndex) search backwards for characters and strings starting from the right side and moing from right to left. . (The fromIndex second

Upload: jeroldferreira

Post on 20-Feb-2015

130 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: String Methods in Java

String class and some of its methods. We also introduce the StringBuffer , StringBuilder, and StringTokenizer classes that provide additional string handling and processing tools.

String MethodsThe String class contains a large number of other useful methods. Here we briefly examine a sample of these methods.int length ()

This method returns the number of characters in the string as in String str = "A string";int x = str.length ();

This results in variable x holding the value 8.String trim ()

Removes whitespace from the leading and trailing edges of the string.String string = "� 14 units� ";String str = string.trim ();

This results in the variable str referencing the string "14 units".int indexOf (int ch)int lastIndexOf (int ch)

This method returns the index, starting from 0, for the location of the given character in the string. (The char value will be widened to int.) For example,� String string = "One fine day";� int x = string.indexOf (�f�);

This results in a value of 4 in the variable x. If the string holds no such character, the method returns -1.� To continue searching for more instances of the character, you can use the method � indexOf(int ch, int fromIndex)

This will� start the search at the fromIndex location in the string and search to the end of the string. The methodsindexOf (String str) indexOf (String str, int fromIndex)

provide similar functions but search for a sub-string �rather than just for a single character.� Similarly, the methodslastIndexOf (int ch) lastIndexOf (int ch, int fromIndex)lastIndexOf (String str) lastIndexOf (String str, int fromIndex)

search backwards for characters and strings starting from the right side and moing from right to left. . (The fromIndex second parameter still counts from the left, with the search continuing from that index position toward the beginning of the string.)boolean startsWith (String prefix)boolean endsWith (String str)

These two methods test indicate whether a string begins or ends with a particular substring. For example:String [] str = {"Abe", "Arthur", "Bob"};for (int i=0; i < str.length (); i++) {�   if (str1.startsWith ("Ar")) doSomething ();}String toLowerCase ()String toUpperCase ()

The first method return a new string with all the characters set to lower case� while the second returns the characters set to upper case.

Page 2: String Methods in Java

String [] str = {"Abe", "Arthur", "Bob"};for (int i=0; i < str.length(); i++){�   if (str1.toLowerCase ().startsWith ("ar")) doSomething ();}

Below we discuss the split() method in the String class after discussing the StringTokenizer class. See the String entry in the Java 2 Platform API Specifications to examine other methods in the class.

java.lang.StringBufferString objects are immutable, meaning that once created they cannot be altered. Concatenating two strings does not modify either string but instead creates a new string object:  String str = "This is ";  str = str + " a new string object";

Here str variable now references a completely new object that holds the "This is a new string object" string.This is not very efficient if you are doing extensive string manipulation with lots of new strings created through this sort of append operations. The String class maintains a pool of strings in memory. String literals are saved there and new strings are added as they are created. Extensive string manipulation with lots of new strings created with the String append operations can therefore result in lots of memory taken up by unneeded strings. Note however, that if two string literals are the same, the second string reference will point to the string already in the pool rather than create a duplicate.The class java.lang.StringBuffer offers more efficient string creation. For example:.  StringBuffer strb = new StringBuffer ("This is ");  strb.append (" a new string object");  System.out.println (strb.toString());

The StringBuffer uses an internal char array for the intermediate steps so that new strings objects are not created. If it becomes full, the array is copied into a new larger array with the additional space available for more append operations.

java.lang.StringBuilderJ2SE5.0 added the StringBuilder class, which is a drop-in replacement for StringBuffer in cases where thread safety is not an issue. Because StringBuilder is not synchronized, it offers faster performance than StringBuffer.In general, you should use StringBuilder in preference over StringBuffer. In fact, the J2SE 5.0 javac compiler normally uses StringBuilder instead of StringBuffer whenever you perform string concatenation as in System.out.println ("The result is " + result);

All the methods available on StringBuffer are also available on StringBuilder, so it really is a drop-in replacement.

java.util.StringTokenizerThe java.util.StringTokenizer allows you to break a string into substrings, or tokens, that are separated by delimiters. The delimiters are whitespace (spaces, carriage returns, etc.) by default but you can defined others. A StringTokenizer provides an Enumeration object that steps through the tokens:  String str = "This is a string object";  StringTokenizer st = new StringTokenizer (str);  while (st.hasMoreTokens ()) {    System.out.println (st.nextToken ());    ...  }

Page 3: String Methods in Java

On the console this shows: This is a string object

An overloaded constructor allows you to specify the delimiters. For example, String str = "A*bunch*of*stars"; StringTokenizer st = new StringTokenizer (str,"*");

This breaks the string into the tokens separated by the "*" character. String.split ()

J2SE 1.4 added the split() method to the String class to simplify the task of breaking a string into substrings, or tokens. This method uses the concept of a regular expression to specify the delimiters. A regular expression is a remnant from the Unix grep tool ("grep" meaning "general regular expression parser"). A full discussion of regular expressions is beyond the scope of this book. See most any introductory Unix text or the Java API documentation for the java.util.regex.Pattern class. In its simplest form, searching for a regular expression consisting of a single character finds a match of that character. For example, the character 'x' is a match for the regular expression "x".The split() method takes a parameter giving the regular expression to use as a delimiter and returns a String array containing the tokens so delimited. Using split(), the first example above becomesString str = "This is a string object";String[] words = str.split (" ");for (int i=0; i < words.length; i++)  System.out.println (words[i]);To use "*" as a delimiter, specify "\\*", where the backslashes indicate that the * is a character to look for rather than the wildcard in a regular expression:String str2 = "A*bunch*of*stars";String[] starwords = str2.split ("\\*");for (int i=0; i < starwords.length; i++)  System.out.println (starwords[i]);

For most string splitting tasks, the String.split() method is much easier and more natural to use than the StringTokenizer class. However, StringTokenizer is still useful for some tasks. For example, an overloaded StringTokenizer constructor allows you to specify that the tokens to be returned include the delimiter characters themselves.

String methods (few more)These are common String methods. In all of these prototypes, i and j are int indexes into a string, s and t are Strings, and c is a char. cs is a CharacterSequence (eg, either String or StringBuilder).

Length

i = s.length() length of the string s.Comparison (note: use these instead of == and !=)

i = s.compareTo(t) compares to s. returns <0 if s<t, 0 if ==, >0 if s>t

i = s.compareToIgnoreCase(t) same as above, but upper and lower case are

Page 4: String Methods in Java

sameb = s.equals(t) true if the two strings have equal valuesb = s.equalsIgnoreCase(t) same as above ignoring caseb = s.startsWith(t) true if s starts with tb = s.startsWith(t, i) true if t occurs starting at index ib = s.endsWith(t) true if s ends with t

Searching -- Note: All "indexOf" methods return -1 if the string/char is not found

i = s.contains(cs) True if cs can be found in s.i = s.indexOf(t) index of the first occurrence of String t in s.i = s.indexOf(t, i) index of String t at or after position i in s.i = s.indexOf(c) index of the first occurrence of char c in s.i = s.indexOf(c, i) index of char c at or after position i in s.i = s.lastIndexOf(c) index of last occurrence of c in s.i = s.lastIndexOf(c, i) index of last occurrence of c on or before i

in s.i = s.lastIndexOf(t) index of last occurrence of t in s.i = s.lastIndexOf(t, i) index of last occurrence of t on or before i

in s.Getting parts

c = s.charAt(i) char at position i in s.s1 = s.substring(i) substring from index i to the end of s.s1 = s.substring(i, j) substring from index i to BEFORE index j

of s.Creating a new string from the original

s1 = s.toLowerCase() new String with all chars lowercases1 = s.toUpperCase() new String with all chars uppercases1 = s.trim() new String with whitespace deleted from

front and backs1 = s.replace(c1, c2) new String with all c1 characters replaced

by character c2.s1 = s.replace(cs2, cs3) new String with all cs2 substrings replaced

by cs3.Regular Expressions (as of Java 1.4) regexStr parameters are Strings, but see also java.util.regex.Pattern, ...

b = s.matches(regexStr) true if regexStr matches the entire string in s. Same as Pattern.matches(regexStr, s)

s1 = s.replaceAll(regexStr, t) replaces each substring that matches regexStr with String t

s1 = s.replaceFirst(regexStr, t) replaces first substring that matches regexStr with String t

sa = s.split(regexStr) array of all substrings terminated by regexStr or end

sa = s.split(regexStr, count) limited to applying regexStr only count times.

Page 5: String Methods in Java

Static Methods for Converting to String

s = String.valueOf(x) Converts x to String, where x is any type value (primitive or object).

s = String.format(f, x...) [Java 5] Use format f to convert variable number of parameters, x to a string.

Comparator for sorting arrays and collections.comp = String.CASE_INSENSITIVE_ORDERA static Comparator object that does case-

insensitive comparisons for sorts and ordered Collections (eg, TreeMap, TreeSet, SortedMap, and SortedSet).

StringBuffer example:In object-oriented programming, a String Buffer is an alternative to a String. It has the ability to be altered through adding or appending, whereas a String is normally fixed or immutable.

Java's standard way to handle text is to use its String class. Any given String in Java is an immutable object, which means its state cannot be changed. A String has an array of characters. Whenever a String must be manipulated, any changes require the creation of a new String (which, turn, involves the creation of a new array of characters, and copying of the original array). This happens even if the original String's value or intermediate Strings used for the manipulation are not kept.

Java provides an alternate class for string manipulation, called a StringBuffer. A StringBuffer, like a String, has an array to hold characters. It, however, is mutable (its state can be altered). Its array of characters is not necessarily completely filled (as oppose to a String, whose array is always the exact required length for its contents). Thus, it has the capability to add, remove, or change its state without creating a new object (and without the creation of a new array, and array copying). The exception to this is when its array is no longer of suitable length to hold its content. In this case, it is required to create a new array, and copy contents.

For these reasons, Java would handle an expression like

String newString = aString + anInt + aChar + aDouble;

like this:

String newString = (new StringBuffer(aString)).append(anInt).append(aChar).append(aDouble)).toString();

[edit] ImplicationsGenerally, a StringBuffer is more efficient than a String in string handling. However, this is not necessarily the case, since a StringBuffer will be required to recreate its character array when it runs out of space. Theoretically, this is possible to happen the same number of times as a new String would be required, although this is unlikely (and the programmer can provide length hints to prevent this). Either way, the effect is not noticeable in modern desktop computers.

Page 6: String Methods in Java

As well, the shortcomings of arrays are inherent in a StringBuffer. In order to insert or remove characters at arbitrary positions, whole sections of arrays must be moved.

The method by which a StringBuffer is attractive in an environment with low processing power takes this ability by using too much memory, which is likely also at a premium in this environment. This point, however, is trivial, considering the space required for creating many instances of Strings in order to process them. As well, the StringBuffer can be optimized to "waste" as little memory as possible.

The StringBuilder class, introduced in J2SE 5.0, differs from StringBuffer in that it is unsynchronized. When only a single thread at a time will access the object, using a StringBuilder processes more efficiently than using a StringBuffer.

StringBuffer and StringBuilder are included in the java.lang package.

public final class StringBufferextends Objectimplements Serializable, CharSequence

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved. The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point. For example, if z refers to a string buffer object whose current contents are "start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4, "le") would alter the string buffer to contain "starlet". In general, if sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x). Whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence) this class synchronizes only on the string buffer performing the operation, not on the source. Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger. As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization. Since:

JDK1.0

Page 7: String Methods in Java

Class BufferedStringjava.lang.Object

TGT.BufferedString

public class BufferedString

extends java.lang.Object

A class that behaves a bit like an input stream but that returns data from a supplied string. The next line or the next character from the string can be requested, and these two operate independently of each other. That is, after calling readLine() a few times, calling read() will return the first character in the string, not the next character after the last line returned by readLine().

Constructor Summary

BufferedString(java.lang.String s) Create a buffered string that will return characters from parameter string s.

Method Summary

int read() Return the next character from the input string.

java.lang.String readLine() Return the next line from the input string.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BufferedStringpublic BufferedString(java.lang.String s)

Page 8: String Methods in Java

Create a buffered string that will return characters from parameter string s.

Parameters:

s - The string to use as the "input stream."

Method Detail

readLinepublic java.lang.String readLine()

Return the next line from the input string.

readpublic int read()

Return the next character from the input string.

In this example we are going to reverse a given string.This example takes values from command line argument as string, buffers the input string by using the StringBuffer(String string) method, reverse the buffered string and converts this buffered string into the string by using the toString() method. Note that pass the words within  " "  to wrap the words into a single string value at the command line argument.

  The code of the program is given below:public class StringReverseExample{  public static void main(String[] args)  {  String string=args[0];  String reverse = new StringBuffer(string).reverse().toString();  System.out.println("\nString before reverse: "+string);  System.out.println("String after reverse: "+reverse);  } 

The output of the program is given below:C:\rajesh\kodejava>javac StringReverseExample.javaC:\rajesh\kodejava>java StringReverseExample "hi how are you."String before reverse: hi how are you.String after reverse: .uoy era

Page 9: String Methods in Java

woh ih

Try and catch block in Java

Exceptions: the try/catch blockIn our introduction to exceptions, we showed how an exception object thrown by a method (in fact a constructor in the example) could be caught by the caller in a construction commonly called the try/catch block. In the block preceded by try, we put the code whose exceptions we want or need to trap. In the block preceded by catch, we put the code that will be executed if and only if an exception of the given type is thrown. Let's expand on this construction here. Firstly, we didn't explicitly state the following:

The try and catch blocks can contain arbitrary number of lines of code: in other words, with a single block, we can catch exceptions over a whole section of code. This makes things much more succinct than the traditional check for an error condition after every line typical in C programming.

So long as at least one of the lines in the try block can throw an exception of the given type, we can have other lines in the same block which don't actually throw the given exception.

We can have multiple catch blocks associated with a single try block, to catch different types of exceptions.

As an illustration of these points, consider the following code, which opens a file, reads a line from it, and parses the line. In this example, the first line of the try block can throw a FileNotFoundException and some of the later lines can throw an IOException. Additionally, there is one line that can throw a NumberFormatException. The call to line.trim() can't actually throw any of these exceptions, but it doesn't matter: we can still include it in the same try block to avoid having to make our code messy with multiple try/catch blocks. Notice how we can even put the return statement to the method inside the try/catch block. (It's important to state that this is an example of the points mentioned so far: in reality, there are other changes we'd need to make to this code, as discussed below.)

public int getNumber(File f) {

try {

FileInputStream fin = new FileInputStream(f);

BufferedReader br = new BufferedReader(new InputStreamReader(fin), "ASCII");

String line = br.readLine();

line = line.trim();

int number = Integer.parseInt(line);

br.close();

return number;

} catch (FileNotFoundException fnf) {

Page 10: String Methods in Java

// Oh dear, error occurred opening file

displayErrorMessage(fnf.getMessage());

} catch (IOException ioex) {

displayErrorMessage(ioex.getMessage());

} catch (NumberFormatException nfe) {

displayErrorMessage("The file contained invalid data");

}

return -1; // If we get here, we didn't read a

// number from the file

}

(Note: we're not going to get bogged down in the actual calls to perform the I/O; to learn more about things such as the BufferedReader and the readLine() method, see this site's separate introduction to I/O in Java.)

Problems with this example (and how to resolve them)Now, there are actually still some inconveniences with the above example that we'd need to resolve:

in the case of every exception, we're actually logging the error there and then; in reality, we might not want to mix file handling and user interface code in utility methods in this way; it would better to let the caller handle the error and manage things such as UI messages;

on a related issue, we're actually still returning a spurious value from our method when an error occurs: astute readers will recall that one of the whole points of exceptions was to properly separate return values from error states;

if an exception occurred after the file was created, we woudldn't close the file. It turns out that there's also no need for us to handle FileNotFoundException and IOException separately (unless we really want to). This is because FileNotFoundException is actually an extension (subclass) of IOException. So just catching or handling IOException is enough to cover both cases.

On the next pages, we'll look at how to resolve these problems:

using a throws declaration, we can make our method throw exceptions 'back up' to the caller for the caller to handle rather than having to handle them there and then;

we can use a finally block to make sure the file is closed whether an exception occurs or not. Try & Catch block:

ExceptionsExceptions are generated when a recognized condition, usually an error condition, occurs during the execution of a method

there are a number of standard error conditions defined in Java

Page 11: String Methods in Java

you may define your own error conditions as wellWhen an exception is generated, it is said to be thrown

Java syntax includes a system for managing exceptions, by tracking the potential for each method to throw specific exceptions

for each method that could throw an exception, your code must inform the Java compiler that it could throw that specific exception

the compiler marks that method as potentially throwing that exception, and then requires any code calling the method to handle the possible exception

There are two ways to handle an exception:

you can try the "risky" code, catch the exception, and do something about it, after which the propagation of the exception ceases

you can mark that this method throws that exception, in which case the Java runtime engine will throw the exception back to the method that called this one (since you must inform Java that this method throws the exception, any method that calls this one must be prepared to handle the exception)

So, if you use a method in your code that is marked as throwing a particular exception, the compiler will not allow that code unless you handle the exception

Once an exception is thrown, it propagates backward up the chain of methods, from callees to callers, until it is caught

if the exception occurs in a try block, the JVM looks to the catch block(s) that follow to see if any of them match the exception type

the first one that matches will be executed if none match, then this methods ends, and execution jumps to the method that called this

one, at the point the call was made If an exception is not caught in your code (which would happen if main was marked as throwing the exception) then the JVM will catch the exception, end that thread of execution, and print a stack trace

There are some exceptions that the compiler does not enforce these rules on, those are called unchecked exceptions

Handling ExceptionsLet's say we are writing a method called getThatInt(ResultSet rs), and want to use the method getInt(int column) from the ResultSet passed in as a parameter:

public int getThatInt(ResultSet rs) {

int i = 0;

return rs.getInt(3);

}

A look at the API listing for ResultSet tells us that the getInt() method throws SQLException, so we must handle that in our code

Page 12: String Methods in Java

1. use try and catch 2. public int getThatInt(ResultSet rs) {

3. int i = 0;

4. try {

5. i = rs.getInt(3);

6. }

7. catch (SQLException e) {

8. System.out.println("Exception occurred!");

9. System.out.println(e.getMessage());

10. e.printStackTrace();

11. }

12. return i;

}

13. declare that the method will throw the exception and let our caller handle it 14. public int getThatInt(ResultSet rs) throws SQLException {

15. int i = 0;

16. i = rs.getInt(3);

17. return i;

}

Note that although you are required to "handle" the exception, you aren't necessarily required to do anything useful about it!

Your decision as to which approach to use should be based on where you think responsibility for handling the exception lies - in the example above, the second approach is probably better; so that the code that works more closely with the SQL handles the exception

Exception ObjectsWhen an exception is thrown, an exception object is created and passed to the catch block much like an parameter to a method

occurrence of an exception generates an object (an instance of a class in the exception hierarchy) containing information about the exception

the exception object is passed to the code designated to catch the exception, which may then use methods of the exception object to help handle the situation

There is an API class called Exception

Page 13: String Methods in Java

all exception classes inherit from Exception, which inherits from Throwable another class, Error, also inherits from Throwable your code must handle most exceptions, but generally should not attempt to handle Error

subtypes (like OutOfMemoryError or StackOverflowError) RuntimeException is a subclass of Exception that is a base class for all the exception classes

that you are not obligated to handle, but still might want to anyway (examples are ArithmeticException, from dividing by zero, NullPointerException, and ArrayIndexOutOfBoundsException)

So, there are several classes of exceptions you are not required to handle (shaded below)

these extend either Error or RuntimeException the ones you are required to handle are called checked exceptions generally, runtime exceptions can be prevent by good coding practices:

o avoid null pointer exceptions by checking the reference firsto check array indexes before using them to avoid ArrayIndexOutOfBoundsException o looking at the documentation for allowable parameter values, and testing them

before passing them to a method will prevent IllegalArgumentException

Attempting Risky Code - try and catch If a method is going to resolve an potential exception internally, the line of code that could generate the exception is placed inside a try block

there may be other code inside the try block, before and/or after the risky line(s) - any code that depends upon the risky code's success should be in the try block, since it will automatically be skipped if the exception occurs

Syntaxtry {

code

risky code

Page 14: String Methods in Java

code that depends on the risky code succeeding

}

There is usually at least one catch block immediately after the try block

a catch block must specify what type of exception it will catchSyntaxcatch (ExceptionClassName exceptionObjectName) {

code using methods from exceptionObjectName

}

there can be more than one catch block, each one marked for a specific exception class the exception class that is caught can be any class in the exception hierarchy, either a general

(base) class, or a very specific (derived) class the catch block(s) must handle all checked exceptions that the try block is known to throw

unless you want to throw that exception back to the method that called this one it is possible to have a try block without any catch blocks if you have a finally block

o but any checked exceptions still need to be caught, or the method needs to declare that it throws them

o we will cover finally later in this sectionIf an exception occurs within a try block, execution jumps to the first catch block whose exception class matches the exception that occurred (using an instanceof test)

any steps remaining in the try block are skippedIf no exception occurs, then the catch blocks are skipped

???this would only be legal if the exception could be thrown by the method, either because it is marked to throw that exception, or because it is a RuntimeException

Note: you cannot catch an exception that would not occur in the try block

but you can mark a method as throwing an exception that it doesn't (this leaves open that possibility that an extending class can override the method and actually throw the exception)

Notes on try … catch Blocks and Variable Initialization/ScopeIf declare a variable within a try block, it will not exist outside the try block, since the curly braces define the scope of the variable

you will often need that variable later, if nowhere else other than the catch or finally blocks, so you would need to declare the variable before the try

If you declare but don't initialize a variable before a try block, and the only place you set a value for that variable is in the try block, then it is possible when execution leaves the try ... catch structure that the variable never received a value

so, you would get a "possibly uninitialized value" error message from the compiler, since it actually keeps track of that sort of thing

usually this happens with object references; you would also generally initialize them to null

Code Sample: Java-Exceptions/Demos/ExceptionTest.java

Page 15: String Methods in Java

public class ExceptionTest {

public static void main(String[] args) {

int i, j, x = 5, y = 5, z = 0;

try {

i = x/y;

System.out.println("x/y = " + i);

j = x/z;

System.out.println("x/z = " + j);

}

catch(ArithmeticException e) {

System.out.println("Arithmetic Exception!");

}

System.out.println("Done with test");

}

}

Code Explanation

The program will print the first result, then fail while performing the division for the second equation. Execution will jump to the catch block to print our message on the screen

Note: ArithmeticException is one of the few you are not required to catch, but you can still catch it if you wish.

Example - An Exception You Must HandleThe preceding example used a RuntimeException, which your code is not obligated to handle

Most methods in the I/O classes throw IOException, which is an exception that you must handle

Our KeyboardReader class has try and catch to handle this, essentially stifling the exception, since it is unlikely, if not impossible, to actually get an IOException from the keyboard

Code Sample: Java-Exceptions/Demos/IOExceptionTest.java

import java.io.IOException;

Page 16: String Methods in Java

public class IOExceptionTest {

public static void main(String[] args) {

int num = 0;

num = System.in.read(); // comment out this line

try {

num = System.in.read();

System.out.println("You entered " + (char) num);

}

catch (IOException e) {

System.out.println("IO Exception occurred");

}

}

}

Code Explanation

The line marked to comment out throws IOException, but is not in a try block, so the compiler rejects it. The second read attempt is within a try block, as it should be.

try to compile this code as is, then comment out the indicated line there is no way we can force an IOException from the keyboard to test the catch block

Using Multiple catch BlocksIt is possible that a statement might throw more than one kind of exception

you can list a sequence of catch blocks, one for each possible exception remember that there is an object hierarchy for exceptions - since the first one that matches

is used and the others skipped, you can put a derived class first and its base class later (you will actually get a compiler error if you list a more basic class before a derived class, as it is "unreachable code" )

Code Sample: Java-Exceptions/Demos/MultiCatchTest.java

Page 17: String Methods in Java

import util.KeyboardReader;

public class MultiCatchTest {

public static void main(String[] args) {

int num1, num2;

try {

num1 = KeyboardReader.getPromptedInt("Enter a number: ");

num2 = KeyboardReader.getPromptedInt("Enter another number: ");

System.out.println(num1 + " divided by " + num2 + " is " + num1/num2);

}

catch (NumberFormatException e) {

System.out.println("Number Format Exception occurred");

}

catch (ArithmeticException e) {

System.out.println("Divide by Exception occurred");

}

catch (Exception e) {

System.out.println("General Exception occurred");

}

}

}

Code Explanation

The code in the try block could throw NumberFormatException during the parsing, and ArithmeticException while doing the division, so we have catch blocks for those specific cases. The more generic catch block for Exception would catch other problems, like NullPointerException.

Guaranteeing Execution of Code - the finally BlockTo guarantee that a line of code runs, whether an exception occurs or not, use a finally block after the try … catch blocks

Page 18: String Methods in Java

The code in the finally block will almost always execute, even if an unhandled exception occurs; in fact, even if a return statement is encountered (if System.exit is called, the finally block will not execute, however)

if an exception causes a catch block to execute, the finally block will be executed after the catch block

if an uncaught exception occurs, the finally block executes, and then execution exits this method and the exception is thrown to the method that called this method

Syntaxtry {

risky code block

}

catch (ExceptionClassName exceptionObjectName) {

code to resolve problem

}

finally {

code that will always execute

}

In summary:

a try block is followed by zero or more catch blocks o if the catch block exception classes caught are related, the blocks must be listed in

inheritance order from most derived to most basic there may one finally block as the last block in the structure there must be at least one block from the combined set of catch and finally after the try

It's possible to have a try block followed by a finally block, with no catch block

this is used to prevent an unchecked exception from exiting the method before cleanup code can be executed

Code Sample: Java-Exceptions/Demos/FinallyTest.javaimport util.KeyboardReader;

public class FinallyTest {

public static void main(String[] args) {

String name;

int age;

Page 19: String Methods in Java

try {

name = KeyboardReader.getPromptedString("What is your name: ");

age = KeyboardReader.getPromptedInt("What is your age: ");

System.out.println("Hello " + name);

System.out.println("You are " + age);

}

catch (NumberFormatException e) {

System.out.println("Number Format Exception occurred");

}

catch (Exception e) {

System.out.println("General Exception occurred");

}

finally {

System.out.println("Goodbye");

}

}

}

Code Explanation

The "Goodbye" message will always appear:

when no exception occurs, the finally block will execute after the try if you force an exception by entering a non-numeric age, the catch block will execute,

followed by the finally block ???if you enter 0 for age, the unhandled ArithmeticException will cause execution to back up

the call stack, but only after executing the finally block

Important Notes on finally BlocksAs noted on the previous page, a finally block will almost always execute

it will not execute if the try or catch blocks call System.exit() it will, however, run if the try or catch blocks execute a return statement

A return value from a finally block will supercede one from a try or catch block

Page 20: String Methods in Java

Letting an Exception be Thrown to the Method CallerA method that generates an exception can be written to not catch it - instead it can let it be thrown back to the method that called it

The possibility that a method may throw an exception must be defined with the method

Syntax

[modifiers] returnType functionName(arguments)

throws ExceptionClassName {

body including risky code

}

Then an instance of ExceptionClassName or a class that extends it may be thrown

so, stating that a method throws Exception is about as generic as you can get (stating that it throws Throwable is as generic as you can get, but not recommended)

a method can throw more than one type of exception; in which case you would use a comma-separated list of exception types

In this way, the method is now marked as throwing that type of exception, and an code that calls this method will be obligated to handle it

When you extend a class and override a method, you cannot add exceptions to the throws list

but, a base class method can list exceptions that it does not throw, in the expectation that an overriding method will throw the exception

this is another example of the "inheritance cannot restrict access" principle we saw earlierIf main() throws an exception, the JVM, which runs under Java rules, will handle the exception (by printing a stack trace and closing down the offending thread - in a single-threaded program, this will shut down the JVM).

Throwing an ExceptionThe keyword throw is used to trigger the exception-handling process (or, "raise" the exception, as it is often termed in other languages)

That word is followed by an instance of a throwable object - i.e., an instance of a class that extends Throwable

usually, a new instance of an appropriate exception class is created to contain information about the exception

Example:

suppose a setAge() method expects a non-negative integer - we can have it throw an IllegalArgumentException if it receives a negative value

it makes sense for the method that calls setAge() to do something about the problem, since it is where the illegal number came from

Page 21: String Methods in Java

so, we can declare setAge() as throws IllegalArgumentException public void setAge(int age) throws IllegalArgumentException {

if (age < 0)

throw new IllegalArgumentException("Age must be >= 0");

else

this.age = age;

}

Exercise: Payroll-Exceptions01: Handling NumberFormatException in Payroll

Duration: 5 to 10 minutes.

A though exercise - our program to this point has been prone to potential bad numeric inputs when reading from the keyboard.The parsing methods all throw NumberFormatException

We could now put each line that requests a number inside a small loop

The loop could be controlled by a boolean variable, perhaps with a name like isInvalid, and initially set to true (using the reverse approach is also a possible strategy)

inside the loop, we try the read and parse operations then, still in the try block, change the state of the boolean to one that will end the loop

(because we wouldn't get to that step unless we succeeded) in the catch block, print an error message and request to try again1. Where would you put this code? In the payroll main method or in the KeyboardReader class?

http://learn-java-tutorial.com/Java-Exceptions.cfm-------

Static declaration in JavaStatic/Class methodsThere are two types of methods.

Instance methods are associated with an object and use the instance variables of that object. This is the default.

Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined Math class. (See Math and java.util.Random).

Qualifying a static call

Page 22: String Methods in Java

From outside the defining class, an instance method is called by prefixing it with an object, which is then passed as an implicit parameter to the instance method, eg, inputTF.setText("");

A static method is called by prefixing it with a class name, eg, Math.max(i,j);. Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.

ExampleHere is a typical static method.

class MyUtils {

. . .

//================================================= mean

public static double mean(int[] p) {

int sum = 0; // sum of all the elements

for (int i=0; i<p.length; i++) {

sum += p[i];

}

return ((double)sum) / p.length;

}//endmethod mean

. . .

}

The only data this method uses or changes is from parameters (or local variables of course).

Why declare a method staticThe above mean() method would work just as well if it wasn't declared static, as long as it was called from within the same class. If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly) with an object. Even when used within the class, there are good reasons to define a method as static when it could be.

Documentation. Anyone seeing that a method is static will know how to call it (see below). Similarly, any programmer looking at the code will know that a static method can't interact with instance variables, which makes reading and debugging easier.

Efficiency. A compiler will usually produce slightly more efficient code because no implicit object parameter has to be passed to the method.

Calling static methodsThere are two cases.

Called from within the same class

Page 23: String Methods in Java

Just write the static method name. Eg,

// Called from inside the MyUtils class

double avgAtt = mean(attendance);

Called from outside the class

If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. Eg,

// Called from outside the MyUtils class.

double avgAtt = MyUtils.mean(attendance);

If an object is specified before it, the object value will be ignored and the the class of the object will be used.

Accessing static variablesAltho a static method can't access instance variables, it can access static variables. A common use of static variables is to define "constants". Examples from the Java library are Math.PI or Color.RED. They are qualified with the class name, so you know they are static. Any method, static or not, can access static variables. Instance variables can be accessed only by instance methods.

Alternate callWhat's a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case.