More about Strings

This chapter accompanies the previous one. Read it for even more info on Strings.

6. Play with substring()


(a new String is created,
containing all the characters of the original)
Line of code:
New String
String line = "buttercup" ;
String a = line.substring( 0 );
String b = line.substring( 6 );
String c = line.substring( 9 );
(an empty string is created)
String d = line.substring( line.length() );
(an empty string is created)
String e = line.substring( line.length()+1 );
String f = line.substring( -1 );

Play with substring()

Play with substring() with the following demonstration. The parameter for substring() must be an integer literal like 0 or 12.

Try some other strings than the one suggested. Be sure to enclose the characters of the string with quote marks. (However, the demonstration does not support escape characters in the string, so don't try tab characters.)

The resulting string may sometimes be the empty string or contain spaces. The quote marks in the result are not part of the string that the substring method produces.

In the original version of this page the demonstration was a Java applet. The demonstration uses Javascript, but works the same as Java.

If the demonstration does not work on your computer, Javascript might not be enabled. Just skip this page.

String line =  ; // Enter a string here between quotes

String result = line.substring(  ) ; // Enter a single integer parameter


Question 6:

The empty string "" is a legitimate String object and it has the substring( int from ) method.

What are the valid values for its from parameter?

(Test your answer with the above demonstration.)