Open In App

What’s New in Java 15 and C++ 20?

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Java 15, includes several new features and enhancements. Some notable new methods in Java 15 include:

Hidden Classes

This feature allows classes to be defined as hidden, which means they are not visible to code outside of the package in which they are defined. This can be used to improve the security and maintainability of code. It is mainly used for runtime code generation and class redefinition. Below is an example of the above feature:

Java




// In a file called 'HiddenClass.java'
package hidden;
  
final class HiddenClass {
    private final int value;
  
    public HiddenClass(int value) {
        this.value = value;
    }
  
    public int getValue() {
        return value;
    }
}
  
// In a file called 'Main.java'
import hidden.HiddenClass;
  
public class Main {
    public static void main(String[] args) {
        // Compiler Error: hidden.HiddenClass is not visible
        // HiddenClass obj = new HiddenClass(5);
    }
}


Text Blocks

This feature allows developers to write multi-line string literals in a more readable and convenient format. This can make it easier to write and maintain code that uses large strings, such as JSON or HTML. This feature eliminates the need to escape characters and concatenate string lines. Below is an example of the above feature:

Java




public class Main {
    public static void main(String[] args) {
        String html = """
                      <html>
                        <body>
                          <p>Hello, World!</p>
                        </body>
                      </html>
                      """;
        System.out.println(html);
    }
}


Records

This feature allows developers to define simple, immutable data classes with minimal boilerplate code. This can make it easier to write and maintain code that works with data structures. This feature is similar to struct in C++, and it’s a way to define a data class without the need to write getters, setters, constructors, and hashcode methods. Below is an example of the above feature:

Java




public record Point(int x, int y) {}
  
public class Main {
    public static void main(String[] args) {
        Point point = new Point(1, 2);
        System.out.println(point.x());
        System.out.println(point.y());
    }
}


Pattern Matching for instanceof

This feature allows developers to perform pattern matching on the result of an instanceof operation. This can make it easier to write and maintain code that performs type checking and type casting. This feature allows developers to use the ‘instanceof’ operator in a more functional way. Below is an example of the above feature:

Java




class Shape {
    void draw() {
        System.out.println("drawing a shape");
    }
}
  
class Circle extends Shape {
    void draw() {
        System.out.println("drawing a circle");
    }
}
  
class Square extends Shape {
    void draw(int a) {
        System.out.println("drawing a square of side " + a);
    }
}
  
public class Main {
    public static void main(String[] args) {
        Shape shape = new Circle();
        if (shape instanceof Circle c) {
            c.draw();
        } else if (shape instanceof Square s) {
            s.draw(3);
        } else {
            shape.draw();
        }
    }
}


Switch Expressions Enhancements

This feature allows developers to use switch expressions as statements and also use them in a more concise way. Below is an example of the above feature:

Java




public class Main {
    public static void main(String[] args) {
        int x = 1;
        int y = switch (x) {
            case 1 -> 10;
            case 2 -> 20;
            default -> 30;
        };
        System.out.println(y);
    }
}


Foreign Linker API

This feature allows the loading of native libraries and C header files. This feature allows developers to access native libraries and headers directly from java code. Below is an example of the above feature:

Java




import java.io.*;
import jdk.incubator.foreign.CLinker;
import jdk.incubator.foreign.MemorySegment;
import jdk.incubator.foreign.MemoryAddress;
  
class GFG {
    public class Main {
        public static void main(String[] args) {
            CLinker cl = CLinker.getInstance();
            try (MemorySegment segment = cl.allocate(16, true)) {
                MemoryAddress address = segment.baseAddress();
                cl.putInt(address, 42);
                int value = cl.getInt(address);
                System.out.println(value);
            }
        }
    }
}


Note: To use the Foreign Linker API in Java 15, you will need to use the –enable-preview flag when compiling and running your code, as it is an experimental feature. Additionally, keep in mind that this feature is platform-specific, and its behavior may vary across different operating systems and architectures.

These are just a few examples of the new features and enhancements in Java 15. It’s always good to keep an eye on the latest updates to the language, as they can make it easier to write and maintain code and improve performance.

What’s New in C++ 20?

C++20, the latest version of the C++ programming language, includes several new features and enhancements. Some notable new methods in C++20 include:

Modules

This feature allows developers to organize and manage code in a more modular way. This can make it easier to write and maintain large, complex codebases. Modules provide a way to package and reuse code, hiding implementation details and reducing the number of headers that need to be included in a compilation unit. Below is an example of the above feature:

