go to previous page   go to home page   go to next page hear noise
String stringG = new String("You know my methods, Watson.");



A Method that Creates a String

class StringDemo3
  public static void main ( String[] args )
    String str = new String( "Golf is a good walk spoiled." ); // create the original object

    String sub = str.substring(8); //create a new object from the original

    System.out.println( sub );


Many of the methods of String objects create other String objects.

For example, the substring(int begin) method creates a new String that contains a copy of part of the data in the original string. The example program uses this method.

The expression


creates a new String object. That object contains its own data, which are characters copied from the original string. The original string is not changed. The copy starts with character number 8 of the original string and continues to the end. Character numbering starts at zero, so character number 8 in the original string is the first 'a'.

The substring of the original string is contained in a new String object. A reference to that new string is assigned to the reference variable sub.


What characters are contained in the new object?

Remember that character numbering starts at zero.