Strings Introduction
Strings are what I classify (along with arrays) as half object and half primitive type. In this unit, we will learn more about the 'half' object part of strings.
Strings are clearly incredibly useful. Every instruction that you type into the computer is a string. The computer then manipulates it depending which application you are using. All of the major applications in use today are glorified text editors - Word Processors, Spreadsheets, Databases, E-mail, Web Pages - in some cases greatly glorified :)
In Java, strings methods are located in java.lang.String. It is useful to keep in mind the following things when dealing with strings. A string is essentially a collection of words, which is in turn a collection of chars. For example, "Grace Murray Hopper" is a string of 3 words and 19 chars.
All of the chars are stored as ASCII numbers, so the string actually looks like this in memory:
1. Basic Strings Questions
Try the following code to understand what each function does. Looking at the help file should simplify this task greatly.
1. Concatenation: What does the + sign do when used with strings?
String dog = "dog";
String space = " ";
String house = "house";
String all = dog + space + house;
System.out.println (all);
2. What does .length() do?
String fred = "fred";
System.out.println (fred + "'s length is " + fred.length ());
3. What does .substring() do?
String fred = "fred";
System.out.println (fred + "'s middle two characters are " + fred.substring (1, 3));
4. What does .toLowerCase() and .toUpperCase() do?
String SHOUT = "SHOUT";
System.out.println (SHOUT + " in small letters is " + SHOUT.toLowerCase ());
String normal = "normal";
System.out.println (normal + " in capital letters is " + normal.toUpperCase ());
5. What does .replace() do?
String banana = "banana";
banana = banana.replace ('a', 'g');
System.out.println (banana);
6. What does .trim() do?
String manyspaces = " al li ga tor ";
manyspaces = manyspaces.trim ();
System.out.println (manyspaces);
7. Find another String method via the help file, describe how it works and give an example of it.
8. Run the file here, add in the appropriate code to make the Haiku Error Messages. (Follow the comments)