Java 13: Text Blocks and Refinements

Java 13: Text Blocks Preview and Switch Finalization
Java 13 (September 2019) refined preview features and improved developer ergonomics. It brought text blocks to preview status and evolved switch expressions based on feedback.
1. Text Blocks (Second Preview)
Text blocks became more polished in Java 13 with better handling of whitespace.
// Text blocks for JSON
String jsonData = """
{
"user": {
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"tags": ["admin", "developer"]
}
}
""";
// Text blocks for HTML
String htmlTemplate = """
<!DOCTYPE html>
<html>
<head><title>My Page</title></head>
<body>
<h1>Welcome!</h1>
<p>This is a text block.</p>
</body>
</html>
""";
// Text blocks for SQL
String sqlQuery = """
SELECT u.id, u.name, u.email,
COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > ?
GROUP BY u.id
ORDER BY order_count DESC
""";
// Text blocks with escape sequences
String withTabs = """
Name\tAge\tCity
Alice\t25\tNew York
Bob\t30\tLos Angeles
""";
// Careful with leading/trailing whitespace
String trimmed = """
Hello
World
""".stripIndent(); // Removes common leading whitespace2. Enhanced Switch Expression
Switch expressions were refined with better semantics.
// More sophisticated patterns (Preview)
String result = switch (day) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
case SATURDAY, SUNDAY -> "Weekend";
};
// Complex logic with yield
String category = switch (score) {
case int s when s < 60 -> "Fail";
case int s when s < 80 -> "Pass";
case int s when s < 90 -> "Good";
default -> "Excellent";
};
// Pattern matching (future direction)
Object obj = "Hello";
String message = switch (obj) {
case String s -> "String: " + s;
case Integer i -> "Integer: " + i;
default -> "Unknown";
};3. Dynamic CDS Archives
Class Data Sharing improvements for faster startup.
# Generate CDS archive
java -Xshare:dump -XX:SharedArchiveFile=app-cds.jsa \
-cp app.jar
# Use CDS archive
java -Xshare:on -XX:SharedArchiveFile=app-cds.jsa \
-cp app.jar com.example.Main
# Benefit: Faster startup times (20-50% improvement)
# Applications start with pre-loaded class data4. ZGC Improvements
Garbage collector improvements for low-latency applications.
# Enable ZGC (Experimental)
java -XX:+UnlockExperimentalVMOptions -XX:+UseZGC MyApp
# Benefits:
# - Sub-millisecond pause times
# - Concurrent garbage collection
# - Handles heaps up to 16TB
# - Great for microservices and real-time systems5. String Methods
New methods for string comparison and searching.
// indexOf with from index
String text = "The quick brown fox jumps over the lazy dog";
int pos = text.indexOf("fox"); // 16
// compareTo with case insensitivity
"Hello".compareToIgnoreCase("HELLO"); // 0
// Advanced: MethodHandle improvements6. Socket API Replatforming
Socket implementation rewritten for better performance.
import java.net.*;
// Transparent improvements - no code changes needed
ServerSocket serverSocket = new ServerSocket(8080);
Socket clientSocket = serverSocket.accept();
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
// New implementation is faster and more maintainable
// Benefits: Better performance on Windows platformDeveloper Impact
Positive:
- Text Blocks: More polished multi-line string handling
- Performance: Faster startup with CDS
- Low Latency: ZGC suitable for real-time apps
- Better Feedback Loop: Community preview process working
Challenges:
- Preview Status: Features still subject to change
- No LTS: Short 6-month support window
- Learning Curve: Text block indentation rules
Pros and Cons
Pros ✅
- Text Blocks Refinement: Better handling of whitespace and escapes
- Switch Expressions: Moving toward pattern matching
- CDS Performance: Significant startup time improvements
- ZGC Maturity: Sub-millisecond GC pauses
- Community Driven: Benefits from preview feedback
Cons ❌
- Preview Features: Still experimental
- Short Support: Non-LTS release with 6-month EOL
- No LTS: Consider Java 11 or 17 for stability
- Learning Curve: Text block formatting rules complex
Practical Example
public class ConfigurationLoader {
// Using text blocks for configuration
private static final String DEFAULT_CONFIG = """
{
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp_db"
},
"cache": {
"ttl": 3600,
"maxSize": 10000
}
}
""";
// SQL queries as text blocks
private static final String INSERT_USER_QUERY = """
INSERT INTO users (name, email, created_at)
VALUES (?, ?, NOW())
""";
// HTTP response template
private static final String ERROR_RESPONSE = """
{
"status": "error",
"message": "%s",
"timestamp": "%s"
}
""";
}Text Block Indentation Rules
// Understanding how text blocks handle indentation
// Example 1: Simple alignment
String aligned = """
Hello
World
""";
// Result: "Hello\nWorld\n"
// Example 2: Common leading whitespace is removed
String indented = """
Hello
World
""";
// Result: "Hello\nWorld\n"
// The 4-space indent (common prefix) is removed
// Example 3: Different indentation levels
String mixed = """
Line one
Line two (extra indent)
Line three
""";
// Result: "Line one\n Line two (extra indent)\nLine three\n"
// Relative indentation is preserved
// Controlling indentation
String compact = """
First
Second""";
// Result: "First\nSecond"
// No trailing newline if last line has no newline
// Using indent() method
String indented10 = DEFAULT_CONFIG.indent(10);
// Adds 10 spaces to each lineConclusion
Java 13 refined the preview features and delivered solid performance improvements. While not an LTS release, it represents the evolution of Java's design philosophy toward functional and modern syntax. Developers on Java 13 should consider moving to Java 17 (next LTS) for long-term stability.
Key Points:
- Text blocks mature and ready for Java 14
- Switch expressions evolving toward pattern matching
- CDS and ZGC provide significant performance benefits
- Short release cycle allows rapid innovation