The Nuts and Bolts of the Java Language |
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.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."); } }The character-counting program uses Strings in two different places. The first is in the definition of the
main()
method:This code explicitly declares an array, namedString args[]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:Two of the strings concatenated together are literal strings: ""Input has " + count + " chars."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
The Nuts and Bolts of the Java Language |