Table of ContentsBasic SyntaxArrays

Strings

In Java, you handle strings using the String object. String looks and feels exactly like any other Java-referenced object except for two minor changes: You can use the + and += operators to concatenate (join) strings, and strings cannot be altered. Once they are constructed, they are immutable. Here are some examples of String in action:

int i = 10;
String a = "abc";
a += "def";
String final = a + " - " + i;     // result is "abcdef - 10"

Being a full class object, String has a nice set of methods, such as substring, indexOf, and charAt,you can call to provide more advanced functionality.

Another note about strings (this applies in principle to all objects): When you want to determine whether two String objects are equal by comparing them, keep in mind that there are two quite distinct comparisons you can make. (And I guarantee you'll use the wrong one at some point in a Java program.) Have a look at the following example, and see whether you can spot what's wrong:

String a = "Hello";
String b = "Hello";
if (a == b)
    System.out.println("They are equal");

The problem is with the comparison inside the if statement. This looks like a comparison of the two strings "Hello" and "Hello," which should be equalright? Wrong. If you think back to the details about objects and references, the if statement is comparing whether a is the same object reference as b, not whether they contain the same value. (The fact that they do contain the same value is irrelevant.) What you need to do is compare the contents of each object, not the object itself. For example, the following code is correct:

if (a.equals(b))
    System.out.println("They are equal");

The equals method, available for most objects, will logically compare the values of objects, rather than the references. (You can implement your own equals method for your classes. It's your decision as to what the equality of your objects really means.)

Quite often you will need to convert primitive type into a string. Thankfully, this is a relatively painless process using the String class's valueOf methods. These methods are static so you can call them on the String class, rather than a String object. For example:

String b = String.valueOf(700);

There's a slightly easier way to do this, but it's a little slower. You can use the concatenation operator. For example:

String b = "" + 700;

I had to add a string quote before the number literal to avoid a compile-time error. (String b = 700 is illegal because the compiler interprets this as you trying to assign a primitive type to an object reference.)

NOTE

Tip

This is a simple look at the String class's capabilities. I recommend spending some time reviewing all the capabilities offered in this class.

    Table of ContentsBasic SyntaxArrays