What Makes Java 14 Special?

Java 14 has finally been released in March 2020 and brings a whole host of new features that will help ease coding frustrations.

In this article, we will break down the top 6 features that make Java 14 an outstanding update compared to the previous versions. Here we go:

1. Switch Expressions

Although Switch Expressions was just a preview feature over the previous two versions, it has now been given permanent status in version 14.

The lambda syntax was introduced for switch expressions in Java 12 and this means that multiple case labels for pattern matching could be produced. This also stopped any fall-through that led to verbose code and enforced exhaustive cases that would issue a compilation error if all input cases weren’t entered.

In the previous versions yield statements were introduced to replace a break for returning values from an expression. Within Java 14, all these features are included as standard now. We should also point out that yield is not a new keyword for Java and is just used within switch expressions.

2. Previewing Text Blocks

Another former preview item, Text Blocks were first added into Java 13 with the intention to make multiline string literals much easier to create. In particular, HTML, JSON and SWL query strings became much easier as a result.

“Text blocks do remain a preview within Java 14, but they have some interesting new additions,” says Robert Class, a journalist at NextCoursework and Australia2Write. “In particular, you can now use a backslash to display smart multiline string blocks.”

The code \s can build trailing spaces that are ignored by the compiler as a default. This then preserves all of the spaces that are included before it.

3. Pattern Matching for instanceof

Most codebase creations by Java developers will include a strong use of instanceof conditions filtered in throughout the code. Generally speaking, the instanceof conditional check normally comes before an explicit typecast.

Within the Java 14, developers will be happy to know that this has been removed to make conditional extraction a lot clearer. The scope of this variable is currently limited to just the conditional block.

4. Useful NullPointerExceptions

Most developers will tell you that the null pointer exceptions have been a complete nightmare in previous versions of Java. The infamous NPEs can be exceedingly difficult to debug.

This invariably led to developers falling back on other debugging tools or trying to manually figure the variable/method that was null because the stack trace shows only the line number.

“In Java 14, we also see the introduction of a brand new JVM feature, which has enhanced insights with a descriptive stack,” suggests Anita Lockfield, a tech writer at Britstudent and Write My X. “This is not a language feature, but a development of the runtime environment.”

5. Previewing Records

Within Java, you can build classes to hold data and utilize encapsulation to control the way that the data is accessed and modified. It is an object-oriented language.

Because it uses objects, this makes manipulating complicated data types easy and straightforward. This is one of the things that makes Java popular as a platform. The problem has been that the creation of data types has been verbose in old versions and it needs a lot of code for even the simplest case.

Within Java 14, they have introduced records as a brand-new preview feature. This new concept helps developers to include a new language feature without having to make it part of the Java standard. This means that developers can test features and provide feedback that leads to changes before those features become standard.

If you want to use the preview feature, you need to specify the command line flag, --enable-preview for the compilation and runtime. For compilation, you must also specify the sourceflag. The record becomes a much simpler way of showing a data class.

6. New APIs

There are three new APIs within Java 14 that we love. The first is java.io which contains a new annotation type called Serial. This was designed to be used with compiler checks on Serializations. This means that annotations of this type can be applied to serialization related methods and with the fields in any classes declared to be Serializable.

The second API that we enjoyed is java.lang. This class has two distinct methods for the new Record feature, including isRecord() and getRecordComponents(). These have a range of RecordComponent objects and gives up to eleven ways to retrieve things, like the details of annotations and the generic type.

Finally, the new java.util.concurrent.locks API has one new method called setCurrentBlocker. This provides an ability to unpark and park a thread. This helps avoid the same problems that previous versions have had with the Thread.suspend and Thread.resume methods. You can also set the Object that will be returned by getBlocker with this new API, which can help when recalling the no-argument park method from a non-public object.

Top 10 Best Apps for Programmers 2020

When it comes to using programming languages, coders can make an easy choice. Python is the fastest growing language, but JavaScript is still the most popular one. A great programmer knows what language to focus on, depending on the projects they develop.

But what about other programming tools?

The language is not the only thing that you need to choose. There are too many software developing tools, so you might get confused comparing all their features. First and foremost, you need a code editor. But you also need apps that help you focus and fight procrastination. Let’s not forget collaboration in real time, which is an essential need of modern programming teams.

