Extremely Serious

Category: Modular Java (Page 1 of 2)

Record Class

A record class is a restricted form of classes that models data as data. Thus, also can be thought as data only class. Additionally, this type of class is immutable.

It automatically implements the following methods:

  • public boolean equals...
  • public int hashCode...
  • public String toString() {...}

The class generated by the record is a final class.

The constructor will also be handled and the parameters is matching the arrangement of the record parameter(s).

Use Cases

  • Data Transfer Objects (DTO) (i.e. not applicable to JPA entities)
  • Compound map keys
  • Multiple return values

Syntax

record <IDENTIFIER>([[[<FIELD_TYPE_1> <FIELD_NAME_1>][, <FIELD_TYPE_2> <FIELD_NAME_2>]][,... <FIELD_TYPE_2> <FIELD_NAME_N>]]) {}
Token Description
IDENTIFIER A valid Java identifier.
FIELD_TYPE_1
FIELD_TYPE_2
FIELD_TYPE_N
The type of the field(s) in the record parameter(s).
FIELD_NAME_1
FIELD_NAME_2
FIELD_NAME_N
The name of the field(s) in the record parameter(s).

The identifier has an equivalent cannonical constructor with parameters equivalent to its parameters.

Each fields has the following:

  • private final field of the same name.
  • public accessor method of the same name and type.

Example

record Person(String firstName, String lastName) {}

The above example is equivalent to the following class definition:

public final class PersonC {

    private final String firstName;
    private final String lastName;

    public PersonC(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() {
        return this.firstName;
    }

    public String lastName() {
        return this.lastName;
    }

    public boolean equals...
    public int hasCode...
    public String toString() {...}

}

Compact Constructor

In the record definition we can use a compact constructor. This constructor is the shorthand form of the generated default constructor. All of the fields indicated on the record parameters are implicitly available in it.

Syntax of the Compact Constructor

pubic <IDENTIFIER> {
    // Initilization logic.
}

The IDENTIFIER here is matching the record IDENTIFIER, just like when you are writing a constructor of a class but without parameters even the parentheses.

Example Usage

record Person(String firstName, String lastName) {
    public Person {
        java.util.Objects.requireNonNull(firstName);
        java.util.Objects.requireNonNull(lastName);
    }
}

Module Resolution

Resolve modules from the root module using the following syntax:

java --show-module-resolution -p <MODULE_PATHS> -m <ROOT_MODULE>
Identifier Description
MODULE_PATHS List of modules paths delimited by semi-colon (i.e. ;).
ROOT_MODULE The module to start the resolution.

Module-Info Syntax

[open] module <MODULE_NAME> {
    [[requires [transitive] <MODULE_NAME>;]
    [exports <PACKAGE>[ to <MODULE_NAME_1>[,<MODULE_NAME_2>..,<MODULE_NAME_N>];]
    [opens <PACKAGE>;]
    [provides <SERVICE> with <SERVICE_IMPLEMENTATION_1>[,<SERVICE_IMPLEMENTATION_2>..,<SERVICE_IMPLEMENTATION_N>];]
    [uses <SERVICE>;]]
}
Identifier Description
module The module keyword that holds the module directives.
<MODULE_NAME> The module identier.
<PACKAGE> The package identifier.
requires The requires directive indicates that this module depends on another module. ^1
transitive The transitive directive indicates that the user of the current module will also requite another module that the current user will also have access into.
exports The exports directive indicates which public types of the module's package are accessible to other modules. ^1
opens The opens directive also indicates which public types of the module's package are accessible to other modules. The difference between that and exports is that opens is not for compile time, only during runtime, while exports is for both compile time and runtime. The opens directive can typically be used when you want to allow other modules to use reflection for the types in the specified packages, but not to use them during compile time. Let's make this more clear by means of an example. ^1
open This is like the opens directive but with this it opens the whole module.
to <MODULE_NAME_1>[, <MODULE_NAME_2>.., <MODULE_NAME_N>] This indicates to target just specific module(s).
provides...with The provides...with directive indicates that the module provides a service implementation.^1
uses The uses directive indicates that the module requires a service implementation.
<SERVICE> The interface or abstract class that will be implemented as a service.
<SERVICE_IMPLEMENTATION_1>[, <SERVICE_IMPLEMENTATION_2>.., <SERVICE_IMPLEMENTATION_N>] The implementation classes of the SERVICE_INTERFACE.

Java Text Blocks

The text blocks is Java's way to simplify rendering of a string that spans multiple lines. A text block begins with three double-quote characters followed by a line terminator.^1

Example:

String text = """
    The quick 
    brown fox 
    jumps over 
    the lazy dog""";

The above example is equivalent to:

String text = "The quick \n"
    + "brown fox \n" 
    + "jumps over \n"
    + "the lazy dog";

Notice who how simple the example against its equivalent.

Incidental and essential white space

The java text blocks differentiates the incidental white space from essential white space^1. Like the following example:

void writeHTML() {
    String html = """
········<html>
········    <body>
········        <p>Hello World.</p>
········    </body>
········</html>
········""";
    writeOutput(html);
}

The dots, preceding the tag represents the incidental white spaces while the space preceding the tag not including the dots, represents the essential white spaces.

Normally the left incidental white space can be controlled by the location of the ending delimiter of the text blocks.

Trailing white space on each line in a text block is also considered incidental and is stripped away by the Java compiler^1.

Removing the ending new line of each line

Using the backslash at the end of each line will remove the implicit \n character.

String text = """
    The quick \
    brown fox \
    jumps over \
    the lazy dog""";

If you output the preceding variable it will become a single line like the following:

The quick brown fox jumps over the lazy dog

Sample Usage of Teeing Collector

//A Stream of Integers
var ints = Stream.of(10, 20, 30 , 40);

//Calculate the average using the Collectors.teeing method.
long average = ints.collect(
        Collectors.teeing(
                
                //Sum all of the integers in the stream.
                Collectors.summingInt(Integer::valueOf),
                
                //Count the content of the stream.
                Collectors.counting(),
                
                //Calculate the average.
                ( sum, count) -> sum / count
        )
);

System.out.println(average);

Sample HttpClient.sendAsync() Method Usage

//Create an instance of HttpClient using its builder.
HttpClient httpClient = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)
        .build();

//Create an instance of HttpRequest using its builder.
HttpRequest req = HttpRequest.newBuilder(URI.create("https://www.google.com"))
            .GET()
            .build();

/* Use the httpClient.sendAsync() method and encapsulate the response
in the CompletableFuture. */
CompletableFuture<HttpResponse> resFuture =
        httpClient.sendAsync(req, HttpResponse.BodyHandlers.ofString());

//Use the resFuture.thenAccept to wait for the async response.
resFuture.thenAccept(res -> System.out.println(res.version()));

//Wait for the resFuture to to complete.
resFuture.join();

Java Switch Expression

Syntax

switch(VARIABLE) {
	case MATCH_1 [, MATCH_2][, MATCH_N] -> EXPRESSION; | THROW-STATEMENT; | BLOCK
	default -> EXPRESSION; | THROW-STATEMENT; | BLOCK
}
Token Description
VARIABLE The variable to test.
MATCH_1, MATCH_2, MATCH_N The value or values that can match the VARIABLE.
EXPRESSION A expression to execute.
THROW-STATEMENT A expression that throws an exception.
BLOCK A block of statements to execute.

If a return value is required use the yield keyword instead of return.

Example

public enum Day { 
	SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; 
}

Day day = Day.WEDNESDAY;

int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY -> 7;
    case THURSDAY, SATURDAY -> {
        System.out.println(8);
        yield 8;
    }
    case WEDNESDAY -> {
        System.out.println(9);
        yield 9;
    }
    default -> {
        throw new IllegalStateException("Invalid day: " + day);
    }
};

