0Pricing
Java Academy · レッスン

テキストブロックと String.format

テキストブロックで複数行文字列を記述し、String.format のパターンでデータを整形します。

「テキストブロックと String.format」はCoddyKit上の無料Java Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはJava Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Java Academyコースには全4レッスンが含まれています。

テキストブロックとString.format

テキストブロック(Java 15以降)を使うと、エスケープなしで複数行の文字列リテラルを記述できます。String.formatやformatted()と組み合わせることで、複雑な文字列出力をすっきり読みやすく記述できます。

テキストブロックとは

テキストブロックとは、三重の二重引用符"""で囲んだ文字列リテラルです。改行とインデントが自動的に保持されるため、複数行の内容でエスケープシーケンスが不要になります。

// Traditional multi-line string
String old = "SELECT id, name, email\n" +
             "FROM users\n" +
             "WHERE active = true\n" +
             "ORDER BY name;";

// Text block (Java 15+) — much cleaner
String sql = """
    SELECT id, name, email
    FROM users
    WHERE active = true
    ORDER BY name;
    """;

System.out.println(sql);

インデントの処理

テキストブロックでは、共通する行頭の空白が自動的に除去されます。閉じる"""の位置によってインデントが決まります。

// Leading spaces up to the closing """ are stripped
String json = """
        {
            "name": "Alice",
            "role": "admin"
        }
        """;
// Output has no leading spaces (stripped by common indent)
System.out.println(json);
// {
//     "name": "Alice",
//     "role": "admin"
// }

埋め込み引用符

テキストブロック内では、連続する3つの引用符が現れない限り、二重引用符をエスケープせずに記述できます。単一の"や""はそのまま使用できます。

String html = """
    <div class="container">
        <p class="title">Hello, World!</p>
        <a href="https://example.com">Click here</a>
    </div>
    """;
System.out.println(html);
// Note: no need to escape " inside the block

JSONテンプレートでのテキストブロック

テキストブロックは、テストや設定で使用するJSON、HTML、XML、SQLのテンプレートに特に適しています。

String request = """
    {
        "email": "alice@example.com",
        "password": "secret123",
        "plan": "PRO"
    }
    """;

// In tests: compare expected JSON
String expected = """
    {
      "status": "created",
      "id": 42
    }
    """;
// Perfect for MockMvc test assertions
System.out.println(request);

テキストブロックでのformatted()

テキストブロックとformatted()(Java 15以降)を組み合わせると、パラメーター化されたテンプレートを作成できます。

String name = "Alice";
long orderId = 1234L;
double total = 149.99;

String email = """
    Dear %s,

    Your order #%d has been confirmed.
    Total charged: $%.2f

    Thank you for shopping with us!
    """.formatted(name, orderId, total);

System.out.println(email);
// Dear Alice,
// Your order #1234 has been confirmed.
// Total charged: $149.99

テキストブロックのエスケープシーケンス

テキストブロックでは\nと\tに加えて、Java 14以降の\(行の継続)と\s(末尾の空白を保持)を使用できます。

// \s forces a space (preserves trailing whitespace on line)
String padded = """
    line one  \s
    line two   \s
    """;

// \ (backslash at end of line) joins lines in source but keeps them as one
String poem = """
    Roses are red, \
    violets are blue.
    """;
System.out.println(poem); // Roses are red, violets are blue.

String.formatリファレンス

String.formatで使用する主なフォーマット指定子:

  • %s — String
  • %d — 整数
  • %f — 浮動小数点数
  • %.2f — 小数点以下2桁
  • %n — プラットフォームの改行
  • %x — 16進数
  • %10d — 10文字幅で右寄せ
System.out.printf("%s | %d | %.2f | %X%n", "Item", 42, 9.99, 255);
// Item | 42 | 9.99 | FF

String formatted = String.format("%-20s %6.2f%n", "Mechanical Keyboard", 129.95);
System.out.print(formatted);
// Mechanical Keyboard 129.95

// Named format with text block
System.out.printf("""
    Order: %s
    Total: $%.2f
    Status: %s%n""", "ORD-001", 99.99, "SHIPPED");

テキストブロックのstripIndentとtranslateEscapes

テキストブロックに関連するStringのメソッドが2つあります。stripIndent()は共通する行頭の空白を削除し、translateEscapes()は実行時の文字列内のエスケープシーケンスを処理します。

String raw = "  hello\\n  world";
System.out.println(raw);                    // hello\n  world
System.out.println(raw.translateEscapes()); // hello (newline) world

// stripIndent removes common leading whitespace
String indented = "    line 1\n    line 2\n    line 3";
System.out.println(indented.stripIndent()); // line 1\nline 2\nline 3

実践:HTMLメールテンプレート

テキストブロックを使って、パラメーター化されたHTMLメールテンプレートを構築します。

static String buildWelcomeEmail(String name, String activationLink) {
    return """
        <!DOCTYPE html>
        <html>
          <body>
            <h1>Welcome, %s!</h1>
            <p>Click the link below to activate your account:</p>
            <a href="%s">Activate Account</a>
          </body>
        </html>
        """.formatted(name, activationLink);
}

System.out.println(buildWelcomeEmail("Alice",
    "https://app.example.com/activate?token=abc123"));

テキストブロックとString.joinの比較

項目のリストには、テキストブロックよりString.joinやCollectors.joiningの方が柔軟です。固定された複数行の内容にはテキストブロックを、動的なリストにはjoinを使用してください。

import java.util.*;
import java.util.stream.*;

List<String> features = List.of("Unlimited storage", "Priority support", "AI assistant");

// Dynamic list: join
String bullet = features.stream()
    .map(f -> "  • " + f)
    .collect(Collectors.joining("\n"));
System.out.println(bullet);
// • Unlimited storage
// • Priority support
// • AI assistant

// Fixed template: text block + formatted
String plan = """
    PRO Plan — $29/month
    Features:
    %s
    """.formatted(bullet);
System.out.println(plan);

確認問題

テキストブロックで、閉じる"""の位置は何を決めますか。

まとめ:テキストブロックとString.format

要点:

  • テキストブロック(Java 15以降)は三重引用符を使用し、エスケープなしで複数行の構造を保持します
  • 閉じる\"\"\"の位置に基づいて、共通する行頭の空白が自動的に除去されます
  • テキストブロック内の二重引用符はエスケープする必要がありません
  • パラメーター化されたテンプレートには、テキストブロックに.formatted()を使用します
  • String.formatの指定子:%s、%d、%.2f、%n、%x、幅や配置のフラグ
  • 行末の空白を保持するには行末に\sを、行を結合するには行末に\を使用します

よくある質問

「テキストブロックと String.format」レッスンは無料ですか?

はい。「テキストブロックと String.format」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Java Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Java Academyコースには全4レッスンが含まれています。

「テキストブロックと String.format」で何を学びますか?

テキストブロックで複数行文字列を記述し、String.format のパターンでデータを整形します。 ブラウザで直接実行するハンズオンコードでJava Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Java Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのJava Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「テキストブロックと String.format」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このJava Academyレッスンでコードを書いて実行できますか?

はい。すべてのJava Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. String の不変性と String Pool
  2. 効率的な連結のための StringBuilder
  3. テキストブロックと String.format
  4. Pattern と Matcher による正規表現
← Java Academyに戻る