Top 10 Java Date, Time and Calendar Interview Questions Answers

The Date and Time API is very important one for day to day Java development work but many interviewers don't ask enough questions on this topic. Most of the questions are based on either Java Collection framework e.g. HashMap, ConcurrentHashMap or ArrayList, or on multi-threading concepts e.g. volatile, synchronized and atomic variables. This is not good and I think many interviewers have realized that a good understanding of date and time API is also important for a good Java developer. That's the main reason of increasing number of date, time and calendar based Java interview questions in recent time, particularly in 2017.

Since Java development job market is very good at this moment and there are a lot of jobs open, particularly in investment banking domain in Asia Pacific, its probably the best time to change your job, especially if you are stuck with no learning, no salary increment and not a significant bonus or incentives in last a couple of years.

Apart from stability, growth is very important because if you don't move forward you will be stuck and eventually move backward, hence changing job is as important as sticking to a job which is working for you.

Top 10 Date, Time and Calendar Interview Questions and Answers

I have been sharing interview questions on various Java topics from last a couple of years e.g. multithreading, collections, design patterns etc, but one topic which I haven't touched yet was date and time and that's why I thought to share some of the interesting date and time-based questions from recent Java interviews. In this article, you will find those.

Does SimpleDateFormat be safe to use in the multithreaded program? (answer)
No, unfortunately, DateFormat and all its implementations including SimpleDateFormat is not thread-safe, hence, should not be used in the multi-threaded program until external thread-safety measures are applied e.g. confining SimpleDateFormat object into a ThreadLocal variable. If you don't do that, you will get an incorrect result while parsing or formatting dates in Java. Though, for all practical date time purpose, I highly recommend joda-time library.

How do you format a date in Java? e.g. in the ddMMyyyy format? (answer)
You can either use SimpleDateFormat class or joda-time library to format the date in Java. DateFormat class allows you to format date on many popular formats. Please see the answer for code samples to format the date into different formats e.g. dd-MM-yyyy or ddMMyyyy.

Can you tell some difference between old and new Date Time API of Java 8?
Even though new Date and Time API are a completely new API, you can deduce following difference between them:
1) In old API, Date was mutable but in Java 8 all date and time classes e.g. LocalDate, LocalTime or LocalDateTime are Immutable.
2) In old API, SimpleDateFormat was not thread-safe, but in Java 8 Formatter are thread-safe.
3) In old Date and Calendar API, Year starts with 1900, Months starts with 0, which is corrected in Java 8, here numbers make more sense.
4) Old Date and Calendar API has just one class Date to represent date and time, but Java 8 has separated classes for Date and Time e.g. LocalDate and LocalTime

Which date the following Date instance represent?
Date aDate = new Date(2015, 12, 25, 20, 40);

This is a really tricky question for any casual Java developers who have not written date and time-based code for himself because this will not represent the Christmas day or 25th December 2015. This code has got two bugs, first, the year starts from 1900 to, to represent 2015, you need to pass 115 i.e. 2015-1900. The second issue with this code is that month is not correct. The month starts from 0, so December would 11 not 12, interesting right? That's why you should new Date and Time API from Java 8, which solves all these issues.

Does Date class be Immutable in Java?
No, Date is not immutable. You can change it's internal to represent a different date. This is the reason that when you have a member represent Date, you must be careful not to leak its reference outside using getDate() method, because then the client can modify the state of the Immutable object, instead a copy should be returned to the client as suggested in Effective Java.

How do you copy a Date in Java? (answer)
It's a simple question to answer. The Date class implements the clone() method, so just call date.clone() to create a copy of the Date object in Java.

What is the relationship between java.sql.Date and java.util.Date? (answer)
This is one of the very interesting questions as not many developers know this fine but obvious detail. The java.sql.Date extends java.util.Date and suppress all time-related methods to act as just a date class. This is in direct violation of Liskov substitution principle.

Can you format Calendar in Java?
No, Calendar cannot be formatted in Java. You can only format dates.

How do you convert a Calendar to Date and vice-versa?
Well, you can use the Calendar.setTime() and Calendar.getTime() method to convert the Calendar to Date and vice-versa.

