Strings

index
BASIC

A string literal is a sequence of zero or more characters enclosed in quotation (double quote) marks. For example:

""       // an empty string
"hello"  // a string containing five characters

In order to put quotation marks inside a string literal, they must be escaped (preceded with a backslash character):

"He said, \"Don't go.\""

Other escape sequences include:

\\    backslash
\n newline
\t tab
\' single quote, or apostrophe

You may not be used to thinking of newlines, tabs, or spaces as "characters," but that is how they are implemented in Java and other programming languages. (Not all characters have printed representations.) When you press the tab key on the keyboard, you are typing a tab character.

The width of a "tab" (that is, the amount of horizontal space used to represent a tab character) varies from program to program and system to system, so you should never use tab characters to control horizontal spacing--use space characters instead. Most IDEs (including BlueJ and Eclipse) will automatically translate tabs into spaces for you.

Strings literals are values, and can be saved in String variables:

String name = "Dr. Dave";

Strings can be concatenated, or "pasted together":

String fullName = firstName + " " + lastName;

Values of other types can be concatenated with Strings:

String message = "There are " + count + " students in CIT591.";

Strings are objects. They have the above special syntax (double quote literals, the plus sign for concatenation) to make them easier to use, but in all other respects, they are objects--in particular, they have a variety of constructors and methods that you can use. For example,

String word = new String(myByteArray);
System.out.println(word + " contains " + word.length() + " characters.");
if (word.endsWith("ing")) System.out.println("gerund");