Course contentsShow
← Java
Lesson 2237 of 2,87043. String Handling in DepthFree lesson

Indentation Removal Algorithm

Understand how the compiler determines the common leading whitespace to strip from each line in a text block.

Indentation Removal Algorithm

You'll learn how Java's compiler determines which leading whitespace to strip from every line in a text block, keeping only the essential indentation.

How the Compiler Decides What to Strip

When you write a text block, you naturally indent it to match your code's structure. Java doesn't want all that indentation in your actual string—it's just there to make your code readable. The compiler uses a specific algorithm to figure out what's incidental (code-structure whitespace) versus essential (whitespace you actually want).

Here's the process:

  1. Ignore the opening line: The """ opener doesn't count
  2. Find the closing delimiter's column: Where does the closing """ start?
  3. Examine every non-blank content line: Check how much leading whitespace each has
  4. Determine the minimum: The smallest indentation among all lines (including the closing delimiter)
  5. Strip that amount from every line: Remove exactly that many spaces/tabs from the start of each line

Think of it like aligning a ruler: the compiler places an imaginary vertical line at the leftmost non-whitespace character (considering both content lines and the closing delimiter), then erases everything left of that line.

String html = """
              <html>
                  <body>
                      <p>Hello</p>
                  </body>
              </html>
              """;

If the closing """ sits at column 14, and all content lines start at column 14 or beyond, the compiler strips 14 spaces from every line. The <html> has zero remaining indent, while <p>Hello</p> keeps its 8-space essential indentation.

Key Takeaway:
The compiler strips the minimum leading whitespace shared by all lines (including the closing delimiter's position), preserving only the relative indentation structure you intended.