Java Reference
In-Depth Information
There is no character at position 12 in
s2
, but this call asks for characters starting
at position 8 that come before position 12, so this actually makes sense.
You have to be careful about what indexes you use, though. With the
substring
method you can ask for the position just beyond the end of the
String
, but you can't
ask for anything beyond that. For example, if you ask for
s2.substring(8, 13) // out of bounds!
your program will generate an execution error. Similarly, if you ask for the
charAt
at a
nonexistent position, your program will generate an execution error. These errors are
known as
exceptions.
Exceptions are runtime errors as mentioned in Chapter 1.
Exception
A runtime error that prevents a program from continuing its normal
execution.
We say that an exception is
thrown
when an error is encountered. When an excep-
tion is thrown, Java looks to see if you have written code to handle it. If not, program
execution is halted and you will see what is known as a
stack trace
or
back trace.
The
stack trace shows you the series of methods that have been called, in reverse order. In
the case of bad
String
indexes, the exception prints a message such as the following
to the console:
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException:
String index out of range: 13
at java.lang.String.substring(Unknown Source)
at ExampleProgram.main(ExampleProgram.java:3)
You can use
String
s as parameters to methods. For example, the following pro-
gram uses
String
parameters to eliminate some of the redundancy in a popular chil-
dren's song:
1
public class
BusSong {
2
public static void
main(String[] args) {
3 verse("wheels", "go", "round and round");
4 verse("wipers", "go", "swish, swish, swish");
5 verse("horn", "goes", "beep, beep, beep");
6 }
7
8
public static void
verse(String item, String verb, String sound) {
9 System.out.println("The " + item + " on the bus " +
10
verb + " " + sound + ",");
Search WWH ::
Custom Search