Basic Operators in Java

This article covers basic operators of Java syntax, and how they function. By thorough discussion and coding examples, you’ll be able to use basic operators in your programs like a pro.

What are basic operators?

Java provides different sets of operators to perform simple computations like addition/ subtraction and other advanced operators for decision making or individual bitwise calculations.

Here are some major categories of operators

  • Arithmetic Operators (+, -, *, /)
  • Relational Operators (==, !=)
  • Logical Operators (&&, ||)
  • Assignment Operators (=, +=, -=)
  • Unary Operators (pre/post-fix)
  • Shift Operators (>>, << )
  • Bitwise Operators (&, |, ^)
  • Ternary/Conditional Operator (?:)
  • Misc Operators

The scope of this article encompass arithmetic, relational and logical operators only.

Arithmetic Operators

You can use basic arithmetic operators to perform a mathematical calculation and impact the value of any variable. Let’s see how it works in Java.

package com.basicoperators.core;

public class ArithmeticOperators {
    public static void main(String[] args) {
        // Addition 
        int apples = 5;
        int oranges = 7;
        int totalFruits = apples + oranges;

        System.out.println("\n-------------Addition---------------- " );
        System.out.println("Apples: " + apples);
        System.out.println("Oranges: " + oranges);
        System.out.println("Total Fruits: " + totalFruits);

        // Subtraction      
        int totalBananas = 24;
        int bananasSold = 12;
        int bananasLeft = totalBananas - bananasSold;

        System.out.println("\n----------------Subtraction--------------- " );
        System.out.println("Total Bananas: " + totalBananas);
        System.out.println("Bananas Sold: " + bananasSold);
        System.out.println("Bananas Left: " + bananasLeft);

        // Multiplication   
        int weeks = 3;
        int daysInAWeek = 7;
        int totalNumberOfDays = weeks * daysInAWeek;

        System.out.println("\n--------------Multiplication-------------- " );
        System.out.println("Days In A Week: " + daysInAWeek);
        System.out.println("Days In A Week: " + daysInAWeek);
        System.out.println("Total Number Of Days: " + totalNumberOfDays);

        // Division
        int totalMinutesConsumed = 420;
        int minutesInOneHour = 60;
        int numOfHours = totalMinutesConsumed / minutesInOneHour;

        System.out.println("\n----------------Division---------------- " );

        System.out.println("Total Minutes: " + totalMinutesConsumed);
        System.out.println("Minutes In One Hour: " + minutesInOneHour);
        System.out.println("Num Of Hours: " + numOfHours);    
    }
}

Output

----------------------Addition---------------------- 
Apples: 5
Oranges: 7
Total Fruits: 12

---------------------Subtraction--------------------- 
Total Bananas: 24
Bananas Sold: 12
Bananas Left: 12

--------------------Multiplication------------------- 
Days In A Week: 7
Days In A Week: 7
Total Number Of Days: 21

----------------------Division---------------------- 
Total Minutes Consumed: 420
Minutes In One Hour: 60
Num Of Hours: 7

Relational Operators

As the name implies, relational operators define the relationship of one instance with another. This means you can compare two numbers and see what relationship do they share. If they are equal to each other, one is greater than or smaller than the other number. Like 2 is less than 3. According to Java syntax, both instances should be of the same data type. For example, you can not compare if an integer is less than a string. Here is a small snippet explaining how you can use basic relational operators in Java.

package com.basicoperators.core;

public class RelationalOperators {
    public static void main(String[] args) {
        int even = 2;
        int odd = 3;

        System.out.println("Even = " + even);
        System.out.println("Odd = " + odd);

        // prints if even is equal to odd
        boolean check = even == odd;
        System.out.println("Is Even equal to Odd? " + check);

        // prints if even is not equal to odd
        check = even != odd;
        System.out.println("Is Even not equal to Odd? " + check);

        // prints if even is greater than odd
        check = even > odd;
        System.out.println("Is Even greater than Odd? " + check);

        // prints if even is less than odd
        check = even < odd;
        System.out.println("Is Even less than Odd? " + check);

        // prints if even is greater than equal to odd
        check = even >= odd;
        System.out.println("Is Even greater than equal to Odd? " + check);

        // prints if even is less than equal to odd
        check = even <= odd;
        System.out.println("Is Even less than equal to Odd? " + check);
    }
}

