slanted W3C logo

Day 14 — Strings II

Strings represent text (a sequence of characters) and are widely used in Java programs. Because they are so widely used, the Java language lets a client perform actions with String objects that cannot be performed with other types of objects.

+

You can join two strings to create a new string using the concatenation operator +:

String name1 = "James Bond 007";
String name2 = "James " + "Bond " + "007";
  1. name1 is a reference to a String literal
  2. name2 is a reference to a String computed using an expression using only literals and +
    • such an expression is called a constant expression
    • a constant expression is treated as though it were a literal
    • name1 == name2 is true

+ with Mixed Operands

If you use + with a String and any other type, Java will convert the other type to a String:

Fraction f = new Fraction();

// some code here that uses f

output.println("Fraction is " + f);

Java performs the concatenation by silently invoking toString on f.

+ with Mixed Operands

Concatenation also works with primitive values. The following code fragment:

String name3 = "James Bond " + 0 + 0 + 7;

output.println(name3.equals("James Bond 007"));

prints true.

Concatenation makes it easy to convert a numeric value to a String; just concatenate an empty String with the value:

double value;

// some code here that sets value

String asString = "" + value;

+ with Mixed Operands

Concatenation and addition both use + as the operator. This can lead to errors if you forget that Java evaluates expressions involving operators of the same precedence from left to right.

String laugh = 'h' + 'a' + "ha";
System.out.println(laugh);

The above snippet prints:

201ha

Previous Example Explained

String laugh = 'h' + 'a' + "ha";
System.out.println(laugh);

The expression 'h' + 'a' + "ha" involves operators all having the same precedence, so it is evaluated from left to right:

  1. 'h' + 'a' is the sum of two char literals; addition is not defined for char so both operands are promoted to int and then summed to yield 201
  2. 201 + "ha" involves a String object so string concatenation is performed to yield "201ha"

You can fix the problem by concatenating an empty string "" at the beginning of the expression:

String laugh = "" + 'h' + 'a' + "ha";

+ with Mixed Operands

What does the following statement print?

System.out.println("2 + 2 = " + 2 + 2);

And this?

final String S = "YorkU";
final String T = "York" + "U";

System.out.println("Strings are equal: " + S == T);

Puzzle

Provide a declaration for i that turns this loop into an infinite loop:

while (i != i + 0)
{
   // some code here
}

Concatenating Primitives

How does Java convert an expression like "ABC" + 123 to a String? By silently converting 123 into an object and then invoking toString!

A wrapper class allows the client to create an object the corresponds to a primitive value. There are 8 wrapper classes, one for each primitive type.

Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Boxing

Java translates expressions like:

String s = "ABC" + 123;
String t = "ABC" + 1.23;
String u = "ABC" + 'D':

into these:

String s = "ABC" + (new Integer(123)).toString();
String t = "ABC" + (new Double(1.23)).toString();
String u = "ABC" + (new Character('D')).toString();

When a client creates a wrapped version of a primitive, it is called boxing the primitive.

When the compiler automatically creates a wrapped version of a primitive, it is called auto-boxing the primitive.

Converting String to Primitives

Often you will want to convert a String to a primitive value. The wrapper classes all have static methods to help you (except for Character):

int i = Integer.parseInt(s);

long n = Long.parseLong(t);

double d = Double.parseDouble(u);

These methods will throw an exception if the conversion cannot be performed.

To convert a String to char you just use charAt.

char c = s.charAt(0);

Commonly Used Accessors: substring

String substring(int beginIndex)

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

Throws IndexOutOfBoundsException if beginIndex is negative or larger than the length of this string.

String s = "James Gosling";

String t = s.substring(0);
String u = s.substring(1);
String v = s.substring(s.length() - 1);
String w = s.substring(s.length());
output.printf("s: %s%nt: %s%nu: %s%nv: %s%nw: %s%n",
              s, t, u, v, w);

The code fragment prints:

s: James Gosling
t: James Gosling
u: ames Gosling
v: g
w:

Example with substring

A common operation when working with files to extract the file name from a full path name. In the example below, we want the extract the substring day18.html

String s = "/cs/home/burton/www" + 
           "/teaching/2009F/day18.html";

int idx = s.lastIndexOf('/');
String fileName = s.substring(idx + 1);

Another Version of substring

String
substring(int beginIndex, int endIndex)


Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Throws IndexOutOfBoundsException if beginIndex is negative, or endIndex is larger than the length of this string, or beginIndex is larger than endIndex.

      String s = "ABC";

      String t = s.substring(0, 1);
      String u = s.substring(0, 2);
      String v = s.substring(0, s.length());
      String w = s.substring(1, 1);
      output.printf("s: %s%nt: %s%nu: %s%nv: %s%nw: %s%n",
                    s, t, u, v, w);

The code fragment prints:

s: ABC
t: A
u: AB
v: ABC
w: 

Example with substring

Find the substring between the '*' characters.

String s = "This is a *random* string";

int first = s.indexOf('*');
int second = s.indexOf('*', first + 1);

String between = s.substring(first + 1, second);

substring extracts the String starting from index first + 1 up to but not including index second.