Strings and StringBuffers

In Java, a string is an object (of class type String). There is also a StringBuffer class that can be used for building and manipulating string data.

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 StringBuffer class

Creating

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

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

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

Some common StringBuffer methods

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 29)