Strings and Object References in Java

20. Another substring()


Answer:

ExpressionSubstringComment
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()

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"

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.

bugWarning: the character at endIndex is not included.

The length of the resulting substring is endIndex-beginIndex.

Here is a picture that shows the character numbering. The 'n' is character 11.

subscription

Question 20:

What does this code write?

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