This is the 1st HTML5 slant canvas

KIWY logo depicting a kiwi bird with a candle

k i w y

Need a light for your site?

This is the 2nd HTML5 slant canvas

Strings and StringBuffers

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


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

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)