Java Features You Didn’t Know Existed (But Should)

posted 3 min read

Java is a versatile and powerful programming language, evolving significantly since its inception. While many developers are familiar with its core functionalities, Java contains a treasure trove of lesser-known features that can enhance your productivity and code quality. In this blog, we explore 10 underrated Java features, complete with use cases and code examples, to supercharge your programming skills.


1. Text Blocks (Introduced in Java 13)

Text blocks simplify the handling of multi-line strings, eliminating the need for cumbersome concatenations and escaping.

Use Case:

Creating JSON, HTML, or SQL templates without excessive concatenation.

```java
String jsonTemplate = """
    {
        "name": "John Doe",
        "age": 30,
        "isDeveloper": true
    }
    """;

System.out.println(jsonTemplate);
```

Why It’s Useful:

Improves readability and reduces boilerplate when working with large strings.


2. Pattern Matching for instanceof (Introduced in Java 16)

No need for explicit casting after an instanceof check.

Use Case:

Streamlining object type checks and access.

```java
Object obj = "Hello, Java!";
if (obj instanceof String str) {
    System.out.println(str.toUpperCase());
}
```

Why It’s Useful:

Cleaner and more concise type-checking logic.


3. Switch Expressions (Introduced in Java 14)

Switch statements can now return values, making them more expressive.

Use Case:

Replacing verbose if-else chains for cleaner conditional logic.

```java
int day = 5;
String dayType = switch (day) {
    case 1, 7 -> "Weekend";
    case 2, 3, 4, 5, 6 -> "Weekday";
    default -> "Invalid day";
};
System.out.println(dayType);
```

Why It’s Useful:

Reduces boilerplate and enhances readability in decision-making constructs.


4. Optional.orElseThrow()

Provides a shorthand for throwing exceptions if a value is absent.

Use Case:

Enforcing mandatory fields or ensuring values are present.

```java
Optional<String> name = Optional.empty();
String value = name.orElseThrow(() -> new IllegalArgumentException("Value is missing"));
```

Why It’s Useful:

Promotes better error handling with minimal code.


5. Compact Number Formatting (Introduced in Java 12)

A feature of java.text.NumberFormat for formatting numbers in human-readable forms.

Use Case:

Displaying large numbers succinctly, e.g., for reports or dashboards.

```java
NumberFormat formatter = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
System.out.println(formatter.format(1000));  // Outputs "1K"
System.out.println(formatter.format(1000000));  // Outputs "1M"
```

Why It’s Useful:

Makes large numbers more user-friendly in UI and reports.


6. Records (Introduced in Java 14)

A concise way to create immutable data classes with minimal boilerplate.

Use Case:

Simplifying data-transfer object (DTO) creation.

```java
public record Person(String name, int age) {}

Person person = new Person("Alice", 25);
System.out.println(person.name());
System.out.println(person.age());
```

Why It’s Useful:

Reduces the overhead of creating getters, constructors, and toString() methods manually.


7. Parallel Streams

Enables parallel processing of data streams for better performance on multicore systems.

Use Case:

Speeding up computations for large data collections.

```java
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
numbers.parallelStream()
       .map(num -> num * num)
       .forEach(System.out::println);
```

Why It’s Useful:

Efficiently leverages multi-core processors for compute-intensive tasks.


8. String Methods: lines() and repeat()

Java 11 introduced helpful utilities for string manipulation.

Use Case 1: Splitting a multi-line string into lines.

```java
String text = "Hello\nWorld\nJava";
text.lines().forEach(System.out::println);
```

Use Case 2: Repeating strings easily.

```java
String repeated = "Java".repeat(3);
System.out.println(repeated);  // Outputs "JavaJavaJava"

### Why It’s Useful:
Saves time and enhances code readability for common string operations.

---

## 9. **Stream Teeing (Introduced in Java 12)**
Splits a stream into two and processes each with a different collector.

### Use Case:
Simultaneously calculating the sum and count of a collection.

    ```java
    List<Integer> numbers = List.of(1, 2, 3, 4, 5);
    
    Map<Boolean, Integer> result = numbers.stream()
        .collect(Collectors.teeing(
            Collectors.summingInt(i -> i),
            Collectors.counting(),
            (sum, count) -> Map.of(true, sum, false, count.intValue())
        ));
    
    System.out.println(result); // {true=15, false=5}
    ```

### Why It’s Useful:
Simplifies complex stream processing pipelines.

---

## 10. **Sealed Classes (Introduced in Java 15)**
Allows you to control the inheritance of a class.

### Use Case:
Defining a strict hierarchy for domain models.

    ```java
    public sealed class Shape permits Circle, Square {}
    
    public final class Circle extends Shape {}
    public final class Square extends Shape {}
    ```

### Why It’s Useful:
Improves maintainability and enforces a specific type hierarchy in your application.

---

Java continues to innovate with features that make coding more concise, readable, and powerful. Whether you're dealing with data structures, improving performance, or simply making your code cleaner, these hidden gems can help you write better Java applications. 

### Which of these features are you most excited to try? Share your thoughts below!
If you read this far, tweet to the author to show them you care. Tweet a Thanks
I came across java programming  language over 9 years ago, it can be challenging to learn at the beginning but with time it gets interesting. Good to know that there are more features.
Nice, article. Concise explanation!

Thanks
Nice, concise article on new features since Java 9.
Virtual Threads is also an important feature added since Java 21.

More Posts

5 Internal Developer Platforms You Need to Know About!

Juraj Karadža - Nov 24, 2024

IO class in Java 25

Pravin - Sep 22

Power Up Java with AI: Integrate LLaMA 3 Using Spring Boot

Mandeep Dhakal - Jul 30

Why Java Remains the Top Choice for Modern Server Applications

Aditya Pratap Bhuyan - Jun 28

Containerized Java: Fix Version Compatibility with Docker

Aditya Pratap Bhuyan - Jun 26
chevron_left