What is the equivalent of Date class in Java 8?
The Instance class is equivalent of java.util.Date in Java 8 because it also represents a millisecond value or an instance in timescale. Java 8 has also added conversion method e.g. toInstant() and fromDate() to convert instance to java.util.Date and vice-versa. See Java SE 8 for Really Impatient By Cay S. Horstmann for more details.

Top 10 Java Date, Time and Calendar Interview Questions Answers

How do you convert a millisecond to Date in Java? (answer)
One of the simplest question to answer, you can call the getTime() method which returns the millisecond from the Epoch.

How do you get month and year from a Date object in Java? (answer)
You can convert a Date to Calendar and then use its get() method with various fields to get the month, year, day of week and other date particulars e.g.

int day = calendar.get(Calendar.DATE); // returns the day
int month = calendar.get(Calendar.MONTH) + 1; // month starts from 0
int year = calendar.get(Calendar.YEAR) + 1900; // year starts from 1900

How do you convert XMLGregorianCalendar to Date in Java? (answer)
I have discussed this problem before, please check the link for the detailed answer.

How do you get the current time in GMT in Java? (answer)
The Java date is independent of time and display time in a current time zone only if you print them. So, in order to convert the current time in GMT, you need to use Calendar with time zone as shown in the given answer.

How do you add and subtract a day, month and year in a Date object? (answer)
This is one of the common day to day task of a Java developer, you can use the code shared in the answer for adding or subtracting a day or month from the Date object.

How do you compare two dates in Java to check if they are equal? (answer)
This is one of the easier questions you will see in terms of skill checking on Date classes. The java.util.Date class implements the equals() method, which returns true if both Dates is same and false otherwise.

How do you find if one date comes before or after another date in Java? (answer)
This is the follow-up question of the previous question. Interviewer further checks candidate's date comparison skill by asking this question. The answer is simple, the java.util.Date class provides before() and after() method which returns true and false if the date on which method is called comes before or after the other date passed as a method argument.

How do you convert java.util.Date to java.sql.Date in Java JDBC? (answer)
It's the follow-up question of 6th question. Since java.sql.Date is a subclass of java.util.Date you can simply get the time in millisecond and passed it to SQL date as shown below:

Date now = new Date();
java.sql.Date sqlDate = new java.sql.Date(now.getTime());

Simple and easy right? but there are some interesting follow-up questions when you write this code, I suggest you check the answer link for more detailed discussion, where I have answered those follow-up questions as well.

How to convert local time to GMT in Java? (answer)
This is similar to one of the previous questions where we need to get the current time in GMT

How do you show timezone in formatted date in Java? (answer)
see the answer link for a code example

The difference between java.util.Date and java.sql.Date in Java? (answer)
There are many difference between them but the most important one is that java.sql.Date is from JDBC package and it acts as converted between Date and Time data types in database and Date in Java.

How do you calculate the difference between two dates in Java? (program)
There are multiple ways to calculate the difference between two dates in Java e.g. you can get the long millisecond values from two dates and get the difference but that's not very valuable, you mostly need the difference in days or hours etc. See the program to learn more about those differences.

How do you convert a String(YYYYMMDD) to date in Java? (answer)
You can use SimpleDateFormat prior to JDK 8 and DateTimeFormatter along with format and parse method to convert a String to date in Java.

That's all about the date, time, and Calendar based Java Interview Questions. It's very important for a Java developer to have a solid understanding of Date and Time API of Java, both old and new because you will not find Java 8 in every project you work. You still need to

Other Java Interview Questions Articles.
Top 10 Spring Framework Interview Questions with Answers (see here)
15 Data Structure and Algorithm Questions from Java Interviews (read here)
20 Great Java Design Pattern Questions asked on Interviews (see here)
10 frequently asked Servlet Interview Questions with Answers (see here)
Top 10 JSP Questions  from J2EE Interviews (read here)
12 Good RESTful Web Services Questions from Interviews (read here)
10 Great Hibernate Interview Questions for Java EE Developer (see here)
10 Great JDBC Interview Questions for Java Programmers (questions)
15 Java NIO and Networking Interview Questions with Answers (see here)
Top 10 Trick Java Interview Questions and Answers (see here)
Top 40 Core Java Phone Interview Questions with answers (list)

Thanks for reading this article so far. If you like these questions then please share with your friends and colleagues too.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

No comments:

Post a Comment