Another 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:

Expression Substring Comment
String snake = "Rattlesnake"; "Rattlesnake" Create original String
snake.substring(6) "snake" Characters starting at character 6 to the end
snake.substring(0) "Rattlesnake" The new substring contains all the characters of the original string
snake.substring(10) "e" Character 10 is the last one
snake.substring(11) "" If beginIndex==length, an empty substring is created.
snake.substring(12)   If beginIndex is greater than length, a
IndexOutOfBoundsException is thrown.

Another substring()

Here is another method of String objects:

substring(int beginIndex, int endIndex)

This method creates a new String containing characters from the original string starting at beginIndex and ending at endIndex-1. Warning: the character at endIndex is not included.

subscription
Expression Result
String source = "Subscription"; "Subscription"
source.substring(0,3) "Sub"
source.substring(3,9) "script"
source.substring(0,0) ""
source.substring(0,1) "S"
source.substring(0,source.length()) "Subscription"

The length of the resulting substring is endIndex-beginIndex.

QUESTION 20:

Examine the following code:

String stars = "*****" ;
int j = 1;
while ( j <= stars.length() )
{
  System.out.println( stars.substring(0,j) );
  j = j+1;
}