Output

Even = 2
Odd = 3
Is Even equal to Odd? false
Is Even not equal to Odd? true
Is Even greater than Odd? false
Is Even less than Odd? true
Is Even greater than equal to Odd? false
Is Even less than equal to Odd? true

Logical Operators

Logical Operators in Java are used for decision making. They allow the programmer to test if the combination of given expressions are true or false. Based on the result of your expression, you can make a decision.

  • AND – returns “true” only if both expressions are true
  • OR – returns “true” if any of the given expressions is true
  • NOT – returns the “inverse” of any given boolean expression

For your better understanding, let’s look at the following snippet.

package com.basicoperators.core;

public class LogicalOperators {
    public static void main(String[] args) {
        String myPet1 = "doggo";
        String myPet2 = "kitty";

        System.out.println("Pet1: " + myPet1);
        System.out.println("Pet2: " + myPet2);

        // implements AND
        boolean check = myPet1.equals("doggo") && myPet2.equals("kitty");
        // returns true only when both conditions are true
        System.out.println("Does my first pet name \"doggo\", and second one \"kitty\"? " + check);

        check = myPet1.equals("dog") && myPet2.equals("kitty");
        // returns "false" even if single condition is false 
        // remember these conditions are case sensitive
        System.out.println("Does my first pet name \"dog\", and second one \"kitty\"? " + check);

        // implements OR
        check = myPet1.equals("doggo") || myPet2.equals("lion");
        // returns "true" even when single condition is true
        System.out.println("Does any of my pet name \"doggo\"? " + check);

        check = myPet1.equals("cat") || myPet2.equals("tiger");
        // returns "false" because both conditions are false
        System.out.println("Does any of my pet name \"tiger\"? " + check);

        // implements NOT
        check = !(myPet1.equals("bingo") && myPet2.equals("kate"));
        // returns "true" when both conditions are true (inverse of statement)
        System.out.println("Does my first pet name \"bingo\", and second one \"kate\"? " + check);

        check = !(myPet1.equals("doggo") && myPet2.equals("kitty"));
        // returns "false" because both conditions are true
        System.out.println("Does my first pet name \"doggo\", and second one \"kitty\"? " + check);
    }
}

Output

Pet1: doggo
Pet2: kitty
Does my first pet name "doggo", and second one "kitty"? true
Does my first pet name "dog", and second one "kitty"? false
Does any of my pet name "doggo"? true
Does any of my pet name "tiger"? false
Does my first pet name "bingo", and second one "kate"? true
Does my first pet name "doggo", and second one "kitty"? false

Conclusion

The basic operators in Java are pretty simple to learn and easy to use. You might get overwhelmed by studying the different operators all at once. However, we recommend you practicing one set at a time. This way, you’ll master all of them soon. As always, you’re welcome to plug-in in case of any confusion. Happy learning!

How do I create a generic class in Java?

In this example you will learn how to create a generic class in Java. In some of the previous post in this blog you might have read how to use generic for working with Java collection API such as List, Set and Map. Now it is time to learn to create a simple generic class.

As an example in this post will create a class called GenericMachine and we can plug different type of engine into this machine that will be use by the machine to operate. For this demo we will create two engine type, a DieselEngine and a JetEngine. So let’s see how the classes are implemented in generic.

package org.kodejava.examples.generic;

public class GenericMachine<T> {
    private T engine;

    public GenericMachine(T engine) {
        this.engine = engine;
    }

    private void start() {
        System.out.println("This machine running on: " + engine);
    }

    public static void main(String[] args) {
        //
        // Creates a generic machine with diesel engine.
        //
        GenericMachine<DieselEngine> machine = new GenericMachine<>(new DieselEngine());
        machine.start();

        //
        // Creates another generic machine with jet engine.
        //
        GenericMachine<JetEngine> anotherMachine = new GenericMachine<>(new JetEngine());
        anotherMachine.start();
    }
}

Now, for the two engine class we will only create an empty class so that the GenericMachine class can be compile successfully. And here are the engine classes:

package org.kodejava.examples.generic;

public class DieselEngine {
}
package org.kodejava.examples.generic;

public class JetEngine {
}

The <T> in the class declaration tell that we want the GenericMachine class to have type parameter. We also use the T type parameter at the class constructor to pass the engine.

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