We have a list for you. It combines various tools that cover different aspects of a programmer’s work. We’ll list the best apps for developers at the moment.

Top 10 Apps for Developers

1. CodeRunner

A successful programming process starts with the choice of an editor. It has to be fast, and it should support multiple languages.

CodeRunner meets those standards. It’s a lightweight Mac app that supports 25+ languages, and lets you do your work in the fastest way possible. Its bracket management, auto-indenting, and code completion features are outstanding.

2. Todo.txt

Your list of programming tools needs an app that lets you plan tasks and update them as you go through the daily schedule.

Todo.txt is a simplistic app, without too many options, reminders, drop-downs, and additional features that aren’t necessary when you want to create a straightforward list of tasks. You’ll interact with it right from the command line. This may not be what a usual to-do app user would like, but it’s definitely something a programmer appreciates.

3. Marked

If you use Markdown for easy formatting, you need apps for programmers that let you see the styled version before its publication. Marked gives you that option.

In addition to the preview feature, it also gives you tools for simplifying your style, checking the grammar and spelling, lightening the word count, and achieving an optimal reading time for the visitor.

4. Appian

This list of apps for developers wouldn’t be complete without Appian – a tool that lets you develop perfect mobile apps. It makes app development as easy as it gets. According to the provider’s estimations it takes eight weeks from the idea development to the app’s completion with the use of this low-code tool.

Appian lets you achieve greater speed by automating processes and combining data from multiple sources.

5. Unity

This is one of the best 3D software developing tools on the market. It’s perfect for creating games, architecture and engineering projects, automotive models, and more.

Unity offers a great user manual, which the most popular apps for programmers often skip. With these complete lessons, you’ll easily learn how to use the tool to its full potential.

6. MusicForProgramming

A music platform is not the first idea that comes to mind when you search for the best apps for developers. However, MusicForProgramming is one of those essential tools that help you work in a focused environment.

Currently there are 59 playlists that are specifically designed as the perfect background to a coder’s working process.

It’s much better than creating your own playlists on YouTube. Let’s be honest: it would take a lot of time for you to create 59 different playlists. Plus, when you choose your own music, you’re too attached to some pieces, which can make you distracted.

7. RescueTime

Is there a programmer who has never burned out? It’s a common situation, which leads to procrastination, dissatisfaction, and more procrastination. RescueTime can prevent the delays that you make when you feel unmotivated to work. It records how much time you spend on different apps and sites.

The reality hit will be enough for you to get back to work… seriously.

8. iTerm2

Your Mac’s Terminal is one of the essential programming tools that you use. But do you feel like it’s stuck back in time? iTerm2 is a similar, but more advanced tool.

It lets you split a tab into multiple panes, so you’ll navigate through different sessions. It also has a convenient search feature, which will find parts of your code that you need to work on. It has an autocomplete function, mouseless copy feature, easily accessible paste history, and more.

9. Unicode Table

This is an outstanding searchable database for all the Unicode characters that you plan to use. It includes alphabets, math symbols, fancy letters, flowers, stars, emoji, hearts, and much more.

You will get Unicode, CSS, and HTML codes for each character that you plan to use.

10. Codeanywhere

Gone are the days when programming was considered to be solitary work. Nowadays, we all use collaborative apps for developers, which allow us to join forces and work on different parts of the code at the same time.

This is a simple code editor, which lets you work remotely from any location. You will connect with your team, and you’ll all make changes in the code in real time. The app manages to make that process NOT messy, since it easily lets you switch between versions and check out each change that was made.

Only Use the Apps That You Need

Since the choice of tools for programmers is so great, it’s easy to start using more apps than you need to.

You need only a few software developing tools and accompanying software to support your work. Anything beyond the essentials may clog up your work environment.

That’s why we listed tools in different categories. Even if you use all of them, they won’t collide with one another. Check them out, and use the ones that can help you enhance your workflow.

How do I convert java.util.TimeZone to java.time.ZoneId?

The following code snippet will show you how to convert the old java.util.TimeZone to java.time.ZoneId introduced in Java 8. In the first line of our main() method we get the default timezone using the TimeZone.getDefault() and convert it to ZoneId by calling the toZoneId() method. In the second example we create the TimeZone object by calling the getTimeZone() and pass the string of timezone id. To convert it to ZoneId we call the toZoneId() method.

