Algorithms and OOD (CSC 207 2013F) : Readings

Strings in Java

Summary: We introduce (or re-introduce) strings in the Java programming language, focusing on a selection of useful operations.

Prerequisites: Basics of Java

Important Classes

String Basics

In the parlance of computer science, a string is a sequence of simple characters. (A character is, most frequently, something you can type on the keyboard, such as a letter, number, or piece of punctuation.) Almost every modern programming language permits programmers to use variables of the string data type. Languages typically permit a variety of operations on strings, including input (since they are easy for most people to type), output (since they are easy for most people to type), and to extract individual characters.

In Java, strings are objects that belong to class java.lang.String. Because that is such a common class, Java permits you to skip the package name, even without a corresponding import statement. For example,

String username;

is equivalent to

java.lang.String username;

String constants are represented by placing the sequence of characters between a pair of double-quotation marks. For example

username = "jdoe";

Java strings can contain essentially any character you can type or otherwise generate. They can contain numbers, spaces, punctuation, and so on and so forth. For example,

String address;
address = "Apt. 2, East House, Main St.";

Comparing Strings

Strings are also comparable. That means we can determine whether two strings are the same and whether one string “naturally” precedes another. (Java typically uses a local configuration file for determining order so that it matches the local language and its ordering rules.) Once you can compare strings, you have the ability to develop more sophisticated operations on collections of strings, such as placing them in order or searching for a particular string.

Java provides two basic operations for comparing strings:

  • equals(String other) determines whether this string is the same as another string.
  • compareTo(String other) determines the relative order for two strings. It returns zero if they are equal, a negative number if the string executing compareTo naturally precedes other, and a positive number if the string executing compareTo naturally follows other.

Other Operations

We can do many other things with strings. Java's primary string class, java.lang.String gives us access not just to the sequence of characters as a whole, but also to subsequences and to operations on those subsequences. Interestingly enough, Java takes advantage of the encapsulation for the String class and makes strings immutable: Operations do not change strings, but only return new strings based on the original string executing an operation.

Some of the string operations you may find useful include:

  • toLowerCase(): Build a new string, similar to the original, but with all letters in the string converted to lower-case (using the local installations definition of lower-case and upper-case to lower-case conversion).
  • toUpperCase(): Build a new string, similar to the original, but with all letters in the string converted to upper-case.
  • trim(): Build a new string, similar to the original, but without leading and trailing whitespace. This command is often useful when you're processing unstructured user input.
  • substring(startindex): Extract the portion of the string that begins at startindex. Note that indices start at 0.
  • substring(startindex,endindex): Extract the portion of the string that begins at startindex and ends directly before endindex.
  • replace(target,replacement): Build a new string, similar to the orignal, but with all substrings that match target replaced by replacement.
  • indexOf(target): Determine the first index of target within the string. (This method is often useful in conjunction with substring.)
  • indexOf(target, startHere): A variant that starts looking at the specified index.
  • concat(target): Build a new string by joining the specified target to the end of the current string.
  • length(): Determine how many characters are in the string.

For example,

String str = "All mimsy were the Borogoves.";
	// All mimsy were the Borogoves.
	// all mimsy were the borogoves.
	// mimsy were the Borogoves.
	// mimsy
	// All frumious were the Borogoves.
	// 19
	// -1
pen.println(str.concat("  And the mome raths outgrabe."));
	// All mimsy were the Borogoves.  And the mome raths outgrabe.
	// All mimsy were the Borogoves.

Observe that even after all of the “changes” to the original string, the final command prints the original string, suggesting that the string was never changed.

You can find other interesting and useful string operations in the official documentation, linked at the top of this reading.

StringBuffer Objects

As suggested at the end of the previous section, String objects are immutable in Java. That is, once you've created a string, you can't change it. However, there are also times that you want to change your strings, rather than simply building new strings each time. For such purposes, Java provides the java.lang.StringBuffer class. (Again, you need not import this class to refer to objects simply as StringBuffer.)

You can create a new StringBuffer in one of two ways, using a zero-parameter constructor, which builds an empty buffer, or using a string as the parameter, which builds a string buffer based on the given string. For example,

  StringBuffer initiallyEmpty;
  StringBuffer sillyWord;
  initiallyEmpty = new StringBuffer();
  sillyWord = new StringBuffer("borogoves");

The StringBuffer class provides many of the same methods as the String class, including indexOf, substring, and length.

However, the StringBuffer class also provides many mutators for changing the underlying string.

  • append(String str): Appends str to the end of the buffer.
  • insert(int offset, String str): Inserts str starting at position offset. Everything that was at that position is moved to the right, after str.
  • delete(int start, int end): Delete the characters between start and end-1, inclusive.

You can also use the toString method to recover a string from a StringBuffer.

Copyright (c) 2013 Samuel A. Rebelsky.

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.