×

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.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Tower of Hanoi Program in Java

Tower of Hanoi Program in Java The Tower of Hanoi program in Java is written to solve a mathematical puzzle, called Tower of Hanoi, where we have three poles and n...

4 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.