package org.kodejava.example.datetime;

import java.time.ZoneId;
import java.util.TimeZone;

public class TimeZoneToZoneId {
    public static void main(String[] args) {
        ZoneId zoneId = TimeZone.getDefault().toZoneId();
        System.out.println("zoneId = " + zoneId);

        TimeZone timeZoneUsPacific = TimeZone.getTimeZone("US/Pacific");
        ZoneId zoneIdUsPacific = timeZoneUsPacific.toZoneId();
        System.out.println("zoneIdUsPacific = " + zoneIdUsPacific);
    }
}

This snippet prints the following output:

zoneId = Asia/Shanghai
zoneIdUsPacific = US/Pacific

To convert the other way around you can do it like the following code snippet. Below we convert the ZoneId to TimeZone by using the TimeZone.getTimeZone() method and pass the ZoneId.systemDefault() which return the system default timezone. Or we can create ZoneId using the ZoneId.of() method and specify the timezone id and then pass it to the getTimeZone() method of the TimeZone class.

package org.kodejava.example.datetime;

import java.time.ZoneId;
import java.util.TimeZone;

public class ZoneIdToTimeZone {
    public static void main(String[] args) {
        TimeZone timeZone = TimeZone.getTimeZone(ZoneId.systemDefault());
        System.out.println("timeZone = " + timeZone.getDisplayName());

        TimeZone timeZoneUsPacific = TimeZone.getTimeZone(ZoneId.of("US/Pacific"));
        System.out.println("timeZoneUsPacific = " + timeZoneUsPacific.getDisplayName());
    }
}

And here are the output of the code snippet above:

timeZone = China Standard Time
timeZoneUsPacific = Pacific Standard Time

How do I get a list of all TimeZones Ids using Java 8?

To retrieve a list of all available time zones ids we can call the java.time.ZoneId static method getAvailableZoneIds(). This method return a Set of string of all zone ids. The format of the zone id are “{area}/{city}”. You can use this ids of string to create the ZoneId object using the ZoneId.of() static method.

package org.kodejava.example.datetime;

import java.time.ZoneId;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Set;

public class GetAllTimeZoneIds {
    public static void main(String[] args) {
        Set<String> zoneIds = ZoneId.getAvailableZoneIds();
        for (String id : zoneIds) {
            ZoneId zoneId = ZoneId.of(id);
            System.out.println("id          = " + id);
            System.out.println("displayName = " + 
                zoneId.getDisplayName(TextStyle.FULL, Locale.US));
        }
    }
}

Here are some of zone IDs printed out to the console:

id          = Asia/Aden
displayName = Arabian Time
id          = America/Cuiaba
displayName = Amazon Time
id          = Etc/GMT+9
displayName = GMT-9:00
id          = Etc/GMT+8
displayName = GMT-8:00
id          = Africa/Nairobi
displayName = Eastern Africa Time
...
...
...
id          = Europe/Nicosia
displayName = Eastern European Time
id          = Pacific/Guadalcanal
displayName = Solomon Is. Time
id          = Europe/Athens
displayName = Eastern European Time
id          = US/Pacific
displayName = Pacific Time
id          = Europe/Monaco
displayName = Central European Time

How do I get HTTP headers using HttpClient HEAD request?

The HTTP HEAD method is used for reading the headers information of a resource returned when accessing it using the HTTP GET method. Such request can be done before deciding to download a large resource to save bandwidth. The response to a HEAD method should not have a body, in the code below we use the HttpResponse.BodyHandlers.discarding(), which is a response body handler that discards the the response body.

In the code snippet below we start by creating an instance of HttpClient, in this example we use the HttpClient.newBuilder().build() method. After creating the HttpClient we create the HttpRequest object. We set the HTTP method to HEAD by calling the method method() and pass a string “HEAD” as the method name and HttpRequest.BodyPublishers.noBody() a request body publisher which sends no request body.

The next step in the code below is to send the request and get the response headers from the HttpResponse object using the headers() method. The map() method of the HttpHeaders object give us a key-values of the headers returned by the server.

