Home
Examples
Labs
Assignment
Marks
Midterm
Final Exam
Resources

String Objects

A String is a sequence of characters.  Strings in java are represented as objects.  String objects have both state and behaviour - they have information that they must remember, and also stuff that they know how to do.  String objects must remember the sequence of characters that they represent.  String objects know how to do things like convert their character sequence to upper or lower case.


Creating new Objects

  • objects are created in java using the keyword new.
  • the keyword new is used to invoke a constructor for the object.
  • every class has at least one constructor method.
  • constructor methods describe what java should do whenever a new object is created from a particular class.
  • constructors sometimes take arguements to use while creating the new object.
  • all constructors return a reference describing where to find the new object that was created.


Using new to Create a String Object

The following snippet of code shows how to create a String object using the keyword new to invoke the String constructor.  The newly created String object will represent the sequence of characters, "Java String" - without the quotes.

        // Create a String variable
           String s;

        // Assign variable s the reference to
        // the newly created String object
           s = new String("Java String");



String Methods

This is a brief list of String methods.  These are some of the things that String objects know how to do.  This list is nowhere near complete however.  If you are interested to learn more about String methods you should check out the java API.  API stands for Application Programming Interface.  The API describes all components of the java language in detail.
  • concat(String str)
    Returns a new String object where the character sequence of the original String has the specified String str added to the end.
            // Create the String icecream and
            // save the reference to it in t
               String s = "ice";
               String t = s.concat("cream");


  • indexOf(String str)
    Returns the index within the String of the first occurrence of the specified substring str.  Remember that the character positions in a String are numdered starting at zero.
            // Get the position of the space
               String s = "Tim McGraw";
               int i = s.indexOf(" ");


  • length()
    Returns the length of the String.  The length is the total number of characters in a String, not the index of the last character position.
            // The length of String s is 12
               String s = "Julie Fraser";
               int i = s.lenght();


  • substring(int beginIndex)
    substring(int beginIndex, int endIndex)

    Returns a new String that is a substring of the original.  If you only specify one index position, java will assume that the second index position is the end of the String.
            // Put the String "def" int
               String s = "abcdefg";
               String t = s.substring(3,6);


  • toLowerCase()
    Returns a new String that is the same as the original String, but with all of the characters converted to lower case.
            // Put a lowerCase version of s in t
               String s = "SCREAMING!";
               String t = s.toLowerCase();


  • toUpperCase()
    Returns a new String that is the same as the original String, but with all of the characters converted to upper case.
            // Put an upperCase version of s in t
               String s = "shhhh!";
               String t = s.toUpperCase();


  • trim()
    Returns a new String the same as the original, but with the white (blank) space removed from both ends.
            // Put a trimmed verson of s in t
               String s = "   January  ";
               String t = s.trim();




Immutable

In java we say that Strings are immutable.  When we send a String object a message like trim() or toUpperCase() the String does not change itself.  The String stays the same and returns a new object like itself, but with the change applied.  This is the reason why you can't just write: s.toUpperCase();.  Instead, if you want a String to change itself, you have to write s = s.toUpperCase();.



Cascading

Using the object returned by one method as the receiver for another method call.  In this example, the String object returned by the toUpperCase() method is immediately sent the trim() message.

       // trim and upcase with cascading
          String t = s.toUpperCase().trim();


Composition

Using the object returned by one method as an argument for another method call.  In this example, the readLine() method returns a String object.  The returned String object is used as an argument for the parseInt() method.

       // parseInt with composition
          int i = Integer.parseInt(kb.readLine());


Using Objects for Keyboard Input

Often it is necessary for a java program to use or access a resource that exists outside of itself.  For example, you will frequently want to read information from the keyboard, or from an input file or webpage.  In java when you want to access the keyboard, a file, or a webpage, you must use objects in your program to help you establish a link to the outside resource that you want to read from or write to.


  • Reading Strings from the keyboard - To establish a link to the keyboard you need a BufferedReader and an InputStreamReader.  InputStreamReader objects know how to read characters from an InputStream.  The name of the default InputStream is System.in.  For you, this is automatically the keyboard.  BufferedReader objects know how to take an InputStreamReader and read Strings from it one line at a time.
      // Create a link to the keyboard
         BufferedReader kb = new BufferedReader(
                               new InputStreamReader(System.in));
    
      // Ask the user to type something
         System.out.println(" Please type something.");
         System.out.print(" > ");
    
      // Read whatever the user typed on the
      // keyboard into a String variable
         String s = kb.readLine();