Classnotes | JAVA01 | RecentChanges | Preferences 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";
Determining the Length of a String
It can be useful at times to determine the length of a string in characters. You do this by using the length() method:
String name = "Sam Hart";
int nameLength = name.length();
Comparing Two Strings
One thing you will be testing often in your programs is whether one string is equal to another. You do this by using the equals() method in a very similar fashion to how you check the length of a string:
String name1 = "Sam Hart";
String name2 = "Bob Jenkowitz";
System.out.println("The two names are the same?");
System.out.println("Answer: " + name2.equals(name1));