package org.kodejava.example.httpclient;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HeadRequestExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder().build();

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://google.com"))
            .method("HEAD", HttpRequest.BodyPublishers.noBody())
            .build();

        HttpResponse<Void> response = client.send(request,
            HttpResponse.BodyHandlers.discarding());

        // Returns an unmodifiable multi map view of this HttpHeaders.
        // The map contains key of string, with list of strings as
        // its value.
        HttpHeaders headers = response.headers();
        headers.map().forEach((key, values) ->
            System.out.printf("%s = %s%n", key, values));
    }
}

Here are the HTTP headers we got and printed out to the console screen:

:status = [301]
alt-svc = [quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,h3-T050=":443"; ma=2592000]
cache-control = [public, max-age=2592000]
content-length = [220]
content-type = [text/html; charset=UTF-8]
date = [Wed, 22 Apr 2020 14:41:49 GMT]
expires = [Fri, 22 May 2020 14:41:49 GMT]
location = [https://www.google.com/]
server = [gws]
x-frame-options = [SAMEORIGIN]
x-xss-protection = [0]

How do I read website content using HttpClient?

The HTTP Client API can be used to request HTTP resources over the network. This new API was introduced as a new API in Java 11. It supports HTTP/1.1 and HTTP/2 and also support both synchronous and asynchronous programming models. The code snippet below show you how to use the new API to read the content of a website page.

In the code below we start by creating a new instance of HttpClient using the newHttpClient() static method. This is equivalent to calling newBuilder().build(). This give us an instance of HttpClient with default settings like using the “GET” request method the as the default. Then we create an HttpRequest object using the newBuilder() method, set the request URI and call the build() method to build the HttpRequest object.

Next we send the request by calling the send() method of the HttpClient object. This will sends the given request, blocking if necessary to get the response. The returned HttpResponse object contains the response status, headers, and body as handled by given response body handler.

package org.kodejava.example.httpclient;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class ReadWebsiteContent {
    public static void main(String[] args) throws Exception {
        // Creates HttpClient object with default configuration.
        HttpClient httpClient = HttpClient.newHttpClient();

        // Creates HttpRequest object and set the URI to be requested, 
        // when not defined the default request method is the GET request.
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://httpie.org/hello"))
            .GET()
            .build();

        // Sends the request and print out the returned response.
        HttpResponse<String> response = httpClient.send(request,
            HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));

        System.out.println("Status Code: " + response.statusCode());
        System.out.println("Headers    : " + response.headers().toString());
        System.out.println("Body       : " + response.body());
    }
}

Here is the content of the website that we read using the code snippet above:

