🔤 Strings & Math
Strings & Math: In Java a String is immutable: once created, the text never changes in memory, and every "change" actually produces a brand-new String object — like text carved i
In Java a String is immutable: once created, the text never changes in memory, and every "change" actually produces a brand-new String object — like text carved in stone: to fix it you do not erase the stone, you carve a new one while the old stone stays intact. But if immutability is inconvenient, why did Java design String this way and make StringBuilder a separate class? Because immutability has big advantages such as making String thread-safe and safe as a HashMap key; yet if you concatenate with `+` 10,000 times in a loop, each step creates a new object and generates garbage — which is exactly why the mutable StringBuilder exists. In Python str is also immutable and the same problem is solved with `join`; in C++ strings are mutable so this distinction does not exist. For a QA engineer this difference shows up in performance tests: a reporting util that joins a large CSV line by line with `+`, if not converted to StringBuilder, visibly slows the test suite and can produce timeout-driven flaky results in timing-sensitive tests.
Most important String methods
Micro Lab: Code practice
Replace the TODO line with the critical line from the expected solution. This is not a real runtime; the goal is to reinforce writing the correct structure in a controlled way.
Step by Step: Code practice
Identify goal and input
Complete the critical line
Check output or behavior
Read the error message as evidence
Order the code reading and verification flow.
What does this line print? Evaluate it left to right in your head before running.
This would be right if all were Strings — but the first 1 + 2 is still numeric addition (no String yet).
1 + 2 collapses to a single number (3); you do not get two separate 3s.
Java applies no multiplication/precedence here; the + operator runs strictly left to right.