×

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to the development of another method.

Let us first understand the sense of the static keyword.

The static keyword in Java is primarily used for the management of memory. The static keyword in Java is taken into account to share the identical variable or method of a given class. The static keywords can be used along with variables, methods, blocks, and nested classes. The static keyword fits in to the class more than an instance of the class. The static keyword is taken into account for a constant variable or a method that is similar for every instance of a class.

Let us first know the meaning of static value.

A static value is a value that depends on which constructor is to be used. The most elementary one is Date first date= new Date();. 

In addition to this basic constructor, other constructors can be used too to provide a long for the time or a string such as – ‘2022-11-26 23:05:00’, ‘2021-10-2103:10:00’.

To be able to use the date, one must take classes in java.time package into its account, otherwise the date is of no use.

There exists a public static util method that can analyse a string and a Date object is returned, but also a Parse Exception is thrown in case the parsed string cannot be transformed into a Date object.

Now, in the following class, a static final Date is being initialized to a value using the util method described already. Since the util method throws Parse Exception, so this is not allowed. The following example throws a parse exception so, it is not allowed in java.

Example 1:

public static final DATE_1 = Util.getDateFromString('30000201');

Example 2:

public static final DATE_2 = Util.getDateFromString('22000104');

Example 3:

public static final DATE_3 = Util.getDateFromString('22000107');

The solution to the above issue is to take the static initializer block into account.

Method 1: static initialize block

public static final Date DATE_1;
static {
    try {
       DATE_1 = Util.getDateFromString("21000201");
    } catch (ParseException e) {
This is the space where the user can do anything such as – throwing an   unchecked exception or using a fallback value, it is to be noted there should only be one assignment to the final value
    }
}


Method 2: Another way to use an anonymous class, with an instance block

public static final Date DATE_1 = new Date() {{
    try {
        setTime(Util.getDateFromString("21000201").getTime());
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}};


Method 3: Overriding the setter methods

public static final Date DATE_1 = new Date() {{
        try {
            super.setTime(Util.getDateFromString("21000201").getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }


    @Override public void setYr(int yr) { throw new UnsupportedOperationException();}
    @Override public void setMnth(int mnt) {throw new UnsupportedOperationException();}
    @Override public void setDte(int dte) {throw new UnsupportedOperationException();}
    @Override public void setHrs(int hrs) {throw new UnsupportedOperationException();}
    @Override public void setMin(int min) {throw new UnsupportedOperationException();}
    @Override public void setSec(int sec) {throw new UnsupportedOperationException();}
    @Override public void setTme(long tme) {throw new UnsupportedOperationException();}
};


Method 4: The Creation of another method, either locally or in Util, that envelops the ParseException in an unconstrained exception, in the following way:

public static final Date DATE_1 = getDateFromString("21000201");


private static Date getDateFromString(String dateStrg) {
    try {
        return Util.getDateFromString(dateStrg);
    catch(ParseException e) {
        throw new IllegalArgumentException(e);
    }
}

Summary:

In this tutorial, we understood the meaning of static keywords and static values. We saw certain examples to understand the topic better. Further, we saw four different methods to assign static values to date.


Related Topics

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.