These classnotes are depreciated. As of 2005, I no longer teach the classes. Notes will remain online for legacy purposes

JAVA01/Strings And Characters

Classnotes | JAVA01 | RecentChanges | Preferences

Showing revision 1
Strings are a common feature in computer programming because they provide a way to store text and present it to users. We have already seen the way strings are created and manipulated, but let's look at some of the functionality you can do with strings.

String Operators

Strings can be acted upon using the "+" operator. "+" is used to join strings together. Consider the following declarations:
 String a = "Hello ";
 String b = "World, ";
 String c = "I ";

You could combine these strings, with an additional value, thusly

 String d = a + b + c + "am a Computer.";

and the final string, d, would equal:

 Hello World, I am a Computer.

The item passed to println can be a string, thus you can use this operator there as well:

 System.out.println(a + b + c + "am a Computer.");

which would print

 Hello World, I am a Computer.

You can also combine other data types with strings this way. For example, if you had the following definition:

 int keys = 2;

you could set the following string

 String myKeys = "I have " + keys + " keys.";

Special Characters in Strings

Now that you have seen how to create strings, let's say that you wanted to place the following text:
 "Hello World."
 I am a Computer.

into a single string. How would you do that?

You would need to use special characters to correlate to the non-printable characters (new line) in the text above. The following are special characters which can be used in a string:

 \'     Single quotation mark
 \"    Double quotation mark
 \\    Backslash
 \t    Tab
 \b    Backspace
 \r     Carriage Return
 \f     Formfeed
 \n    New line

So the above text could be set to a string like this:

 String k = "\"Hello World.\"\nI am a Computer";


Classnotes | JAVA01 | RecentChanges | Preferences
This page is read-only | View other revisions | View current revision
Edited May 27, 2003 10:16 pm (diff)
Search:
(C) Copyright 2003 Samuel Hart
Creative Commons License
This work is licensed under a Creative Commons License.