Strings and text blocks: C# and Java

A string is immutable in both languages, and both give a builder for the case that changes one many times. The rest is syntax: C# has interpolation with a dollar sign, Java has concatenation and String.format; C# has a span over a string, Java has substring; C# has a raw string, Java has a text block. The task formats a line, builds one in a loop, cuts a field out of a log line and writes a literal of two lines.

The task in C#

The interpolation with its alignment, a StringBuilder over three numbers, a ReadOnlySpan<char> over the level field of a log line, and a raw string literal:

using System.Text; Console.WriteLine("strings 1.0"); var name = "Ada"; var born = 1815; Console.WriteLine($"{name} was born in {born}"); Console.WriteLine($"padded [{name,-6}][{born,6}]"); var builder = new StringBuilder(); for (var i = 1; i <= 3; i++) { builder.Append(i).Append(' '); } Console.WriteLine($"builder [{builder.ToString().TrimEnd()}]"); var text = "2024-03-10 INFO started"; var level = text.AsSpan(11, 4); Console.WriteLine($"level {level} upper {level.ToString().ToUpperInvariant()}"); Console.WriteLine($"equals {level.SequenceEqual("INFO")}"); var block = """ line one line two """; Console.WriteLine($"block lines {block.Split('\n').Length}"); Console.WriteLine($"block first {block.Split('\n')[0]}");

dotnet run
echo "status: $?"

strings 1.0
Ada was born in 1815
padded [Ada   ][  1815]
builder [1 2 3]
level INFO upper INFO
equals True
block lines 2
block first line one
status: 0

The same task in Java

The same four things with the Java tools: concatenation and printf, the builder, a substring and a text block:

public class StringsText { public static void main(String[] args) { System.out.println("strings 1.0"); String name = "Ada"; int born = 1815; System.out.println(name + " was born in " + born); System.out.printf("padded [%-6s][%6d]%n", name, born); StringBuilder builder = new StringBuilder(); for (int i = 1; i <= 3; i++) { builder.append(i).append(' '); } System.out.println("builder [" + builder.toString().trim() + "]"); String text = "2024-03-10 INFO started"; String level = text.substring(11, 15); System.out.println("level " + level + " upper " + level.toUpperCase()); System.out.println("equals " + level.equals("INFO")); String block = """ line one line two """; System.out.println("block lines " + block.lines().count()); System.out.println("block first " + block.lines().findFirst().orElse("")); } }

javac -g -d out StringsText.java
java -cp out StringsText
echo "status: $?"

strings 1.0
Ada was born in 1815
padded [Ada   ][  1815]
builder [1 2 3]
level INFO upper INFO
equals true
block lines 2
block first line one
status: 0

What differs

The next page is about failure: the exception both languages have, and the one Java checks.

Exercises

  1. Format the same padded line with a C# format item and a Java format string and compare the two outputs.
  2. Cut the timestamp out of the log line in both languages.
  3. Measure the allocation of the span version and the substring version with the method of lesson 106.
  4. Write a text block in Java with three lines and check what lines() counts.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How does C# interpolate a string?

    Answer

    With a dollar sign before the literal and holes in braces

    The page writes $"..." with alignment and format in the holes.

  2. What does a ReadOnlySpan<char> over a string copy?

    Answer

    Nothing: it is a view into the string

    The page cuts the level with AsSpan and no allocation.

  3. What does this program print? var name = "Ada"; var born = 1815; Console.WriteLine($"padded [{name,-6}][{born,6}]");

    Answer

    padded [Ada ][ 1815]

    The C# alignment is measured in the page output.

  4. What is a Java text block?

    Answer

    A multi-line string literal in three quotes, dedented by the compiler

    The page counts the lines of one with lines().

  5. What does this program print? using System.Text; var builder = new StringBuilder(); for (var i = 1; i <= 3; i++) { builder.Append(i).Append(" "); } Console.WriteLine(builder.ToString().TrimEnd());

    Answer

    1 2 3

    The builder appends each number and a space.

  6. Why does Java substring copy in Java 7 and later?

    Answer

    To keep the small substring from holding the whole original string alive

    A span in C# makes the opposite trade and keeps the original alive.

  7. What does this program print? var text = "2024-03-10 INFO started"; var level = text.AsSpan(11, 4); Console.WriteLine(level.ToString());

    Answer

    INFO

    The span over the field is the level text of the log line.

  8. Why does a chain of + in a loop cost more than a builder?

    Answer

    Every concatenation makes a new string, so the loop copies the whole text each time

    The C# course measures this in lesson 106.

  9. What does this program print? Console.WriteLine("abc".Length);

    Answer

    3

    The length of the string is three characters.

  10. How does Java format a number with two decimals?

    Answer

    String.format("%.2f", value)

    The page formats the sums with that call.

The C# program was built with the .NET SDK 10.0.303 and the Java program with OpenJDK 21.0.13.1 (javac 21.0.13.1), both run on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.

Article author: Arthur Isaev