Two-parameter substring()

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

Only one value is legitimate: 0 .

Two-parameter substring()

There is a second version of 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.

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 );