Strings and numbers: + and format
Java's calculator has one more rule, and it concerns the + operator. While there are numbers on both sides of it, it adds. As soon as text appears on either side, + stops counting and starts gluing.
Imagine that a label has appeared on the calculator's screen. From now on, each press of + adds nothing: it writes the next value on the right, as if you had typed it on a keyboard. Let's see how this looks in a program:
public class Main {
public static void main(String[] args) {
System.out.println(1 + 2 + "3"); // 33
System.out.println("1" + 2 + 3); // 123
}
}Java runs the + operators left to right, one at a time:
- In the first
println,1 + 2comes first. Both values are numbers, so the result is3. Then comes3 + "3": there is text on the right, so+glues, and the result is33. - In the second
println, the text comes first."1" + 2gives12, and"12" + 3gives123. The numbers never get added.
The screen picture is off in one respect: on a screen, 3 and "3" look the same, but to Java they are different values. The number 3 can be added, while the string "3" is text, and Java will not add it.
Joining strings
Joining strings is called concatenation. There is one rule: if a string stands on one side of +, the value on the other side is turned into text and appended to it. That way you can join a string with a value of any type:
String name = "Anna";
System.out.println("Hi, " + name); // Hi, Anna
System.out.println("Price: " + 2.5); // Price: 2.5
System.out.println("1" + (2 + 3)); // 15Let's go through them in order:
nameis a variable of typeString, and it holds the textAnna."Hi, " + namejoins two strings."Price: " + 2.5turns the number2.5into text and appends it to the string.- In
"1" + (2 + 3), the parentheses run first:2 + 3gives5, and only then does"1" + 5glue15.
Interviewers like to ask this: what does 1 + 2 + "3" print, and what does "1" + 2 + 3 print? One rule always gives the answer: + runs left to right, and after the first string it only glues.
Printing by a template
A long string of pieces and pluses is hard to read. String.format is handier: it fills in a template, like a form with blanks. In place of the blanks, the template has markers that start with %, and the values for them follow, in order:
%d—a whole number;%.2f—a fractional number rounded to two digits after the decimal point;%s—a string, or any value as text;%n—a line break.
String name = "Anna";
int age = 30;
double height = 1.6789;
String line = String.format("%s is %d, %.2f m", name, age, height);
System.out.println(line); // Anna is 30, 1.68 m
System.out.printf("%s is %d%n", name, age); // Anna is 30Let's see what happens here:
String.formattakes the template and three values. The marker%sis replaced withAnna,%dwith30, and%.2fwith1.68: the number was rounded to two digits.- The result is an ordinary string. It goes into
lineand gets printed. System.out.printfdoes the same thing but prints the result right away. Likeprint, it does not end the line by itself, so the template ends with%n.
%.2f takes the decimal separator from the computer's language settings. With English settings the program prints 1.68, as in the comment, and with Russian ones it prints 1,68. Joining with + and println, on the other hand, always print a fraction with a point.
A marker must fit its value. If you pass 2.5 to a %d marker, the program stops with an IllegalFormatConversionException.
Common mistake
The sum of two numbers is appended to a string without parentheses:
public class Main {
public static void main(String[] args) {
int apples = 2;
int pears = 3;
String text = "Fruit: " + apples + pears; // ✗
System.out.println(text); // Fruit: 23
}
}The goal was to print Fruit: 5, but the program printed Fruit: 23. The first + glued the string to 2, so a string already stands to the left of the second +. That is why 3 was appended to the text instead of being added to 2. Put the sum in parentheses: "Fruit: " + (apples + pears) prints Fruit: 5.
Key points
- If a string stands on one side of
+, it glues instead of adding. +runs left to right:1 + 2 + "3"is33, and"1" + 2 + 3is123.- To add numbers inside a string, put the sum in parentheses:
"1" + (2 + 3)is15. String.formatandprintfput values into a template by the markers%d,%.2fand%s, and%nends the line.