Strings: Java and C++

A std::string is a container of characters: it grows, shrinks, and a character can be assigned through operator[]. A Java String is immutable: every operation that changes the text returns a new string, and the only way to build one in a loop is a StringBuilder. That one decision explains most of what surprises a C++ programmer.

The task

Build a second string from a first, compare two strings of the same text, build 0 1 2 from a loop, and then read a length, a character, a substring and an upper-case copy. Every step is a line of both programs, and the outputs are compared line by line.

The Java version

concat answers a new string and leaves a as it was. The loop appends to a StringBuilder and calls toString once, at the end. The reads are the ones the API names: length, charAt, substring, toUpperCase:

public class Texts { public static void main(String[] args) { String a = "Hello"; String b = a.concat(", world"); System.out.println("a: " + a); System.out.println("b: " + b); String copy = new String("Hello"); System.out.println("same reference: " + (copy == a)); System.out.println("equal content: " + copy.equals(a)); StringBuilder out = new StringBuilder(); for (int i = 0; i < 3; i++) { out.append(i).append(' '); } System.out.println("built: " + out.toString().trim()); System.out.println("length: " + b.length()); System.out.println("char at 1: " + b.charAt(1)); System.out.println("slice: " + b.substring(7)); System.out.println("upper: " + b.toUpperCase()); System.out.println("the original: " + b); } }

javac -Xlint:all -d out Texts.java
java -cp out Texts

a: Hello
b: Hello, world
same reference: false
equal content: true
built: 0 1 2
length: 12
char at 1: e
slice: world
upper: HELLO, WORLD
the original: Hello, world

The comparison that is not ==

The fourth and fifth lines are the trap. copy == a compares the two references, and a string made with new is a different object from the literal, so the answer is false although the text is the same. equals compares the characters, and the answer is true. The == of Java on two objects is the C++ comparison of two pointers, not the comparison of two std::string values.

A literal and a literal are the same object, because the compiler interns them, so "Hello" == "Hello" is true and a test written with two literals can pass for the wrong reason. The rule that does not depend on the compiler is equals for the text, and Objects.equals when a null is possible.

The C++ version

The C++ string is mutable and compares by value. The block is not compiled here, because the image has no g++; the text after it says what the program prints.

#include <iostream> #include <string> int main() { std::string a = "Hello"; std::string b = a + ", world"; std::cout << "a: " << a << '\n'; std::cout << "b: " << b << '\n'; std::string copy = "Hello"; std::cout << "equal content: " << (copy == a) << '\n'; std::string built; for (int i = 0; i < 3; i++) { built += std::to_string(i); built += ' '; } std::cout << "built: " << built << '\n'; b[0] = 'h'; std::cout << "after b[0]: " << b << '\n'; std::cout << "length: " << b.size() << '\n'; std::cout << "char at 1: " << b[1] << '\n'; std::cout << "slice: " << b.substr(7) << '\n'; }

The program would print the two strings, equal content: 1, the built text, and then the line that has no Java counterpart: after b[0] = 'h' the string reads hello, world. The Java program cannot express that assignment at all, because there is no method on String that changes a character; the nearest is b = "h" + b.substring(1), which makes a third string and leaves the second as it was.

What differs and why

Immutability is a design choice with a list of consequences. A Java string can be shared between threads and used as a map key without a copy, because nothing can change it. The compiler can intern literals and cache the hash. And every write pays for a new object: s += x in a loop copies the whole text on every pass, which is quadratic in the length and is the reason StringBuilder exists.

The C++ string owns a buffer and grows it, usually by doubling, so an append in a loop is amortised constant time. The price is that a copy is a deep copy unless it is moved, that a reference into the buffer can be invalidated by a later append, and that two threads cannot share one string that either may write.

The units differ as well. String.length counts UTF-16 code units, so a character outside the basic plane counts two and an emoji is not one char. std::string::size counts bytes in the encoding it was given, which for UTF-8 makes a letter with an accent two. Neither is the number of characters a person sees, and both languages have a separate API for that.

The habit that breaks

Two habits, and the first is the comparison. A C++ programmer writes if (a == b) for text out of muscle memory, and Java compiles it, because == is defined on references. The program then works on the literals of a test and fails on the strings that came from a file, a request or a new. The compiler cannot help; the fix is equals.

The second is the append in a loop. result += word reads like the C++ result += word and costs a copy of the whole result per iteration. A loop over ten thousand words copies fifty million characters, and the same loop with a StringBuilder copies ten thousand. The course covers the builder in lesson 025.

The next page

The next page is collections: ArrayList and HashMap against vector and map, boxing, and the reference that a resize invalidates in C++ and that Java's references survive. The C++ lesson is std::string, and the Java lesson is String.

The Java program was compiled with OpenJDK 21.0.13 (javac) and run on Alpine Linux in a Docker container. The C++ program is shown and was not compiled here: the image has no g++.

Article author: Arthur Isaev