Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language


Character Data

class Count {
    public static void main(String args[])
	throws java.io.IOException
    {
        int count = 0;

        while (System.in.read() != -1)
            count++;
        System.out.println("Input has " + count + " chars.");
    }
}    
In C and C++, strings are simply null-terminated arrays of characters. However, in the Java language, strings are first-class objects--instances of the String class. Like System, the String class is a member of the java.lang package.

The character-counting program uses Strings in two different places. The first is in the definition of the main() method:

    String args[]
This code explicitly declares an array, named args, that contains String objects. The empty brackets indicate that the length of the array is unknown at compilation time.

The compiler always allocates a String object when it encounters a literal string--a string of characters between double quotation marks. So the program implicitly allocates two String objects with "Input has " and " chars.".

String Concatenation

The Java language lets you concatenate strings together easily with the + operator. The example program uses this feature of the Java language to print its output. The following code snippet concatenates three strings together to produce its output:
"Input has " + count + " chars."
Two of the strings concatenated together are literal strings: "Input has " and " chars." The third string--the one in the middle--is actually an integer that first gets converted to a string and then concatenated to the others.

See Also

java.lang.String
The String and StringBuffer Classes


Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language