Java Notes
String Overview
Strings are sequences of Unicode characters. In many programming languages strings are are stored in arrays of characters. However, in Java strings are a separate object type, String. The "+" operator is used for concatenation, but all other operations on strings are done with methods in the String class.
See the Summary - Strings for an overview of the methods in String and related classes.
Related types and classes
String |
The basic class for strings. String objects can NOT be changed. |
char |
Primitive type for 16-bit Unicode characters. |
Character |
Primarily useful for its utility functions for working with characters. |
StringBuffer |
StringBuffers are used to build or change strings. Conversion between String and StringBuffer is easy. |
StringBuilder |
StringBuilder was added in Java 5. It is the same as StringBuilder, but slightly faster because it's unsynchronized. |
StringTokenizer |
Used to break a String into tokens (words). |
BufferedReader BufferedWriter |
Useful for reading and writing text files. |
Pattern, Matcher |
JDK 1.4 added java.util.Pattern and Matcher to do regular expression matching. |
String literals
To write a constant string, put the characters between double quotes, eg "abc".
Escape Character
There are some characters that can't be written directly in a string.
The backslash ('\') character preceeds any of these special characters.
For example, if a string contains a double quotes, put a
backslash ('\') in front of each internal double quote, eg "abc\"def\"ghi".
The other most common escape character is the newline character, which
is written as "n" following the backslash. For example, the following
string will produces two output lines. Note that the compiler replaces the
backslash plus character with the one desired character. Eg, "\n".length()
is one.
System.out.println("This is the first\nand this is the second line.");
The "empty" string
The String equivalent of 0, is the string with no characters, "".
Concatenation
Expression | Value |
1 + 2 | 3 |
"1" + 2 | "12" |
1 + "2" | "12" |
"1" + 2 + 3 | "123" |
1 + 2 + "3" | "33" |
Putting two strings together to make a third string is called concatenation. In Java the concatenation operator is '+', the same operator as for adding numbers. If either operand is a String, Java will convert the other operand to a String (if possible) and concatenate the two.
Upper- and lowercase
To change to uppercase (and similarly to lowercase), Java has two methods, depending on whether you have a single character (eg, c) or a String (eg, s).
Converting a string to uppercase
s = s.toUpperCase();
Converting a character to uppercase
c = Character.toUpperCase(c);
Of course, you don't have to assign these values back to themselves -- you can use the values where you want.