Strings and StringBuilders

In Java, a string is an object. String processing involves three important pre-built classes:

The String class

A common way to construct a String

One constructor allows the use of a string literal as the parameter. Example string constructions:
  String greeting = new String("Hello, World!");
  String name = new String("Marvin Dipwart");
  String subject = new String("Math");

  // also, a shorthand notation for building strings (below)

  String sentence = "The quick brown fox sat around for a while";

Some commonly used String class methods

The StringBuilder class

Creating

Three of the four constructors shown here. Here are sample creations:
  // creates an empty string buffer with initial capacity of 16 characters
  StringBuilder buf1 = new StringBuilder();

  // creates empty string buffer with initial capacity given in parameter
  StringBuilder buf2 = new StringBuilder(50);

  // creates string buffer filled with argument -- initial capacity is 
  // length of given string plus 16
  StringBuilder buf3 = new StringBuilder("Hello, World");

Some common StringBuilder methods

The StringTokenizer class

Example usage:
  String s1 = "The quick brown fox jumped over the lazy dog.";
  StringTokenizer st = new StringTokenizer(s1);
  // default delimiters are space, tab, newline, carriage return

  System.out.print("Number of words = " + st.countTokens());
  // prints "Number of words = 9"

  String s2 = st.nextToken();		// s2 = "The"
  String s3 = st.nextToken();		// s3 = "quick"
  String s4 = st.nextToken();		// s4 = "brown"

Command line arguments

Recall that the main method of a Java program looks like this:
  public static void main(String[] args)
The String[] args part allows a set of arguments to be passed into the program from the command line. Suppose we execute a java program with the following command:
  java MyProgram file1.txt output lazy
Inside the main program, the arguments are stored in an array of strings:
  args[0] is "file1.txt"
  args[1] is "output"
  args[2] is "lazy"
  args.length -- stores the number of parameters passed (3, in this example)

Examples from Deitel (Chapter 30)