Java - Packages - Interview Questions and Answers on java.util package

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

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

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

Q5.  Name few Calendar related classes and Interfaces ?

Ans. http://www.buggybread.com/2015/02/java-util-calendar-classes-and.html

Q6.  Name few Locale classes and interfaces ?

Ans. http://www.buggybread.com/2015/01/java-locale-classes-and-interfaces.html

Q7.  Name few classes that are part of java.util package ? 

Ans. http://www.buggybread.com/2015/01/java-javautil-classes-and-interfaces.html

Q8.  Name few Java util classes that were introduced with Java 7 ?

Ans. http://www.buggybread.com/2015/01/migrating-to-java-7-new-classes_25.html

Q9.  Name few Java Util classes introduced with Java 8 ?

Ans. http://www.buggybread.com/2015/01/migrating-to-java-8-new-classes_25.html

Q10. What is the package name for  UIDefaults class?

Ans.java.util

Q11. Name few classes of package java.util?

Ans.[ SerialException,  SecureDirectoryStream<T>, ConcurrentModificationException,  SimpleBindings, CurrencyNameProvider, PreferencesFactory, ArrayList, IllegalFormatConversionException, ToLongFunction, TreeSet, Phaser, EnumMap, StringJoiner, DoubleUnaryOperator,  WeakHashMap, TimeZone, Arrays, ForkJoinPool, Set, Matcher, FormatterClosedException,  ConcurrentSkipListMap, IntSummaryStatistics, Pack200.Packer, LoggingPermission,  Collection<E>,  TreeSet,  PriorityBlockingQueue, InflaterOutputStream, Queue, Enumeration, RejectedExecutionHandler, Hashtable,  MessageContext, AbstractSet, ZipException, AtomicReference,  SyncProviderException, JarFile, CheckedInputStream, ScheduledFuture, AtomicLong, BiFunction, OptionalLong, IllegalFormatException,  CopyOnWriteArrayList, BiConsumer, LinkedHashSet,  ConcurrentLinkedDeque, Spliterator.OfInt, T_CONS, Spliterators.AbstractDoubleSpliterator, Comparator, Spliterator<T>, EmptyStackException, IllegalFormatPrecisionException,  SortedSet<E>,  LogicalMessageContext, List,  RenderingHints, Collections, ForkJoinPool.ForkJoinWorkerThreadFactory, HashSet, AbstractList, ScheduledExecutorService, Optional, Spliterators.AbstractLongSpliterator, InvalidPreferencesFormatException, PriorityQueue, LinkedList, ZipInputStream, Objects, CheckedOutputStream, AtomicMarkableReference, Scanner, NavigableSet,  HashSet,  Vector, CRC32, ReentrantReadWriteLock.ReadLock,  SQLDataException, ServiceConfigurationError, IntToDoubleFunction, MatchResult, ForkJoinPool.ManagedBlocker, TimerTask, FutureTask, InvalidPropertiesFormatException,  EnumMap, Spliterators.AbstractIntSpliterator, IllegalFormatFlagsException, Preferences,  Spliterators.AbstractIntSpliterator, Condition, PreferenceChangeEvent, JarException, LocaleNameProvider, BackingStoreException,  AuthProvider, Adler32,  LinkedHashSet, DoubleSupplier, ExecutorService, ThreadPoolExecutor, NoSuchElementException, ReentrantReadWriteLock.WriteLock, Map.Entry, TransferQueue,  SQLWarning, LinkedBlockingQueue, AbstractMap, ArrayBlockingQueue, Calendar.Builder,  ServiceLoader, BinaryOperator, Vector, CountedCompleter, ThreadPoolExecutor.AbortPolicy,  AbstractList,  TabularDataSupport, DoublePredicate, NavigableSet<E>, RecursiveAction, RandomAccess,  Stack, Stream.Builder, IntConsumer, IllegalFormatCodePointException, IntFunction, CompletionService,  PriorityQueue, StampedLock, Inflater,  SQLSyntaxErrorException, ConcurrentLinkedQueue, Map,  LinkedBlockingDeque, BiPredicate, ZipError, DoubleAccumulator,  Properties, StreamSupport, Bindings, Callable,  SQLIntegrityConstraintViolationException, CalendarNameProvider, TooManyListenersException, CompletableFuture, Executor, ForkJoinWorkerThread, Supplier, ExecutionException, ObjIntConsumer, NodeChangeListener, InflaterInputStream, SimpleFormatter,  LinkedBlockingQueue,  BlockingQueue<E>, Deque, Formattable, Lock, StringTokenizer, AtomicLongArray,  SQLTransactionRollbackException,  JobStateReasons, Locale, ThreadFactory, HashMap, XMLFormatter, MissingResourceException,  Path, AbstractSequentialList, AtomicIntegerFieldUpdater, Random, BlockingDeque,  Queue<E>,  SyncFactoryException,  ArrayDeque, LongPredicate,  BlockingDeque<E>,  SynchronousQueue, DoubleBinaryOperator, LoggingMXBean, CancellationException,  Spliterators.AbstractSpliterator, Collection, ToIntFunction, IllegalFormatWidthException, Dictionary, DuplicateFormatFlagsException, LinkedBlockingDeque, NavigableMap,  Spliterator.OfLong, Semaphore, ReentrantReadWriteLock, GZIPInputStream, Function,  Deque<E>,  ConcurrentLinkedQueue, LogRecord, ResourceBundleControlProvider, ObjLongConsumer,  HashMap, ToDoubleFunction, AtomicIntegerArray,  IdentityHashMap, PrimitiveIterator, TimeZoneNameProvider,  LinkedList, ToDoubleBiFunction, CountDownLatch, Manifest, ConcurrentLinkedDeque,  AttributeList,  DelayQueue, Locale.Category, LockSupport,  ArrayList,  List<E>, UnknownFormatFlagsException,  Attributes, ScheduledThreadPoolExecutor, Consumer, ToIntBiFunction, AtomicReferenceArray, LongToIntFunction, Currency, TimeUnit,  SQLNonTransientException, RunnableFuture, BlockingQueue, AbstractMap.SimpleImmutableEntry, ThreadPoolExecutor.CallerRunsPolicy, GregorianCalendar, IllformedLocaleException, LongStream, IntStream.Builder, AtomicBoolean, AtomicInteger, SortedMap, LongStream.Builder, WeakHashMap,  PrinterStateReasons,  SQLClientInfoException, AbstractCollection, Logger, LinkedTransferQueue, AbstractQueue, Observer, CompletableFuture.AsynchronousCompletionTask, PreferenceChangeListener, ConcurrentHashMap, BooleanSupplier,  Set<E>, ConcurrentNavigableMap, Base64.Encoder, LongBinaryOperator, Spliterator.OfLong, Calendar,  SQLNonTransientConnectionException, OptionalInt, Attributes.Name, DoubleSummaryStatistics, Observable, DoubleConsumer, ZipFile, CompletionException,  SortedMap<K, Locale.Builder, Base64.Decoder, ToLongBiFunction,  AbstractSet,  SQLException, Exchanger, DelayQueue, ConcurrentHashMap.KeySetView, Predicate,  LinkedTransferQueue,  ConcurrentMap<K, ReadWriteLock, StreamHandler, Collectors, BitSet, V>,  BeanContextServicesSupport, ThreadPoolExecutor.DiscardPolicy, PrimitiveIterator.OfDouble, AtomicReferenceFieldUpdater, CyclicBarrier, Stack, PrimitiveIterator.OfLong, EventListenerProxy, LongAdder,  AbstractQueue, ResourceBundle, AbstractExecutorService, CopyOnWriteArrayList, Collector.Characteristics, ErrorManager, IntSupplier, Locale.LanguageRange,  ArrayBlockingQueue, AtomicStampedReference, ExecutorCompletionService, MemoryHandler, Properties, Locale.FilteringMode, Spliterator.OfPrimitive, DoubleAdder, AbstractQueuedLongSynchronizer, Iterator, DeflaterOutputStream, ThreadLocalRandom,  SQLTransientConnectionException,  Spliterator.OfInt, Spliterators.AbstractSpliterator, NodeChangeEvent, Delayed, ConcurrentSkipListMap, JarInputStream,  Spliterator.OfPrimitive<T, IntPredicate, FormatFlagsConversionMismatchException, ArrayDeque, Spliterator.OfDouble,  RoleUnresolvedList,  RoleList, Filter, IntBinaryOperator, DoubleStream, IntStream, AbstractMap.SimpleEntry,  SQLTransientException, DoubleToIntFunction, SocketHandler, DeflaterInputStream,  RowSetWarning, PropertyResourceBundle, ObjDoubleConsumer, AtomicLongFieldUpdater, RunnableScheduledFuture, Deflater, Checksum, MissingFormatArgumentException,  BatchUpdateException, ReentrantLock, AbstractPreferences, PrimitiveIterator.OfInt, InputMismatchException, PriorityBlockingQueue, LongSummaryStatistics, ServiceLoader, BeanContext, AbstractOwnableSynchronizer,  SQLInvalidAuthorizationSpecException, Level,  BeanContextSupport,  SQLTimeoutException, LongSupplier, Base64, PropertyPermission, ZipEntry, SortedSet,  ConcurrentSkipListSet,  SQLRecoverableException, UnknownFormatConversionException, SimpleTimeZone, ListResourceBundle,  DataTruncation, EventListener, UnaryOperator, CompletionStage, Spliterator, Pattern,  TreeMap, TreeMap, OptionalDouble, LongToDoubleFunction,  ConcurrentHashMap, DoubleFunction, CalendarDataProvider, DataFormatException,  Hashtable, LongUnaryOperator,  NavigableMap<K, IntToLongFunction, MissingFormatWidthException,  SOAPMessageContext, BrokenBarrierException, Formatter.BigDecimalLayoutForm, RecursiveTask, IdentityHashMap, Attributes, DoubleToLongFunction,  NavigableSet<E>, ForkJoinTask, IntUnaryOperator, Executors, LinkedHashMap,  Spliterators.AbstractLongSpliterator, GZIPOutputStream, SynchronousQueue, Stream,  UIDefaults,  TransferQueue<E>, UUID, TimeoutException, ConcurrentMap, Handler, JarOutputStream, ListIterator, EventObject, Spliterators, LongConsumer, LongFunction, ResourceBundle.Control, ThreadPoolExecutor.DiscardOldestPolicy,  Provider,  BeanContextServices, BaseStream, FormattableFlags, AbstractQueuedSynchronizer, Pack200, T_SPLITR>, Formatter, CopyOnWriteArraySet, Pack200.Unpacker,  ConcurrentNavigableMap<K, Collector, PatternSyntaxException,  LinkedHashMap,  DirectoryStream<T>, ConcurrentSkipListSet, EnumSet, LocaleServiceProvider, JarEntry, DoubleStream.Builder,  EnumSet, ConsoleHandler,  CopyOnWriteArraySet, RejectedExecutionException, Date, FileHandler, LongAccumulator, Timer, ZipOutputStream, Future,  AbstractSequentialList,  SQLFeatureNotSupportedException, LogManager, SplittableRandom]