Status Code: 200
Headers    : java.net.http.HttpHeaders@2d299ad6 { {:status=[200], cf-cache-status=[DYNAMIC], cf-ray=[5875b78d5df2eb00-LAX], cf-request-id=[023d710c5b0000eb00b738f200000001], content-length=[116], content-type=[text/x-rst;charset=utf-8], date=[Tue, 21 Apr 2020 08:25:53 GMT], etag=["234b9a1fe19f125356a5396c8cc72d54493a2eef"], expect-ct=[max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"], server=[cloudflare], set-cookie=[__cfduid=d5bdb6d828be3bb85d0f1f4c2ff81041c1587457553; expires=Thu, 21-May-20 08:25:53 GMT; path=/; domain=.httpie.org; HttpOnly; SameSite=Lax]} }
Body       : 

Hello, World! 👋
~~~~~~~~~~~~~~~~

Thank you for trying out HTTPie 🥳

I hope this will become a friendship.

How do I modified the value of LocalDate and LocalTime object?

The easiest way to modify the value of a LocalDate, LocalTime or LocalDateTime object is to use the with() method of the corresponding object. These methods will return a modified version of the object, it doesn’t change the attribute of the original object. All the methods, like withYear(), withDayOfMonth() or the with(ChronoField) of the LocalDate object will return a new object with the modified attribute.

With the LocalTime object you can use the withHour(), withMinute(), withSecond() or the more generic with(ChronoField) method to modified the attribute of a LocalTime object. You can also modified a LocalDateTime object using these with() method. Let’s see the example in the code snippet below.

package org.kodejava.example.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;

public class ManipulatingDateTime {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2020, 4, 21);
        System.out.println("date1 = " + date1);
        LocalDate date2 = date1.withYear(2019);
        System.out.println("date2 = " + date2);
        LocalDate date3 = date2.withDayOfMonth(10);
        System.out.println("date3 = " + date3);
        LocalDate date4 = date3.with(ChronoField.MONTH_OF_YEAR, 12);
        System.out.println("date4 = " + date4);

        LocalTime time1 = LocalTime.of(1, 5, 10);
        System.out.println("time1 = " + time1);
        LocalTime time2 = time1.withHour(6);
        System.out.println("time2 = " + time2);
        LocalTime time3 = time2.withMinute(45);
        System.out.println("time3 = " + time3);
        LocalTime time4 = time3.with(ChronoField.SECOND_OF_MINUTE, 25);
        System.out.println("time4 = " + time4);

        LocalDate now1 = LocalDate.now();
        System.out.println("now1 = " + now1);
        LocalDate now2 = now1.plusWeeks(1);
        System.out.println("now2 = " + now2);
        LocalDate now3 = now2.minusMonths(2);
        System.out.println("now3 = " + now3);
        LocalDate now4 = now3.plus(15, ChronoUnit.DAYS);
        System.out.println("now4 = " + now4);
    }
}

The output of this code snippet are:

date1 = 2020-04-21
date2 = 2019-04-21
date3 = 2019-04-10
date4 = 2019-12-10
time1 = 01:05:10
time2 = 06:05:10
time3 = 06:45:10
time4 = 06:45:25
now1 = 2020-04-21
now2 = 2020-04-28
now3 = 2020-02-28
now4 = 2020-03-14

These with() methods is the counterpart of the get() methods. Where the get() methods will give you the value of the corresponding LocalDate or LocalTime attribute, the with() method will change the attribute value and return a new object. It didn’t call set because the object is immutable, which means it value cannot be changed.

While with the with() method you can change the value of date time attribute in an absolute way using the plus() or minus() method can help you change the date and time attribute in a relative way. The plus() and minus() method allows you to move a Temporal back or forward a give amount of time, defined by a number plus a TemporalUnit, in this case we use the ChronoUnit enumeration which implements this interface.

How do I created tab delimited data file in Java?

The following code snippet show you how to create a tab delimited data file in Java. The tab character is represented using the \t sequence of characters, a backslash (\) character followed by the t letter. In the code below we start by defining some data that we are going to write to the file.

We create a PrintWriter object, passes a BufferedWritter created using the Files.newBufferedWriter() method. The countries.dat is the file name where the data will be written. Because we are using the try-with-resources the PrintWriter and the related object will be closed automatically when the file operation finishes.

package org.kodejava.example.io;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class TabDelimitedDataFile {
    public static void main(String[] args) throws IOException {
        List<String[]> data = new ArrayList<>();
        data.add(new String[]{"Afghanistan", "AF", "AFG", "004", "Asia"});
        data.add(new String[]{"Åland Islands", "AX", "ALA", "248", "Europe"});
        data.add(new String[]{"Albania", "AL", "ALB", "008", "Europe"});
        data.add(new String[]{"Algeria", "DZ", "DZA", "012", "Africa"});
        data.add(new String[]{"American Samoa", "AS", "ASM", "016", "Polynesia"});
        data.add(new String[]{"Andorra", "AD", "AND", "020", "South Europe"});
        data.add(new String[]{"Angola", "AO", "AGO", "024", "Africa"});
        data.add(new String[]{"Anguilla", "AI", "AIA", "660", "Americas"});
        data.add(new String[]{"Antarctica", "AQ", "ATA", "010", ""});
        data.add(new String[]{"Argentina", "AR", "ARG", "032", "Americas"});

        try (PrintWriter writer = new PrintWriter(
            Files.newBufferedWriter(Paths.get("countries.dat")))) {
            for (String[] row : data) {
                writer.printf("%1$20s\t%2$3s\t\t%3$3s\t\t%4$3s\t\t%5$s",
                    row[0], row[1], row[2], row[3], row[4]);
                writer.println();
            }
        }
    }
}

The output of the code snippet above are:

         Afghanistan     AF     AFG     004     Asia
       Åland Islands     AX     ALA     248     Europe
             Albania     AL     ALB     008     Europe
             Algeria     DZ     DZA     012     Africa
      American Samoa     AS     ASM     016     Polynesia
             Andorra     AD     AND     020     South Europe
              Angola     AO     AGO     024     Africa
            Anguilla     AI     AIA     660     Americas
          Antarctica     AQ     ATA     010     
           Argentina     AR     ARG     032     Americas

How do I use TemporalField to access date time value?

The LocalDate and LocalTime are probably the first two classes from the Java 8 Date and Time API that you will work with. An instance of the LocalDate object is an immutable object representing a date without the time of the day and on the other way around the LocalTime object is an immutable object representing a time without the date information.

The LocalDate object have methods to get information related to date such as getYear(), getMonth(), getDayOfMonth(). While the LocalTime object have methods to get information related to time such as getHour(), getMinute(), getSecond(). Beside using those methods we can also access the value of these object using the TemporalField interface. We can pass a TemporalField to the get() method of LocalDate and LocalTime objects. TemporalField is an interface, one of its implementation that we can use to get the value is the ChronoField enumerations.

Let’s see some examples in the code snippet below:

package org.kodejava.example.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;

public class DateTimeValueTemporalField {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        System.out.println("Date = " + date);
        System.out.println("Year = " + date.getYear());
        System.out.println("Year = " + date.get(ChronoField.YEAR));

        System.out.println("Month= " + date.getMonth().getValue());
        System.out.println("Month= " + date.get(ChronoField.MONTH_OF_YEAR));

        System.out.println("Date = " + date.getDayOfMonth());
        System.out.println("Date = " + date.get(ChronoField.DAY_OF_MONTH));

        System.out.println("DOW  = " + date.getDayOfWeek().getValue());
        System.out.println("DOW  = " + date.get(ChronoField.DAY_OF_WEEK) + "\n");

        LocalTime time = LocalTime.now();
        System.out.println("Time  = " + time);
        System.out.println("Hour  = " + time.getHour());
        System.out.println("Hour  = " + time.get(ChronoField.HOUR_OF_DAY));

        System.out.println("Minute= " + time.getMinute());
        System.out.println("Minute= " + time.get(ChronoField.MINUTE_OF_HOUR));

        System.out.println("Second= " + time.getSecond());
        System.out.println("Second= " + time.get(ChronoField.SECOND_OF_MINUTE));

        System.out.println("Nano  = " + time.getNano());
        System.out.println("Nano  = " + time.get(ChronoField.NANO_OF_SECOND));
    }
}

