Resources‎ > ‎Java Basics‎ > ‎

Strings

Some content modified from the Java Tutorials at http://java.sun.com/docs/books/tutorial/java/data/strings.html

Fundamentally, a String is a sequence of characters. The String class provides various methods to access portions of a String, but recall that Strings are immutable. That means that they do not change. To morph one String into another, you must use methods to create a new String object containing the new set of characters.

Common Methods

Following are several common methods that are fairly self-explanatory. Take a look at the String API for a bit more detail.

  • charAt
  • compareTo and compareToIgnoreCase
  • concat
  • equals and equalsIgnoreCase
  • length
  • substring
  • replace

The split Method

The split method can be used to divide a String into several substrings. It takes as input a regular expression denoting the how the string should be split and returns an array of Strings. In the simplest case, the expression is a character denoting the delimiter to be used. The following example splits the String around the colon. The result is an array of Strings - [a,b,c]. Note that the delimiter is removed from the result.

String s = "a:b:c";
String[] splitString = s.split(":");

Concatenation

The + operator can be used to concatenate two or more strings together.  It can also be used to concatenate a string and an int.

Escape Sequences

Escape sequences tell the compiler to interpret the following character in a special way.  For example, in order to insert a quotation mark in a string, you must use the character sequence \". If you use only the quotation mark (") the compiler will interpret it as the end of the string.  An example follows:
System.out.println("I \"love\" computer science.");


The list of escape sequences in Java is as follows:

From http://java.sun.com/docs/books/tutorial/java/data/characters.html
Escape Sequence Description
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a formfeed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.

Number/String Conversion

If an int is concatenated with a string it will automatically be converted to a string.

int x = 2;
String s = "A number: " + x;

In the preceding example, the string s will have the value "A number: 2".
To convert an int into a String without concatenating it with another string, use the valueOf method of the string class.
int x = 2;
String s = String.valueOf(x);

To convert a string to an Integer, use the parseInt method of the Integer class.
String s = "2";
int x = Integer.parseInt(s);


Comments