System.out.println(numLetters);

ShowCodeDetailsInExceptionMessages Java Option

Use the following java option to have a more verbose exception message especially for NullPointerException:

-XX:+ShowCodeDetailsInExceptionMessages

For example, if we have the following snippet:

var a = null;
a.b = 1;

Running the above snippet will have the following exception:

Exception in thread "main" java.lang.NullPointerException: Cannot assign field "b" because "a" is null

Note: This is more useful if the classes were compiled with debugging info (i.e. javac -g )

Using Embedded Derby in Java 9 with Gradle

  1. Add the following dependencies to your build.gradle file:
    compile group: 'org.apache.derby', name: 'derby', version: '10.15.1.3'
    compile group: 'org.apache.derby', name: 'derbyshared', version: '10.15.1.3'
  2. Add the following entries to your module-info.java file:
    requires org.apache.derby.engine;
    requires org.apache.derby.commons;
    requires java.sql;
    
  3. In your Java class, you can create a connection like the following:
    final String DATABASE_NAME = "sample_table";
    String connectionURL = String.format("jdbc:derby:%s;create=true", DATABASE_NAME);
    connection = DriverManager.getConnection(connectionURL);
    
  4. Do your needed database operations with the connection (e.g. create table, execute a query, or call a stored procedure.).
  5. When your done using the connection, close the connection and shutdown the Derby engine like the following:
    connection.close();
    
    boolean gotSQLExc = false;
    try {
        //shutdown all databases and the Derby engine
        DriverManager.getConnection("jdbc:derby:;shutdown=true");
    } catch (SQLException se)  {
        if ( se.getSQLState().equals("XJ015") ) {
            gotSQLExc = true;
        }
    }
    if (!gotSQLExc) {
        System.out.println("Database did not shut down normally");
    }

    A clean shutdown always throws SQL exception XJ015, which can be ignored.

« Older posts