next up previous contents
Next: Arrays Up: Compound statements Previous: Comments   Contents

Strings

Strings in Java are handled using the built-in class String. String variables are declared as follows:

  String s,t;

String constants are enclosed in double quotes, as usual. Thus, one can write:

  String s = "Hello", t = "world";

Strings are not arrays of characters, so one cannot refer to s[i], t[j] etc. To change the contents of string s from "Hello" to "Help!" we cannot just say:

  s[3] = 'p'; s[4] = '!';

What we can do is invoke the method substring in the String class and say something like:

  s = s.substring(0,3) + "p!";

Here, s.substring(0,3) returns the substring of length 3 starting at position 0. The operator + is overloaded to mean concatenation for strings.

String objects are immutable--if a string changes, you get a new String object. Even though, in principle, the new value of s fits in the same amount of space as the old one, Java creates a new object with the contents "Help!" and s points to this new object henceforth.

What happens to the old object? It is automatically returned to the system: Java does runtime ``garbage collection'' so we do not have to explicitly return dynamically allocated storage using something like free(..), unlike in C.

Remember that an expression like

  s = "A new piece of text";

is an abbreviation for something like

  s = new String("A new piece of text");

The string passed as a parameter to new is converted into the appropriate internal representation by the constructor for String class. The point that needs to be noted is that though String is a built in class like any other and has its own methods etc, there are some short cuts built-in to Java, such as:

The length of a string s can be obtained by calling the method s.length(). Note that we don't know (and don't care) how strings are actually represented in the String class--for instance, we don't have the C headache of remembering that we always need to put a '$\backslash$0' at the end of a string to make it compatible with functions that operate on strings.

For more information on what methods are available in String, look at the documentation for Java, available on the system.


next up previous contents
Next: Arrays Up: Compound statements Previous: Comments   Contents
Madhavan Mukund 2004-04-29