Lesson 1.13 · Unit 1 · CED topic 1.15

Strings: creating and combining

Text is everywhere in programs: names, messages, file contents, user input. Java represents text with the String class. A String object represents a sequence of characters, and because String is part of java.lang it is available by default, with no import. This lesson covers how Strings are created and how they are combined. Lesson 1.15b covers how to take them apart.

Required content · LO 1.15.A

Learning objective.

  • 1.15.A. Develop code to create string objects and determine the result of creating and combining strings.

Essential knowledge.

  • 1.15.A.1. A String object represents a sequence of characters and can be created by using a string literal or by calling the String class constructor.
  • 1.15.A.2. The String class is part of the java.lang package. Classes in the java.lang package are available by default.
  • 1.15.A.3. A String object is immutable, meaning once a String object is created, its attributes cannot be changed. Methods called on a String object do not change the content of the String object.
  • 1.15.A.4. Two String objects can be concatenated together or combined using the + or += operator, resulting in a new String object. A primitive value can be concatenated with a String object. This causes the implicit conversion of the primitive value to a String object.
  • 1.15.A.5. A String object can be concatenated with any object, which implicitly calls the object’s toString method (a behavior that is guaranteed to exist by the inheritance relationship every class has with the Object class). An object’s toString method returns a string value representing the object. Subclasses of Object often override the toString method with class-specific implementation. Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass, but the behavior of the method is specific to the subclass.
    Outside the course: Overriding the toString method of a class is outside the scope of the AP Computer Science A course and exam.

Creating Strings

A String object can be created by using a string literal (characters in double quotes) or by calling the String class constructor. Both produce a String object.

String a = "hello";
String b = new String("hello");
String empty = "";
System.out.println(a);
System.out.println(b);
System.out.println("[" + empty + "]");
hello
hello
[]

The empty string "" is a real String object with no characters. It is not the same as null, which means the variable refers to no object at all. Escape sequences work inside any literal, as in Lesson 1.3: \", \\, and \n.

Strings are immutable

A String object is immutable: once it is created, its attributes cannot be changed. Methods called on a String never change the String itself; they return a new one. This single fact explains most String surprises on the exam, because it means that "changing" a String always means assigning a new String to the variable.

String word = "cat";
String longer = word + "s";
System.out.println(word);
System.out.println(longer);
word = word + "s";
System.out.println(word);
cat
cats
cats

Building longer left word untouched. Only the assignment word = word + "s" made the variable word refer to a different String.

Concatenation

Two String objects can be concatenated, or joined, with the + operator or the += operator. The result is a new String object. A primitive value can also be concatenated with a String, which causes an implicit conversion of the primitive to a String.

String name = "Ada";
int age = 36;
double height = 1.7;
boolean student = true;
String line = name + " is " + age + " years old and " + height + " m tall. Student: " + student;
System.out.println(line);
String s = "ab";
s += "cd";
s += 5;
System.out.println(s);
Ada is 36 years old and 1.7 m tall. Student: true
abcd5

### The order of evaluation matters

+ is evaluated left to right. If both operands are numbers it adds; as soon as one operand is a String it concatenates. So the same digits give different results depending on where the first String appears.

ExpressionValueWhy
1 + 2 + "x""3x"1 + 2 is addition (3), then "3" + "x"
"x" + 1 + 2"x12""x" + 1 is a String, then "x1" + 2
"x" + (1 + 2)"x3"the parentheses force the addition first
"" + 7 + 8"78"an empty String starts the concatenation

### Concatenating objects

A String can be concatenated with any object. When that happens, Java implicitly calls the object's toString method, which returns a String value representing the object. That behavior is guaranteed for every class because every class in Java is a subclass of Object. Many classes supply a toString that describes the object; some do not, and the default text is not meaningful, so you do not predict it. Writing your own toString is outside the course. If the object is null, the text null is used.

String missing = null;
System.out.println("Value: " + missing);
Value: null
Worked example · order of evaluation

Predict each output.

int a = 4;
int b = 5;
System.out.println(a + b);
System.out.println("Sum: " + a + b);
System.out.println("Sum: " + (a + b));
System.out.println(a + b + " is the sum");
System.out.println(a + " and " + b);
9
Sum: 45
Sum: 9
9 is the sum
4 and 5

The first and fourth lines add before any String is involved, so a + b is 9. In the second, the String comes first, so each later + is concatenation and the digits are joined as 45. Parentheses fix it in the third.

Worked example · building a String over several statements

Trace the value of result.

String result = "";
result += "A";
result = result + 1;
result += 2 + 3;
result = "[" + result + "]";
System.out.println(result);
After the statementresult
String result = "";""
result += "A";"A"
result = result + 1;"A1"
result += 2 + 3;"A15" (the right side 2 + 3 is evaluated to 5 first)
result = "[" + result + "]";"[A15]"
[A15]
Worked example · a String with an object

The class Point comes with a toString method that returns its coordinates in parentheses.

Point p = new Point(3, 4);
System.out.println("p = " + p);
String text = "Corner " + p + "!";
System.out.println(text);
p = (3, 4)
Corner (3, 4)!

Concatenating p called its toString method automatically. You never wrote p.toString(). The exam shows classes like this and expects you to reason from the documentation, not to write toString yourself.

Exam focus

Expect questions about the value of a concatenation expression where int values and Strings are mixed, so find the first String and read left to right. Expect questions that depend on immutability: a method call whose result is not assigned leaves the String unchanged. Know that += on a String creates a new object and reassigns. Overriding toString is outside the exam; reading code that calls it implicitly is not.

Practice
  1. What is printed?
    System.out.println("A" + 1 + 2);
    System.out.println(1 + 2 + "A");
    Show answer

    A12 and 3A. In the first line the String appears first, so both + operators concatenate. In the second line the first + adds two ints to 3, and then 3 is concatenated with "A".

  2. What is printed?
    String s = "hi";
    s += s;
    s += 1 + 1;
    System.out.println(s);
    Show answer

    hihi2. s += s gives hihi. For the next line the right side 1 + 1 is evaluated to 2 first, and hihi2 results.

  3. What is printed?
    String first = "Java";
    String second = first + "Script";
    System.out.println(first);
    System.out.println(second);
    Show answer

    Java, then JavaScript. Concatenation builds a new String and never changes first, because Strings are immutable.

  4. Write one statement that stores the text Total: 15 in a String named msg, using int total = 15;.
    int total = 15;
    String msg = "Total: " + total;
    System.out.println(msg);
    Show answer

    String msg = "Total: " + total;. The primitive int is converted to a String automatically when it is concatenated.

  5. What is the difference between "" and null for a String variable?
    Show answer

    "" is a String object that contains no characters, so you can concatenate with it and use String methods on it. null means the variable refers to no object, so calling a method on it throws a NullPointerException.

  6. What is printed?
    String t = "ab";
    String u = t + "c";
    t = u + t;
    System.out.println(t + " " + u);
    Show answer

    abcab abc. u is abc. Then t = u + t joins u and the old value of t (ab), giving abcab. The variable u is unchanged.

← 1.12 Calling instance methods1.14 String methods and indexes →

Keep going in the full AP Computer Science A course

All of U1 (Using Objects and Methods) is free to everyone, with no account. The course has 58 lessons, each with worked examples and practice problems that come with full solutions. A free account can also start a free month of the whole course, with no card.

Open this lesson in the courseSee the whole course