The indexOf() Methods

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:

erc

The second statement works like this:

Substrings of buttercup

The final string could just as easily have been created with a single call:

str = str.substring(4,7);

The indexOf() Methods

There are four varieties of indexOf() in the Java library. Only the following may be included on the AP examination:

indexOf( String str ) Returns the index of the first occurrence of str or -1 if str is not found.

For example

String example = "The sea is calm to-night." ;
int location = example.indexOf( "sea" );

puts the value 4 into location. This

String example = "The sea is calm to-night." ;
int location = example.indexOf( "rats" );

puts the value -1 into location. This

QUESTION 9:

What does the following put into location?

String example = "The sea is calm to-night." ;
int location = example.indexOf( "a" );