Java 12 introduced new methods to the String class that enhance string manipulation capabilities. These methods provide more flexibility and convenience for developers working with strings, offering solutions for common string-related tasks such as alignment and transformation.
New String Methods in Java 12
1. indent(int n)
The indent() method was enhanced in Java 12. It adjusts the indentation of each line in the string by the specified number of spaces. If the number is positive, spaces are added at the beginning of each line. If the number is negative, spaces are removed from the start of each line up to the specified number.
Syntax:
String result = str.indent(int n);
- n: The number of spaces to add (positive) or remove (negative).
Example:
public class IndentExample {
public static void main(String[] args) {
String str = "Java\nis\nawesome";
System.out.println("Original String:\n" + str);
System.out.println("Indented String:\n" + str.indent(4));
System.out.println("Reduced Indentation:\n" + str.indent(-2));
}
}
Output:
Original String:
Java
is
awesome
Indented String:
Java
is
awesome
Reduced Indentation:
Java
is
awesome
Explanation:
- Positive Indentation: Adds 4 spaces to each line in the string.
- Negative Indentation: Attempts to remove 2 spaces from each line. If the line has fewer spaces, all leading spaces are removed.
2. transform(Function<? super String, ? extends R> f)
The transform() method applies a function to the string and returns the result. This method allows for easy transformations and chaining operations on strings without intermediate variables.
Syntax:
<R> R result = str.transform(Function<? super String, ? extends R> f);
- f: The function to apply to the string.
Example:
import java.util.Locale;
public class TransformExample {
public static void main(String[] args) {
String str = "hello";
String upperCase = str.transform(String::toUpperCase);
System.out.println("Uppercase: " + upperCase);
int length = str.transform(String::length);
System.out.println("Length: " + length);
String reversed = str.transform(s -> new StringBuilder(s).reverse().toString());
System.out.println("Reversed: " + reversed);
}
}
Output:
Uppercase: HELLO
Length: 5
Reversed: olleh
Explanation:
- Uppercase Transformation: Converts the string to uppercase using
String::toUpperCase. - Length Calculation: Returns the length of the string using
String::length. - Reversal: Reverses the string using a lambda expression with
StringBuilder.
3. describeConstable()
The describeConstable() method returns an Optional describing the constant representation of the string. This method is part of the Java 12 effort to support more robust string handling, particularly in relation to ConstantDesc and Constable interfaces.
Syntax:
Optional<String> constant = str.describeConstable();
- Returns: An
Optionalcontaining the string if it is non-null, or an emptyOptionalif the string isnull.
Example:
import java.util.Optional;
public class DescribeConstableExample {
public static void main(String[] args) {
String str = "constant";
Optional<String> optional = str.describeConstable();
optional.ifPresentOrElse(
s -> System.out.println("Constant: " + s),
() -> System.out.println("No constant value present")
);
String nullStr = null;
Optional<String> emptyOptional = Optional.ofNullable(nullStr).flatMap(String::describeConstable);
System.out.println("Null String Optional: " + emptyOptional);
}
}
Output:
Constant: constant Null String Optional: Optional.empty
Explanation:
- Non-Null String: The
describeConstable()method returns anOptionalcontaining the string itself. - Null String: For a
nullstring, the method returns an emptyOptional.
4. resolveConstantDesc(MethodHandles.Lookup lookup)
The resolveConstantDesc() method is part of Java’s constant description mechanism, which was enhanced in Java 12. It allows strings to be used as constants in a more structured manner. This method is generally used in advanced use cases involving dynamic language features or frameworks.
Syntax:
String constant = str.resolveConstantDesc(MethodHandles.Lookup lookup);
- lookup: The lookup context used to resolve the constant description.
Example:
import java.lang.invoke.MethodHandles;
public class ResolveConstantDescExample {
public static void main(String[] args) {
String str = "constant";
try {
String resolved = str.resolveConstantDesc(MethodHandles.lookup());
System.out.println("Resolved Constant: " + resolved);
} catch (Exception e) {
System.out.println("Error resolving constant: " + e.getMessage());
}
}
}
Output:
Resolved Constant: constant
Explanation:
- Constant Resolution: The
resolveConstantDesc()method is used to resolve the string as a constant using the providedMethodHandles.Lookup.
Conclusion
Java 12 introduced several enhancements to the String class that provide developers with more tools to manipulate and transform strings. These methods simplify string handling and allow for more expressive and efficient code.
Summary:
indent(): Adjusts the indentation of each line in the string.transform(): Applies a function to the string and returns the result, enabling easier transformations.describeConstable(): Returns anOptionaldescribing the constant representation of the string.resolveConstantDesc(): Resolves the string as a constant description usingMethodHandles.Lookup.
By utilizing these new methods, you can write cleaner, more efficient Java code and take advantage of modern string-handling capabilities.