Strings

In Java, a string is an object. The String class is used to create and store immutable strings (i.e. objects that don't change once they are created). Class StringBuilder creates objects that store flexible and changeable strings.

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";

  // this is not quite equivalent to using the constructor above, 
  //  but you still get a string variable (which is what we care about 
  //  right now)
The constructor with no parameters allows the building of an empty string:
  String s = new String();	// s refers to an empty string object
Note that if you only declare a String variable, but you do not assign it to anything, it is not yet attached to any string:
  String s1;			// s1 does not refer to any string yet

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 builder with initial capacity of 16 characters
  StringBuilder buf1 = new StringBuilder();

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

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

Some common StringBuilder methods

Examples from Deitel (Chapter 30)