More about Strings

This chapter accompanies the previous one. Read it for even more info on Strings.

7. Two-parameter substring()


Only one value is legitimate: 0 .

Two-parameter substring()

substring( int from, int to )
Create a new object that contains the characters of the method's string from index from to index to-1.
Throws an IndexOutOfBoundsException if from is negative or if from is larger than to.

There is a second version of substring(). Remember those tricky rules about the second version of the method:

  1. If from is negative, an IndexOutOfBoundsException is thrown.
  2. If from is larger than to, an IndexOutOfBoundsException is thrown.
  3. If to is larger than the length, an IndexOutOfBoundsException is thrown.
  4. If from equals to, and both are within range, then an empty string is returned.

These rules make sense. If something can't be done, Java throws an exception.

Question 7:

What do the following statements create?

Line of code:
New String
String line = "buttercup" ;
String a = line.substring( 0, 6 );
String b = line.substring( 6, 9 );
String c = line.substring( 0, 1 );
String d = line.substring( 0, 0 );
String e = line.substring( 5, 5 );
String f = line.substring( 4, line.length()+1 );
String g = line.substring( 6, 3 );