Main Page

Previous Next


You will need to use character strings in most of your programs – headings, names, addresses, product descriptions... – the list is endless. In Java, strings are objects of the class String. The String class is a standard class that comes with Java, and it is specifically designed for creating and processing strings.

String Literals

You have already made extensive use of string literals for output. Just about every time the println() method was used in an example, we used a string literal as the argument. A string literal is a sequence of characters between double quotes:

"This is a string literal!"

This is actually a String literal with a capital S – in other words, a constant object of the class String that the compiler creates for use in your program.

Some characters can't be entered explicitly from the keyboard for inclusion in a string literal. You can't include a double quote character as it is, for example, as this is used to indicate where a string literal begins and ends. You can't include a newline character by pressing the Enter key since this will move the cursor to a new line. As we saw back in Chapter 2, all of these characters are provided in the same way as char constants – you use an escape sequence. All the escape sequences you saw when we looked at char constants apply to strings. The statement:

System.out.println("This is \na string constant!");

will produce the output:

This is
a string constant!

since \n is used for a newline character. Like values of type char, strings are stored internally as Unicode characters. You can also include Unicode character codes in a string as escape sequences of the form \Unnnn where nnnn are the four hexadecimal digits of the Unicode coding for a particular character. The U can be upper or lower case. The Greek letter, (, for example, is \U03C0.

You will recall from our preliminary discussion of classes and objects in Chapter 1 that a class usually contains data and methods and, naturally, this is true of the String class. The sequence of characters included in the string is the class data, and the methods in the class String enable you to process the data in a variety of ways. We will go into the detail of how the class is defined in Chapter 5, but in this chapter we will concentrate on how we can create and use objects of the class String. You know how to define a String literal. The next step is to learn how a String variable is declared and how String objects are created.

Creating String Objects

Just to make sure there is no confusion in your mind, a String variable is simply an object of the class String. You declare a String variable in much the same way as you define a variable of one of the basic types. You can also initialize it in the declaration, which is generally a good idea:

String myString = "My inaugural string";

This declares the variable myString as type String, and initializes it with the value "My inaugural string". You can store a reference to another string in a String variable, once you have declared it, by using an assignment. For example, we can change the value of our String variable myString to the statement:

myString = "Strings can be knotty";

The effect of this is illustrated below:

Click To expand

The string itself is distinct from the variable you use to refer to it. In the same way as we saw with array objects, the variable myString stores a reference to a String object, in other words, it keeps track of where the string object is in memory. When we declare and initialize myString, it links to the initializing string value. When we execute the assignment statement, the original link is severed, the old string is discarded, and the variable myString stores a reference to the new string value. This means that you cannot extend the string that is referred to in a variable of type String. String objects are said to be immutable – which just means that they cannot be changed. To change the string referenced by a String variable you throw away the reference to the old string and replace it with a reference to a new one. The distinction between a String variable and the string it references is not apparent most of the time, but we will see situations later in this chapter where it is important to understand this, so keep it in mind.

You should also keep in mind that characters in a string are Unicode characters, so each one occupies two bytes. This is also not something you need worry about most of the time, but there are occasions where you need to be conscious of that too.

Of course, if you declare a variable of type String in a method without initializing it:

String anyString;            // Uninitialized String variable

then it does not refer to anything. However, if you try to compile a program containing this statement you will get an error. If you don't want it to refer to anything at the outset, for instance, if you may or may not assign a String object to it before you use the variable, then you must initialize it to a special null value:

String anyString = null;     // String variable that doesn't reference a string

The actual value it stores in this situation is referred to as null, so you can test whether a String variable refers to anything or not by a statement such as:

if(anyString == null)
  System.out.println("anyString does not refer to anything!");

The variable anyString will continue to be null until you use an assignment to make it reference a particular string. Attempting to use a variable that has not been initialized is an error. When you declare a String variable, or any other variable that is not an array, in a block of code without initializing it, the compiler can detect any attempts to use the variable before it has a value assigned, and will flag it as an error. As a rule, you should always initialize variables as you declare them.

Arrays of Strings

Since String variables are objects, you can create arrays of strings. You declare an array of String objects with the same mechanism that we used to declare arrays of elements for the basic types. You just use the type String in the declaration. For example, to declare an array of five String objects, you could use the statement:

String[] names = new String[5];

It should now be apparent that the argument to the method main() is an array of String objects.

We can try out arrays of strings with a small example.

Try It Out – Twinkle, Twinkle, Lucky Star

Let's create a console program to generate your lucky star for the day.

public class LuckyStars {
  public static void main(String[] args) {
    String[] stars = {
                        "Robert Redford"  , "Marilyn Monroe",
                        "Boris Karloff"   , "Lassie",
                        "Hopalong Cassidy", "Trigger"
    System.out.println("Your lucky star for today is "
                          + stars[(int)(stars.length*Math.random())]);

How It Works

This program creates the array stars, of type String. The array length will be set to however many initializing values appear between the braces in the declaration statement, six in this case.

We select a random element from the array by creating a random index value within the output statement with the expression (int)(stars.length*Math.random()). Multiplying the random number produced using the method Math.random()by the length of the array, we will get a value between 0.0 and 6.0 since the value returned by random() will be between 0.0 and 1.0. The result won't ever be 6.0 because the value returned by the random() method is strictly less than 1.0, which is just as well as this would be an illegal index value. The result is then cast to an int, making it a valid array index value.

Thus the program selects a random string from the array and displays it.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor