Strings and Object References in Java

The String class is used for text manipulation. As you read, you will learn different ways to create Strings, methods to manipulate Strings, the String concatenation operator '+', and about how Strings are immutable.

21. More Tricky Rules


Answer:

*
**
***
****
*****

More Tricky Rules

As with the other substring method, this one

public String substring(int beginIndex, int endIndex )

creates a new string. The original string is not changed. Here are some more rules. Essentially, the rules say that if the indexes make no sense, a IndexOutOfBoundsException is thrown.


  1. If beginIndex is negative value, an IndexOutOfBoundsException is thrown.
  2. If beginIndex is larger than endIndex, an IndexOutOfBoundsException is thrown.
  3. If endIndex is larger than the length, an IndexOutOfBoundsException is thrown.
  4. If beginIndex equals endIndex, and both are within range, then an empty string is returned.

Usually, when an exception is thrown your program halts. Future chapters discuss how to deal with exceptions


Question 21:

Decide on what string is formed by the following expressions:

ExpressionNew StringComment
String snake = "Rattlesnake";
snake.substring(0,6)
snake.substring(0,11)
snake.substring(10,11)
snake.substring(6,6)
snake.substring(5,3)
snake.substring(5,12)