In Java, + joins two values into a new String whenever at least one of them is a String; otherwise it adds numbers. Because + works from left to right, 1 + 2 + "x" is "3x" but "x" + 1 + 2 is "x12". A String object can never change: +, += and String methods such as substring leave it as it is and give back their result, and only an assignment makes a variable refer to that result.
Quick check
What is the value of 7 / 2 in Java when both values are int?Show answerHide answer
- Dividing one
intby another drops the remainder.
- Dividing one
After String a = "hi"; String b = a; how many String objects are there, and how many references to them?Show answerHide answer
One object, "hi", and two references to it:
aandb.What does "net" + "work" evaluate to?Show answerHide answer
The single string "network":
+puts the right string straight after the left one, with no space.
Know these already? Jump to the practice questions
What you'll be able to do
- Determine whether each
+in an expression adds numbers or joins strings. - Predict the printed output of code that joins strings with numbers and
booleanvalues. - Determine the value of a
Stringvariable built up with+=. - Explain why a
Stringobject never changes and what a String method returns instead.
Key terms
Concatenation
Joining two values end to end into a new String, done by + when at least one operand is a String.
- In plain English
- Gluing text together.
- Don't write
- "
"a" + 1 + 2is "a3"."
String literal
Characters written between double quotes in code, such as "hello". Each one stands for a String object.
- In plain English
- Text typed straight into the program.
- Don't write
- "A string literal is a primitive value like an
int."
Immutable
Impossible to change after creation. Every String object is immutable.
- In plain English
- Once made, a string's characters stay exactly as they are.
- Don't write
- "
s += "x"adds an x to the end of the existing string object."
What is a String object?
A String is an object that holds a sequence of characters. A string literal such as "sun" stands for a String object, so String w = "sun"; makes w refer to it. You can also write String w = new String("sun");. The empty string "" has no characters at all.
Inside a literal, a backslash starts an escape sequence for a character you can't type directly:
| Escape | Gives | Example literal | Printed |
|---|---|---|---|
\" | a double quote | "say \"hi\"" | say "hi" |
\\ | one backslash | "C:\\temp" | C:\temp |
\n | a new line | "a\nb" | a, then b on the next line |
Check yourself
Show answerHide answer
3: the letter a, one newline character and the letter b. The two typed characters \n stand for one character.
When does + add and when does it join?
Java applies one rule to each + in turn:
- If either side is a
String, the+joins them. - If both sides are numbers, the
+adds them.
+ works from left to right, so 1 + 2 + "x" adds first (3) and then joins: "3x". In "x" + 1 + 2, the first + already has a String on its left, giving "x1", and then "x12".
*, / and % happen before +, so "x" + 2 * 3 is "x6". Parentheses go first of all: "x" + (1 + 2) is "x3".
Key idea
Read each + from left to right and ask: is either side already a String?
Check yourself
Show answerHide answer
"5a23". The first + adds 2 and 3; every later + has a String on its left, so it joins.
How do numbers and booleans look when joined?
When + joins a String with another value, that value is first turned into text:
| Value | Joined as |
|---|---|
int 42 | 42 |
double 2.50 | 2.5 |
double 3.0 | 3.0 |
boolean true | true |
A double keeps at least one digit after the point, but trailing zeros beyond that are dropped, so 2.50 joins as 2.5. Any arithmetic is done first: "avg " + 7 / 2 is "avg 3", because 7 / 2 is int division.
Check yourself
Show answerHide answer
"cost: 8.0". 4.0 * 2 is the double 8.0, which joins as 8.0.
How does += build a string?
s += x means s = s + (x): the right side is worked out first, then joined to the end of s, and the result is stored back in s. It is a common way to build a string step by step:
String code = "";
code += 7;
code += 1 + 1;
System.out.println(code);
| Statement | code |
|---|---|
String code = ""; | "" |
code += 7; | "7" |
code += 1 + 1; | "72" |
The second += adds 1 + 1 before joining, so it prints 72, not 711.
Check yourself
Show answerHide answer
"ab7". The right side, 3 + 4, is 7 before it is joined.
Why does a String never change?
A String object is immutable: no operation can change its characters. +, += and String methods such as substring never change the original: they give back their result as a String value, and a variable changes only when you assign that result to it.
String a = "sun";
String b = a;
a += "set";
System.out.println(a + " " + b);
a and b first refer to the same object, "sun". a += "set" builds a new object, "sunset", and makes a refer to it. "sun" itself is untouched, and b still refers to it, so this prints sunset sun. A method call whose result is not stored, such as a.substring(3); on its own line, changes nothing. The note on String methods covers what each method returns.
Check yourself
Show answerHide answer
"cat". substring(1) returned a new string, "at", which was never stored.
Worked example 1: Decide add or join
Question: What is printed?
int a = 4;
int b = 5;
System.out.println(a + b + "!" + a + b);
System.out.println("" + a * b + a / b);
What tells you the method
Several + signs mix numbers and strings, so take each + in order and decide whether it adds or joins.
Step 1: First line, left to right.
a + badds: 9.9 + "!"joins: "9!". Then "9!" + 4 is "9!4", and "9!4" + 5 is "9!45".WhyOnce the running result is a
String, every later+joins.Step 2: Second line, operators first.
a * bis 20 anda / bis 4 / 5, which is 0 withintdivision."" + 20is "20", and "20" + 0 is "200".Why*and/happen before+, and the empty string makes the first+a join.
Check it
Without the "", line 2 would add 20 + 0 and print 20, so the "" is what turns it into 200.
Answer
9!45 then 200 on the next line.
Worked example 2: Trace a string built with +=
Question: What is printed?
String s = "";
int n = 3;
s += n;
s += n + 1;
s = n + s;
s += 2.0 * n;
System.out.println(s);
What tells you the method
A variable is built up statement by statement, so keep a trace table.
Step 1: Trace
s.Statement Right side ss += n;3 "3" s += n + 1;4 "34" s = n + s;3 + "34" "334" s += 2.0 * n;6.0 "3346.0" Whys += xworks outxfirst, son + 1is 4, not "31".Step 2: Check the types.
In
n + s,sis aString, so the+joins and the 3 goes in front.2.0 * nis adouble, so it joins as 6.0.WhyThe left-or-right position decides where the text goes, and the type decides how a number looks.
Check it
The final string has the parts 3, 3, 4 and 6.0 in that order: "3346.0".
Answer
3346.0
Worked example 3: Follow two references
Question: What is printed?
String first = "data";
String second = first;
second.substring(0, 2);
first += "base";
System.out.println(first + " " + second);
- A)
database database - B)
database data - C)
data data - D)
database da
What tells you the method
Two variables share one object and then one is reassigned, so track which object each variable refers to.
Step 1: Line 3.
substring(0, 2)returns "da", but nothing stores it, sosecondstill refers to "data".WhyA String method never changes the string it is called on; it only gives back a result.
Step 2: Line 4.
first += "base"builds the new object "database" and makesfirstrefer to it.secondstill refers to "data".WhyReassigning
firstdoes not touch the objectsecondrefers to.
Check it
A assumes both variables share a changed object; C assumes += cannot change first; D assumes line 3 changed second.
Answer
B
Your turn
Question: What is printed?
System.out.println("Total: " + 3 + 4 * 2);
Step 1: Do the multiplication first.
4 * 2is 8.Step 2: Your go: take the two
+signs from left to right.
Show the full solutionHide the solution
Step 2. "Total: " + 3 joins to "Total: 3", because the left side is a String. That + 8 joins again, giving "Total: 38".
Answer: Total: 38
Traps
Trap
"Score: " + 5 + 3 shows the sum, 8.
It seems right because 5 + 3 looks like an addition. But + works from left to right, so "Score: " + 5 is already a String and the 3 is joined: "Score: 53". Write "Score: " + (5 + 3) to add first.
What does "n=" + 2 + 2 evaluate to, and what about "n=" + (2 + 2)?
"n=22" and "n=4".
Trap
s += "!" changes the string object that s refers to.
It seems right because s shows the new text afterwards. But the object is immutable: += builds a new object and points s at it, and any other variable still refers to the old one.
After String p = "go"; String q = p; p += "!"; what does q hold?
"go". Only p was pointed at the new string "go!".
What's examined
On the AP® Computer Science A exam (Unit 1), multiple-choice questions ask what a print statement shows when strings, numbers and + are mixed, and test whether you know that String methods never change the original string. In free-response answers you build strings with + and +=. Joining with + is Java syntax, not on the Java Quick Reference: Learn this.
Practice questions
- Recall Which expression evaluates to the
String"57"?
- A)
5 + 7 + "" - B)
"" + (5 + 7) - C)
"" + 5 + 7 - D)
5 + 7
Show answer
Answer: C. The "" makes the first + a join, giving "5", and then "5" + 7 is "57".
Why the others are wrong:
- A adds 5 + 7 first, so it gives "12".
- B adds inside the parentheses first, so it also gives "12".
- D adds two
intvalues, giving theint12, not aString.
- Apply What is printed?
System.out.println(1 + 2 + "3" + 4 + 5);
Show answer
Answer: 3345
Marking points:
- 1 + 2 adds to 3, and 3 + "3" joins to "33".
- Every later
+joins: "334", then "3345".
- Apply What is printed?
double price = 2.50;
boolean ok = true;
System.out.println("p=" + price + ", ok=" + ok);
Show answer
Answer: p=2.5, ok=true
Marking points:
- The
double2.50 joins as 2.5: the trailing zero is dropped. - The
booleanjoins as the word true.
- Exam-style The code segment should print
Sum: 12. Give the number of the line that stops it working.
1: int a = 5;
2: int b = 7;
3: String label = "Sum: ";
4: System.out.println(label + a + b);
Show answer
Answer: Line 4.
Marking points:
label + ais already aString, sobis joined, not added: the segment prints Sum: 57.- The fix is
System.out.println(label + (a + b));.
- Apply What is printed?
String s = "ab";
String t = s;
s = s + "c";
t += t;
System.out.println(s + t);
Show answer
Answer: abcabab
Marking points:
sis pointed at the new string "abc";tstill refers to "ab".t += tgives "abab", so the output is "abc" followed by "abab".
- Exam-style
String w = "cat";runs first. Which statement changes the characters in theStringobject "cat" thatwrefers to?
- A)
w += "s"; - B)
w.substring(1); - C)
w = w + "s"; - D) None of them: the characters of a
Stringobject cannot change.
Show answer
Answer: D. A String object is immutable.
Why the others are wrong:
- A builds a new object, "cats", and points
wat it; the object "cat" is unchanged. - B returns a new string, "at", and changes nothing.
- C does the same as A: it changes the variable, not the object.
- Recall Name the property of
Stringobjects that means their characters cannot be changed after they are created.
Show answer
Answer: Immutable
Marking points:
- Every change you see is a new
Stringobject assigned to a variable.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- A
+joins if either side is aStringand adds if both are numbers. - Expressions run left to right, after
*,/,%and anything in parentheses. - A joined
doubleshows its decimal point, as in 3.0 or 2.5. s += xworks outxfirst, then joins it to the end ofs.- No
Stringobject ever changes; reassigning a variable points it at a new one.