Google
 

 

up previous next contents
Up: 2. Day 2: The Previous: 2.4 Arrays Next: 2.6 Comments and Javadoc   Contents

Subsections

2.5 Strings

2.5.1 String objects

  • Java provides a String class to deal with sequences of characters.
    String username = "Fred Flinstone";
    
  • The String class provides a variety of methods to operate on String objects.
  • The equals() method is used to compare Strings.
  • The length() method returns the number of characters in the String.
  • The + operator is used for String concatenation.
  • String objects are read-only (also called immutable).
  • In the example below, the second assignment gives a new value to the object reference str, not to the contents of the string:
    str = "Fred";
    str = "Barney"
    
  • An array of char is not a String.

2.5.2 StringBuffer class

  • The StringBuffer class is often used when you need the ability to modify strings in your programs.
  • Manipulating a StringBuffer can be faster than creating-re-creating String objects during heavy text manipulation.
  • StringBuffer objects are mutable.
  • Useful methods include append(), charAt(), indexOf(), insert(), length(), and replace().

2.5.2.1 Exercise

  • What is the output of the following class?
    class StringTest {
       public static void main (String args[]) {
          String str1 = null;
          String str2 = null;
          str1 = "Fred";
          str2 = str1;
          System.out.println("str1: " + str1);
          System.out.println("str2: " + str2);
          
          str1 = "Barney";
          System.out.println("str1: " + str1);
          System.out.println("str2: " + str2);
       }
    }
    

2.5.2.2 Exercise

  • Modify the Hello application so it reads the a user's name from the command line, and writes the user's name as part of the output.
  • Here is the source code for the original class:
    public class Hello
    {
      public static void main(String[] args) {
        System.out.println( "Hello, world" );
      }
    }
    
  • Assuming that the users name is Al, after the changes the output of the program should be:
    Hello, Al