A string is simply a collection of characters. In other coding languages, a string is often implemented manually by the programmer using an array of characters. It also often requires a great deal of time writing code to support an array of characters, like allocating memory for them, searching for sub-strings, etc. Arrays of characters can still be programmed in Java.

char[] myCharArray = {'U', 's', 'e', ' ', 'a', ' ', 'c', 'l', 'a', 's', 's'};

However, the Java language includes a String class as the standard for storing string data. This String class is a member of the java.lang package and is readily available for you to use in your Java code. We will look at packages in detail in , so don't worry about them for now; all you need to know now is that you may start using the String class in your code right away, like this:

String myString;

Here we have a reference to a String object that is currently equal to null, ready to be assigned to a String object. There are two ways in which you can create a String object. The simplest way is to specify a character string enclosed in double quotation marks; this is known as a string literal.

myString = "String literal";
// you may create a string with no text also myString = "";

We have been using string literals so far in this tutorial as parameters to the method System.out.println to print text to the console screen. All string literals are implemented as instances of the String class. The other method for creating a String object is the method used to create most other objects in Java: calling a constructor.

// constructor that takes a string literal argument myString = new String("String literal");
// or create a string object with no text myString = new String("");
// or the default constructor does the same myString = new String();

There is also a constructor that takes an array of characters as a parameter, creating a String object with the value of the characters stored in the array.

char[] myCharArray = {'c', 'h', 'a', 'r', 's'};
myString = new String(myCharArray);

The character string data held in a String object is constant; its value cannot be changed once it has been defined. String objects are therefore known as being immutable. The StringBuffer class is used for defining character strings that are mutable—the character string data in the object can be changed. We will discuss the StringBuffer class a little later in this chapter.

String Concatenation

In Java the + operator, as well as being used for numeric addition, is also used for string concatenation (i.e., joining two string values to create one combined value). In fact, when using the + operator for string concatenation in Java, the append method of the StringBuffer class is actually used to create a new String object with the value of the operands combined.

String sentence = "Hello" + " World";

Here the two string values are joined together, creating a new String object containing the data "Hello World". You can also use the assignment operator (+=) for string concatenation. The following example is a very simple example to get you started using strings.

public class SimpleStrings
 public static void main(String args[])
 String sentence = "Hello ";
 String word = "World";
 sentence += word;

When compiling and running this example, you should get output like the following screen shot.

Java Click To expand

When the string concatenation takes place, a new String object is created containing the text "Hello World" to which the variable sentence references. The String object with the text "World" is still referenced by the variable word, and the String object with the text "Hello" is no longer referenced by sentence and is lost.

Strings with Character Escape Sequences

In we mentioned character escape sequences (please return to that chapter to view a table showing the list of character escape sequences). These character escape sequences are used with strings to perform special printing tasks at the point in which they appear in the text. Let's take for example the newline character escape sequence \n. This escape sequence moves the print caret onto a new line; it is not two characters like \ and n but one.

System.out.println("Move to a new line");
System.out.print("Also move to a new line\n");

The first line of code here uses the method println, which is a member of the object out that in turn is a static member of the class System. This method prints whatever value is passed to it to the console screen and moves the caret position to the beginning of the next line. The method print in the second line of code only prints text to the console screen, leaving the caret position where it is after the given text is printed without moving onto the next line. However, we include the newline \n character escape sequence onto the end of the printed string. This will move the caret position to a new line similarly to the first line of code. The character escape sequences are actually characters themselves, in case you have not yet realized. This means they all have numeric values, just like the letter A has the numeric value 65 and \n has the value 10.

System.out.print("New line here too" + (char)10);

Here we typecast the value 10 to a type char, which, when appended to the string literal "New line here too", creates a new String object with the newline character escape sequence as the end character. You can therefore set any character in the string as a character escape sequence.

String quote = "Well I've had a wonderful time,\n but this wasn't it";

This code will print all of the text up until the character escape sequence \n, and at this point, the caret position is moved onto the new line, where the remaining (hopefully untrue) text is printed. There may be a time where you need to print out the text that makes up a character escape sequence; we may try the following code.

System.out.println("You use \n to go to a new line");

This text will move the caret onto a new line after the text "You use " has been printed to the console and then only the text after the \n is printed. What you need to do is include another preceding backslash character (\) with the escape sequence text as follows.

System.out.println("You use \\n to go to a new line");

This code will print the text that we initially intended. It's quite ironic actually that we change the text by adding a backslash character (\) in order to ensure that the text is printed as it was before we changed it (by doing this, we are actually escaping the \ character). Anyway, you may add the backslash character to any of the character escape sequences if you want to print the actual text. Printing special characters is also implemented using character escape sequences such as single and double quotation marks. For example, the double quotation marks in Java are used to delimit the text for a string literal. What if we want to enclose a quote in double quotation marks followed by the person who said the quote? We could not just type out the text as it is read. We would need to add a backslash character (\) to any special characters in the text that we just wanted to be treated as normal characters.

