New Features in Java 12

On March 19, 2019, Java 12 was released as part of the six-month release cycle. It was the new version of Java after the last LTS (Java 11). Java 12 introduced some new features and improvements for developers. We will discuss all the new features in Java 12.

1. New String methods in Java 12
2. Java 12 switch expression

New String methods in Java 12

String indent method(int n)

Java 12 introduced a new method in the String class which is the indent() method. This method adjusts the indentation of each line based on a specified number. It takes an integer n as an input parameter, which represents the number of spaces to be added to the beginning of each line in the string. We will see the how String indent() method works.

public String indent(int n)

It takes one parameter of integer type and returns the String after indentation.

If n > 0, then insert n spaces at the beginning of each line.
If n < 0, then remove n spaces from the beginning of each line.
If n < 0, and n < available spaces, remove all leading spaces of each line.
If n = 0, the method will not change the indentation of the string.

public class SwitchExample {
    public static void main(String[] args) {
        String str1 = "Welcome to JavaGoal.com";
        String indentedStr1 = str1.indent(0);
        System.out.println(indentedStr1);

        String str2 = "     Learning website JavaGoal.com";
        String indentedStr2 = str2.indent(-5);
        System.out.println(indentedStr2);

        String str3 = "JavaGoal.com A Learning Website";
        String indentedStr3 = str3.indent(5);
        System.out.println(indentedStr3);
    }
}

Output:

Welcome to JavaGoal.com

Learning website JavaGoal.com

JavaGoal.com A learning Websitr

transform(Function f)

The transform(Function f) method was a new feature of Java 12 for the String class. It applies the provided function to the string and returns the result of the function.

public <R> R transform(Function<? super String, ? extends R> f)

@param the type of the result
@return the result of applying the function to this string

The Function interface takes a string as input and returns a value of the specified type R. The ? extends R wildcard denotes that the function can return any subtype of R, including R itself, as output.

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class TransformExample {

    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("John");
        names.add("Mary");
        names.add("Peter");

        // Define a function that takes a String and returns an Integer
        Function<String, Integer> lengthFunction = String::length;

        // Transform the list of strings to a list of integers using the lengthFunction
        List<Integer> lengths = transform(names, lengthFunction);

        // Print the transformed list of integers
        System.out.println(lengths);
    }

    public static <R> List<R> transform(List<String> list, Function<? super String, ? extends R> f) {
        List<R> result = new ArrayList<>();

        // Apply the function to each element of the input list
        for (String s : list) {
            R r = f.apply(s);
            result.add(r);
        }

        return result;
    }
}

Output: [4, 4, 5]

Optional describeConstable() Method

Java introduced a new Interface Constable in the release of Java 12 and now the String class also implements the Constanle interface. So String class provides the implementation to the describeConstable() method of the Constable interface. The describeConstable() method returns an optional string that describes the value of the Constable object.

This method returns an Optional object containing the String object itself, which is its canonical representation.

import java.util.Optional;

public class Example {

    public static void main(String[] args) {
        String s = "Hello, world!";
        Optional<String> canonical = s.describeConstable();
        if (canonical.isPresent()) {
            System.out.println("Canonical representation: " + canonical.get());
        } else {
            System.out.println("Canonical representation not available");
        }

    }
}

Output: Canonical representation: Hello, world!

Java 12 switch expression

In Java 12 switch expression was introduced as a new feature that provides a concise and expressive way to handle multiple cases in a switch statement. If you are not familiar with the detailed workings of the switch statement, then you can read the switch statement from here. It simplifies the code and makes it more readable.
So, let’s discuss each change of the switch statement in Java 12.

No need for a break statement

Before Java 12 we use the break statement to prevent fallthroughs but now we don’t need to use the break statement to prevent fallthroughs.

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3;
        String dayName;
        
        switch (day) {
            case 1:
                dayName = "Monday";
                break;
            case 2:
                dayName = "Tuesday";
                break;
            case 3:
                dayName = "Wednesday";
                break;
            default:
                dayName = "Invalid day";
                break;
        }
        
        System.out.println(dayName);
    }
}

Output: Wednesday

In the above example, we used a switch statement that takes an integer variable day as its input. It compares the value of the day to three different cases and executes the corresponding day name to the dayName variable. But as we know we use the break statement is used to stop the fallthrough of execution so that only one case is executed and the rest are skipped. Now we will see how we can achieve the same task in Java 12.

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3;
        
        String dayName = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            default -> "Invalid day";
        };
        
        System.out.println(dayName);
    }
} 

Output: Wednesday

Here we used the new enhanced switch expression syntax that was introduced in Java 12. As you can see, here we haven’t used the break statement to stop the fallthrough of execution because each case is followed by an arrow (->) that specifies the expression to be executed if that case is matched. Now the switch expression automatically returns the value from the matched expression.

Multiple constants in the same label

We can define multiple constants in the same label in Java using the switch statement. Let’s try an example, how does it work before Java 11?

public class SwitchExample {
    public static void main(String[] args) {
        int dayOfWeek = 5;
        String dayName;

        switch(dayOfWeek) {
            case 1, 2, 3, 4, 5:
                dayName = "Weekday";
                break;
            case 6, 7:
                dayName = "Weekend";
                break;
            default:
                dayName = "Invalid day";
        }

        System.out.println("The day is a " + dayName);

    }
}

Output: The day is a Weekday

In this example, we used the multiple constants (1, 2, 3, 4, and 5) in the same label for the first case statement.

Let’s see the same example by use of Java 12’s new feature

public class SwitchExample {
    public static void main(String[] args) {
        int dayOfWeek = 5;
        String dayName = switch(dayOfWeek) {
            case 1, 2, 3, 4, 5 -> "Weekday";
            case 6, 7 -> "Weekend";
            default -> "Invalid day";
        };

        System.out.println("The day is a " + dayName);
    }
}

Output: The day is a Weekday

Leave a Comment