Java 10 introduced several features and enhancements. One significant feature is the introduction of Local-Variable Type Inference, commonly known as the "var" keyword. Let's explore this feature with an example:
Local-Variable Type Inference (var keyword):
Prior to Java 10, when declaring a variable, you had to explicitly mention its type. With Java 10's var keyword, you can now use type inference for local variables, making the code more concise while still maintaining type safety.
public class VarExample {
public static void main(String[] args) {
// Without var (Java 9 and earlier)
String withoutVar = "This is a string without var";
// With var (Java 10 and later)
var withVar = "This is a string with var";
// Type is inferred, but it remains strongly typed
System.out.println(withoutVar.getClass()); // Output: class java.lang.String
System.out.println(withVar.getClass()); // Output: class java.lang.String
}
}
In this example:
withoutVar
: Declaring a variable without the var keyword (as in previous Java versions).withVar
: Declaring a variable with the var keyword, allowing the type to be inferred.getClass()
: Demonstrating that both variables are of type String, proving that type inference does not compromise type safety.
Local-Variable Type Inference simplifies code, especially when the type is obvious from the initializer expression. However, it is important to use it judiciously, as overuse can lead to less readable code.
Other features introduced in Java 10 include:
Optional.orElseThrow()
Improvement: TheOptional
class now has an additional methodorElseThrow()
that does not require specifying a supplier when throwing an exception.Optional<String> optionalString = Optional.empty(); String result = optionalString.orElseThrow(); // Throws NoSuchElementException
CopyOf()
Method for Immutable Collections: The List, Set, and Map interfaces received a newcopyOf()
method to create immutable instances from existing collections.List<String> originalList = List.of("apple", "banana", "cherry"); List<String> immutableList = List.copyOf(originalList);
These features contribute to making Java code more concise and expressive while maintaining the principles of type safety and immutability.