String quote = "\"I find television very educating. Every time somebody turns on the set, I go into the other room and read a tutorial.\", Groucho Marx";

You may want to set the value of a character variable to the single quotation character ('). To do this, you must precede the character symbol with a backslash character (\) as follows.

char normalCharacter = 'A';
char singleQuotation = '\'';

You should take a break from coding now and go in search of Groucho Marx's most famous quotes, which are very funny.

Arrays of Strings

So far we have looked at arrays of primitive data types, like int and boolean. Here we look at arrays of Strings, which are objects. The code is mostly the same; the problem is adapting your mind to understanding that Strings are different because they are objects, and therefore the array elements reference other objects of type String; they are not actually the data itself, like they are for primitive data types. We can declare an array of Strings, as follows.

String[] names;

We can initialize the array similar to the way we learned in the "Arrays" section earlier.

names = new String[5];

This code creates an array of length 5 and of type String. Each element in the array is a reference to a String object, each of which currently is equal to null; hence, they do not currently reference a String object. We can then create String objects and assign them to be referenced by elements in the array.

names[0] = "Glenn"; // string literal names[1] = new String("Andrew"); // constructor

Remember, there are two ways to create String objects, defining a String as a string literal or by using a constructor of the String class. Here, the first two elements in the array reference objects, whereas the other three elements (with indices 2, 3, and 4, respectively) remain equal to null (not referencing a String object). As the elements in the array are just references, we could swap the references of the first two elements, as follows.

String saveString = names[0];
names[0] = names[1];
names[1] = saveString;

Now the first element references the String object containing the text "Andrew" and the second element references the String containing the text "Glenn". No new String objects are created in these three lines of code; the references are simply swapped. We can also use the alternate method for initializing the string array.

names = {"Glenn", "Andrew", "Jim", "Wes", "Leeloo"};
// who is the fifth element?

Or more importantly, you can create a String object using constructors also.

names = {new String("Glenn"), new String("Andrew"),
 new String("Jim"), new String("Wes"),
 new String("Leeloo")

This technique is more important to note because most other objects are created using their constructors like we have used above, whereas String objects can also be created specially using string literals.

Program Arguments

In case you haven't realized it thus far, we have already been declaring an array of String objects, from the first example until now, as a parameter to the method main.

public static void main(String[] args)
 // code here

The parameter args is a parameter variable just like we used before when declaring our own methods with parameters, like in . You can call this parameter whatever you like, as it is just an identifier like any other variable you declare, although the type, an array of String objects, must remain the same.

public static void main(String[] programArguments)
 // code here

A program argument is a text value (of which there may be many) that is passed to the program at run time. In Java, program arguments are defined as String objects that are passed to the method main in the aforementioned String array. We must first define program arguments and then write a program to take a look at the arguments. We can create what is known as an echo program, echoing the program arguments to the console screen. Defining program arguments is very simple. Append text separated by spaces onto the original command line that you have been using to run your programs. Each section of text separated by a space represents one element in the String array argument of main. We have already looked at the command line used to run Java programs in and have been using them since, perhaps in the batch file .bat that you created for convenience. Let's imagine that we have a program called, which has been compiled to create a class file called Echo.class. This command line assumes also that the program is situated in the directory c:\java\Echoapp\ and that the java.exe program is situated in the directory c:\j2sdk1.4.1_01\bin\. The following command line would be entered in order to run the program Echo.class.

c:\j2sdk1.4.1_01\bin\java.exe c:\java\Echoapp\Echo

You can enter this text in the command prompt or in a batch file and then run the batch file. Ideally, if all of your paths were set, this command would be entered as follows.

java Echo

For more details on this, please refer back to . Now you need to add some text onto the end of the command, like so.

java Echo who what where when why


If you are using an integrated development environment (IDE) to execute your Java programs, there should be an option somewhere to specify program arguments for your program. Try the Project menu item and then Settings or Options. There should be a text dialog somewhere for you to enter the arguments. Otherwise, you will just have to run the program manually using the command line.

Now we need to create an echo program to test that the program arguments are working. Here is the code for the example

public class Echo
 public static void main(String args[])
 { System.out.println("There are " + args.length + " arguments:");
 for(int i=0; i<args.length; i++)

When specifying the program arguments who, what, where, when, and why when running the program, you should get output similar to the following screen shot.

Java Click To expand

The length member of the array object is used to control which array elements are accessed. In other coding languages, the number of program arguments needs to be specified as a separate variable using a second parameter of main; in Java it does not, as the array object itself stores this information.