The output of the code snippet above are:

Date = 2020-04-20
Year = 2020
Year = 2020
Month= 4
Month= 4
Date = 20
Date = 20
DOW  = 1
DOW  = 1

Time  = 16:06:11.389185
Hour  = 16
Hour  = 16
Minute= 6
Minute= 6
Second= 11
Second= 11
Nano  = 389185000
Nano  = 389185000

How do I get all Sundays of the year in Java?

You need the create a holiday calendar for your application. One of the functionality is to include all Sundays of the year as a holiday for your calendar. The following code snippet will show you how to get all Sundays of the given year. First we need to find the first Sunday of the year using the first 3 lines of code in the main() method. After getting the first Sunday we just need to loop to add 7 days using the Period.ofDays() to the current Sunday to get the next Sunday. We stop the loop when the year of the Sunday is different to the current year.

package org.kodejava.example.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

import static java.time.temporal.TemporalAdjusters.firstInMonth;

public class FindAllSundaysOfTheYear {
    public static void main(String[] args) {
        // Create a LocalDate object that represent the first day of the year.
        int year = 2020;
        LocalDate now = LocalDate.of(year, Month.JANUARY, 1);
        // Find the first Sunday of the year
        LocalDate sunday = now.with(firstInMonth(DayOfWeek.SUNDAY));

        do {
            // Loop to get every Sunday by adding Period.ofDays(7) the the current Sunday.
            System.out.println(sunday.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
            sunday = sunday.plus(Period.ofDays(7));
        } while (sunday.getYear() == year);
    }
}

The output of this code snippet are:

Sunday, January 5, 2020
Sunday, January 12, 2020
Sunday, January 19, 2020
Sunday, January 26, 2020
Sunday, February 2, 2020
Sunday, February 9, 2020
Sunday, February 16, 2020
Sunday, February 23, 2020
...
Sunday, December 6, 2020
Sunday, December 13, 2020
Sunday, December 20, 2020
Sunday, December 27, 2020