C++




// In a file called 'module.cppm'
export module example;
  
export int add(int x, int y) {
    return x + y;
}
  
export int multiply(int x, int y) {
    return x * y;
}
  
// In a file called 'main.cpp'
import example;
  
int main() {
    int result = add(2, 3);
    int product = multiply(2, 3);
    std::cout << "Result: " << result << '\n';
    std::cout << "Product: " << product << '\n';
    return 0;
}


Note: This code snippet shows an example of using the spaceship operator to compare two custom types, where the operator compares the three elements of the struct and returns a new struct with the comparison results.

Concepts

This feature allows developers to express constraints on template parameters in a more readable and maintainable way. This can make it easier to write and maintain generic code. Concepts provide a way to specify requirements on template parameters, making it possible to write more generic and expressive code. Below is an example of the above feature:

C++




template <typename T>
concept Addable = requires(T a, T b) {
    { a + b } -> T;
};
  
template <Addable T>
T add(T a, T b) {
    return a + b;
}
  
int main() {
    std::cout << add(2, 3) << std::endl;
    std::cout << add(2.3, 3.4) << std::endl;
    return 0;
}


Ranges

This feature provides a set of algorithms and ranges that allow developers to express and manipulate sequences of data in a more readable and maintainable way. Ranges provide a way to express operations on sequences of elements, making it possible to write more concise and expressive code. Below is an example of the above feature:

C++




#include <ranges>
  
std::vector<int> nums {1, 2, 3, 4, 5};
  
for (int i : std::ranges::filter(nums, [](int x) { return x % 2 == 0; }))
    std::cout << i << '\n';


Coroutines

This feature allows developers to write asynchronous code in a more readable and maintainable way. Coroutines provide a way to express asynchronous operations in a way that looks similar to synchronous code, allowing developers to write more readable and maintainable code. Below is an example of the above feature:

C++




#include <iostream>
#include <coroutine>
  
std::coroutine_handle<> foo() {
    std::cout << "Hello, ";
    co_yield;
    std::cout << "world!\n";
}
  
int main() {
    auto f = foo();
    f();
    f();
}


Spaceship Operator

This feature allows developers to define a three-way comparison operator ( <=> ) which can be used to implement comparison operators for user-defined types. This operator is also known as the “Combined comparison operator” and it allows one to compare two objects in a more intuitive way. Below is an example of the above feature:

C++




struct MyType
{
    int a;
    int b;
    int c;
};
  
MyType operator<=>(MyType const & lhs, MyType const & rhs)
{
    if (lhs.a < rhs.a) return MyType{-1, 0, 0};
    if (lhs.a > rhs.a) return MyType{ 1, 0, 0};
    if (lhs.b < rhs.b) return MyType{ 0,-1, 0};
    if (lhs.b > rhs.b) return MyType{ 0, 1, 0};
    if (lhs.c < rhs.c) return MyType{ 0, 0,-1};
    if (lhs.c > rhs.c) return MyType{ 0, 0, 1};
    return MyType{0, 0, 0};
}
  
int main() {
    MyType a{1, 2, 3};
    MyType b{1, 2, 4};
    MyType c = a <=> b;
    std::cout << c.a << "," << c.b << "," << c.c << std::endl;
    return 0;
}


Initializer Lists

This feature allows developers to define lists of values that can be used to initialize variables and objects. Initializer lists provide a way to express lists of values in a more readable and maintainable way. Below is an example of the above feature:

C++




#include <iostream>
  
int main() {
    int a[] = {1, 2, 3};
    std::cout << a[0] << std::endl;
    std::cout << a[1] << std::endl;
    std::cout << a[2] << std::endl;
    return 0;
}


Formatting

This feature provides a type-safe, extensible, and efficient way to format text. Formatting provides a way to format text in a way that is similar to the printf function but is type-safe and extensible. Below is an example of the above feature:

C++




#include <iostream>
#include <format>
  
int main() {
    std::cout << std::format("The answer is {:d}\n", 42);
    std::cout << std::format("The answer is {:x}\n", 42);
    std::cout << std::format("The answer is {:f}\n", 3.14);
    return 0;
}


These are just a few examples of the new features and enhancements in C++ 20. It’s always good to keep an eye on the latest updates to the language, as they can make it easier to write and maintain code and improve performance.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads