Versions of 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:

The program will throw a NullPointerException (and usually stop running).

Versions of substring()

There are two versions of substring:

substring( int from ) Create a new object that contains the characters of the method's string from index from to the end of the string. Throws an IndexOutOfBoundsException if from is negative or larger than the length of the string.
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 if from is larger than to.

There are some tricky rules about the first version of the method:

  1. If from is exactly equal to the length of the original string, a substring is created, but it contains no characters (it is an empty string)
  2. If from is greather than the length of the original string, or a negative value, a IndexOutOfBoundsException is thrown (and for now, your program crashes).

QUESTION 5:

What do the following statements create?

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