Lesson 8.5 Strings
Strings and String Methods
This lesson will take a little closer look at Java's String class and some of the special methods that are provided for working with Strings.
In Java, Strings are kind of like arrays of char, with one exception: Strings are immutable. That means that once a String is created, you can't change any of the individual characters in that String.
This is not true of a char array. With a char array, this, for instance, is perfectly legal:
char[] pet = { 'C', 'A', 'T' };
pet[0] = 'D';
pet[1] = 'O';
pet[2] = 'G'; |
After executing this code, the array variable pet still refers to the same array, but the contents that are stored in the array have changed. Using the pet variable, we can change the characters that comprise the array.
If pet were a String, however, things would be different. Once you've written:
there is no way to change the individual characters that pet refers to. You can, of course, change the String that pet refers to like this:
but that is an entirely different thing. We've changed the value stored in the variable pet, but, if we peek inside our computer's memory, and look at the place where the characters "CAT" are stored, we'll find that they haven't changed at all. Instead of changing the String "CAT", we just changed pet to look in a different place.
In this sense, a String in Java is treated like a constant. You aren't allowed to change the contents of the number 7, for instance. The constant 7 is what it is; an immutable value which will always have the value 7.
String Arrays
Strings are not exactly arrays, but there will be plenty of time when you need to work with arrays of Strings.
One of the most common instances is when you create an application and you need to pass information into that application. With an applet, this is done through the HTML PARAM tag and the getParameter() method. With an application, arguments are passed to your program via the command line.
The Command Line Arguments
When you use javac to compile your Java programs, [at least on DOS and Unix], you are using a command line program. You type in the word javac, and then follow that with the name of the program you want to compile. The program file name you supply is an example of a command line argument.
As you'll recall, when a Java application begins, it starts with the main() method. The main() method is passed a single argument from the operating system, an array of String, traditionally called args. [Of course, you can name it anything you like.]
Inside your main() method, you can test args.length to see how many arguments were passed. If no arguments were passed to your application, then args.length will be 0.
Since args.length tells you how many arguments there are, the situation practically begs for a for loop. Here's a simple console mode application that you can use to see how this works.
|
Args.java
|
public class Args
{
public static void main(String[] args)
{
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
} |
Since Args is a console mode application, it doesn't need to extend anything, it just needs to have a public static void main() method. Inside the main() method, Args simply loops through the array [args] and prints each command line argument to the console.
Here's what you'll see if you type:
java Args One Two "Three Four"

As you can see, Java separates each word into a separate element of the args array. If you want more than one word to appear as a single argument, you can enclose the argument in quotes like "Three Four" in the example.
String Methods
When you first met the String class in Lesson 3.2, you saw that Strings had some of the characteristics of primitives and some characteristics of objects. One of the ways in which Strings are like objects is that the String class has a rich set of methods you can use to manipulate String objects.
Let's look at a few.
String Comparison
One of the commonest String operations is to compare two Strings. You should not use the equality operator [==] to see if two Strings are equal, because that only compares whether two String variables refer to the same actual String. When used with Strings, the equality operator measures identity.
Instead of the equality operator, you should use one of these methods.
equals()
Returns true if the contents of two Strings exactly match, false otherwise.
"cat".equals("cat"); // true
"cat".equals("Cat"); // false |
equalsIgnoreCase()
Returns true if the contents of two Strings match when case is not considered, false otherwise.
"cat".equalsIgnoreCase("cat");// T
"cat".equalsIgnoreCase("Cat");// T
"cat".equalsIgnoreCase("dog");// F |
compareTo()
Returns 0 if both Strings are equal. Returns a negative number if the String on the left is "lower" than the String on the right.
| "cat".compareTo("cat"); // 0 - equal
// "cat" > "Cat" (Unicode ordering)
"cat".compareTo("Cat"); // Positive
// "cat" < "dog"
"cat".compareTo("dog"); // Negative |
Searching Methods
endsWith(), startsWith()
Returns true if the String on the left ends or starts with the String on the right.
"Junk.java".endsWith(".java"); // true
"testFile.txt".startsWith("test"); // true |
indexOf(), lastIndexOf()
There are several overloaded versions of each of these methods, which search the String on the left for the character or String on the right. The indexOf() method starts its search at the beginning of the String, and the lastIndexOf() method starts searching at the end of the String. Both methods return -1 if the character or String searched for is not found.
"Abadaba".indexOf("daba"); // 3
"Abadaba".indexOf('o'); // -1
"Abadaba".indexOf("ba"); // 1
"Abadaba".lastIndexOf("ba"); // 5 |
Conversion Methods
Because Strings are immutable, the Java String conversion methods don't change the String they are operating on; instead, they produce a new String. A common error is to forget this and not save the results of the conversion in a new String object.
toUpperCase(), toLowerCase()
Returns the String on the left translated into either upper or lower case.
"pet".toUpperCase();//Returns "PET"
"Pet".toLowerCase();//Returns "pet" |
replace(a,b)
Returns a String with all occurances of character a replaced by character b.
"Mom".replace('m', 'd');// Mod
"Dad".replace('D', 'B');// Bad |
substring()
Returns a portion of the String on the left.
"Summer".substring(1); // "ummer"
"Summer".substring(0, 3); // "Sum" |
Something to Talk About
Here's an exercise that uses command-line arguments and some String methods. How would you write a simple loop that prints each of the arguments passed on the command line in reverse order, and that prints a special message, [of your devising] if any of the command line arguments are Java source code files?
Please continue to the next section of this lesson.
|