Java - Interview Questions and Answers on Utility Classes

Q1.  What is the difference between comparable and comparator in java.util pkg?

Ans. Comparable interface is used for single sequence sorting i.e.sorting the objects based on single data member where as comparator interface is used to sort the object based on multiple data members.

Q2.  What is the Locale class?

Ans. The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region

Q3.  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().

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

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

Q5.  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.

Q6.  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.

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

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

Q8.  Which of the following is not a valid java.util.Locale initialization ?

a. new Locale ()
b. new Locale ( String language )
c. new Locale ( String language , String country )

Ans. a i.e new Locale()

Q9.  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

Q10.  What's wrong with this code ?

public static void main(String[] args) { 
       String regex = "(\\w+)*"; 
       String s = "Java is a programming language."; 
       
       Pattern pattern = Pattern.compile(regex); 
       Matcher matcher = pattern.matcher(s); 
       while (matcher.next()) { 
          System.out.println("The e-mail id is: " + matcher.group()); 
       }
}

Ans. matcher.find() should have been used instead of matcher.next() within while.

Q11.  Which methods of the Pattern class have equivalent methods in the String class? 

Ans. split() and macthes()