Java - Utility Classes - Interview Questions and Answers on Date

Q1.  Will this code Work ? If not , Why ?

java.util.Calendar c = new java.util.Calendar();

Ans. No. It gives the error "Cannot Instantiate the type Calendar". Calendar is an abstract class and hence Calendar object should be instantiated using Calendar.getInstance().

Q2.  Is java.util.Date an abstract Class ? Is java.util.Calendar an abstract Class ?

Ans. Date is not a abstract class whereas Calendar is.

Q3.  What will the following code print ?

java.util.Calendar c = java.util.Calendar.getInstance();
c.add(Calendar.MONTH, 5);
System.out.println(c.getTime());

Ans. Date and Time after 5 months from now.

Q4.  Which of the following code is correct ?

a. DateFormat df = DateFormat.getInstance();
b. DateFormat df = DateFormat.getDateInstance();
c. DateFormat df = DateFormat.getInstance(DateFormat.FULL);
d. DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);

Ans. All except c are correct.

Q5.  What is the use of parse method in DateFormat ?

Ans. It is used to parse String to get the Date Object with initialized date.

Q6.  Which of the following code is correct ?

a. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).parse(str); 

b. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).format(str); 

c. Date date = DateFormat.getDateInstance(DateFormat.LONG, Locale.US).parse(str);

Ans. c