0% found this document useful (0 votes)
57 views153 pages

Java Interview Questions

The document outlines various Java interview questions and topics, including Object Oriented Programming concepts such as encapsulation, inheritance, polymorphism, and abstraction. It also covers general Java questions about JVM, JDK, and data types, as well as threading, collections, and key differences between various Java classes and interfaces. Each section provides essential information and explanations relevant to Java programming and its core principles.

Uploaded by

chriswforbes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views153 pages

Java Interview Questions

The document outlines various Java interview questions and topics, including Object Oriented Programming concepts such as encapsulation, inheritance, polymorphism, and abstraction. It also covers general Java questions about JVM, JDK, and data types, as well as threading, collections, and key differences between various Java classes and interfaces. Each section provides essential information and explanations relevant to Java programming and its core principles.

Uploaded by

chriswforbes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Interview Questions.

Table of Contents
• Object Oriented Programming (OOP)
• General Questions about Java
• Java Threads
• Java Collections
• Garbage Collectors
• Exception Handling
• Java Applets
• Swing
• JDBC
• Remote Method Invocation (RMI)
• Servlets
• JSP

Object Oriented Programming (OOP)


Java is a computer programming language that is concurrent, class-based and object-
oriented. The advantages of object oriented software development are shown below:
• Modular development of code, which leads to easy maintenance and modification.
• Reusability of code.
• Improved reliability and flexibility of code.
• Increased understanding of code.
Object-oriented programming contains many significant features, such
as encapsulation, inheritance, polymorphism and abstraction. We analyze each
feature separately in the following sections.

Encapsulation
Encapsulation provides objects with the ability to hide their internal characteristics and
behavior. Each object provides a number of methods, which can be accessed by other
objects and change its internal data. In Java, there are three access modifiers: public,
private and protected. Each modifier imposes different access rights to other classes, either
in the same or in external packages. Some of the advantages of using encapsulation are
listed below:
• The internal state of every objected is protected by hiding its attributes.
• It increases usability and maintenance of code, because the behavior of an object can be
independently changed or extended.
• It improves modularity by preventing objects to interact with each other, in an undesired
way.
You can refer to our tutorial here for more details and examples on encapsulation.

Polymorphism
Polymorphism is the ability of programming languages to present the same interface for
differing underlying data types. A polymorphic type is a type whose operations can also be
applied to values of some other type.

Inheritance
Inheritance provides an object with the ability to acquire the fields and methods of another
class, called base class. Inheritance provides re-usability of code and can be used to add
additional features to an existing class, without modifying it.

Abstraction
Abstraction is the process of separating ideas from specific instances and thus, develop
classes in terms of their own functionality, instead of their implementation details. Java
supports the creation and existence of abstract classes that expose interfaces, without
including the actual implementation of all methods. The abstraction technique aims to
separate the implementation details of a class from its behavior.

Differences between Abstraction and Encapsulation


Abstraction and encapsulation are complementary concepts. On the one hand, abstraction
focuses on the behavior of an object. On the other hand, encapsulation focuses on the
implementation of an object’s behavior. Encapsulation is usually achieved by hiding
information about the internal state of an object and thus, can be seen as a strategy used
in order to provide abstraction.

General Questions about Java


1. What is JVM ? Why is Java called the “Platform Independent Programming
Language” ? A Java virtual machine (JVM) is a process virtual machine that can execute
Java bytecode. Each Java source file is compiled into a bytecode file, which is executed by
the JVM. Java was designed to allow application programs to be built that could be run on
any platform, without having to be rewritten or recompiled by the programmer for each
separate platform. A Java virtual machine makes this possible, because it is aware of the
specific instruction lengths and other particularities of the underlying hardware platform.
2. What is the Difference between JDK and JRE ? The Java Runtime Environment
(JRE) is basically the Java Virtual Machine (JVM) where your Java programs are being
executed. It also includes browser plugins for applet execution. The Java Development Kit
(JDK) is the full featured Software Development Kit for Java, including the JRE, the
compilers and tools (like JavaDoc, and Java Debugger), in order for a user to develop, compile
and execute Java applications.
3. What does the “static” keyword mean ? Can you override private or static
method in Java ? The static keyword denotes that a member variable or method can be
accessed, without requiring an instantiation of the class to which it belongs. A user cannot
override static methods in Java, because method overriding is based upon dynamic binding
at runtime and static methods are statically binded at compile time. A static method is not
associated with any instance of a class so the concept is not applicable.
4. Can you access non static variable in static context ? A static variable in Java
belongs to its class and its value remains the same for all its instances. A static variable is
initialized when the class is loaded by the JVM. If your code tries to access a non-static
variable, without any instance, the compiler will complain, because those variables are not
created yet and they are not associated with any instance.
5. What are the Data Types supported by Java ? What is Autoboxing and
Unboxing ? The eight primitive data types supported by the Java programming language
are:
• byte
• short
• int
• long
• float
• double
• boolean
• char
is the automatic conversion made by the Java compiler between the primitive
Autoboxing
types and their corresponding object wrapper classes. For example, the compiler converts
an int to an Integer, a double to a Double, and so on. If the conversion goes the other way,
this operation is called unboxing .
6. What is Function Overriding and Overloading in Java ? Method overloading in
Java occurs when two or more methods in the same class have the exact same name, but
different parameters. On the other hand, method overriding is defined as the case when a
child class redefines the same method as a parent class. Overridden methods must have
the same name, argument list, and return type. The overriding method may not limit the
access of the method it overrides.
7. What is a Constructor, Constructor Overloading in Java and Copy-Constructor
? A constructor gets invoked when a new object is created. Every class has a constructor.
In case the programmer does not provide a constructor for a class, the Java compiler
(Javac) creates a default constructor for that class. The constructor overloading is similar to
method overloading in Java. Different constructors can be created for a single class. Each
constructor must have its own unique parameter list. Finally, Java does support copy
constructors like C++, but the difference lies in the fact that Java doesn’t create a default
copy constructor if you don’t write your own.
8. Does Java support multiple inheritance ? No, Java does not support multiple
inheritance. Each class is able to extend only on one class, but is able to implement more
than one interfaces.
9. What is the difference between an Interface and an Abstract class ? Java
provides and supports the creation both of abstract classes and interfaces. Both
implementations share some common characteristics, but they differ in the following
features:
• All methods in an interface are implicitly abstract. On the other hand, an abstract class
may contain both abstract and non-abstract methods.
• A class may implement a number of Interfaces, but can extend only one abstract class.
• In order for a class to implement an interface, it must implement all its declared
methods. However, a class may not implement all declared methods of an abstract class.
Though, in this case, the sub-class must also be declared as abstract.
• Abstract classes can implement interfaces without even providing the implementation of
interface methods.
• Variables declared in a Java interface is by default final. An abstract class may contain
non-final variables.
• Members of a Java interface are public by default. A member of an abstract class can
either be private, protected or public.
• An interface is absolutely abstract and cannot be instantiated. An abstract class also
cannot be instantiated, but can be invoked if it contains a main method.
Also check out the Abstract class and Interface differences for JDK 8.
10. What are pass by reference and pass by value ? When an object is passed by
value, this means that a copy of the object is passed. Thus, even if changes are made to
that object, it doesn’t affect the original value. When an object is passed by reference, this
means that the actual object is not passed, rather a reference of the object is passed. Thus,
any changes made by the external method, are also reflected in all places.

Java Threads
11. What is the difference between processes and threads ? A process is an
execution of a program, while a Thread is a single execution sequence within a process. A
process can contain multiple threads. A Thread is sometimes called a lightweight process.
12. Explain different ways of creating a thread. Which one would you prefer and
why ? There are three ways that can be used in order for a Thread to be created:
• A class may extend the Thread class.
• A class may implement the Runnable interface.
• An application can use the Executor framework, in order to create a thread pool.
The Runnable interface is preferred, as it does not require an object to inherit
the Thread class. In case your application design requires multiple inheritance, only
interfaces can help you. Also, the thread pool is very efficient and can be implemented and
used very easily.
13. Explain the available thread states in a high-level. During its execution, a thread
can reside in one of the following states:
• NEW: The thread becomes ready to run, but does not necessarily start running
immediately.
• RUNNABLE: The Java Virtual Machine (JVM) is actively executing the thread’s code.
• BLOCKED: The thread is in a blocked state while waiting for a monitor lock.
• WAITING: The thread waits for another thread to perform a particular action.
• TIMED_WAITING: The thread waits for another thread to perform a particular action up to a
specified waiting time.
• TERMINATED: The thread has finished its execution.
14. What is the difference between a synchronized method and a synchronized
block ? In Java programming, each object has a lock. A thread can acquire the lock for an
object by using the synchronized keyword. The synchronized keyword can be applied in a
method level (coarse grained lock) or block level of code (fine grained lock).
15. How does thread synchronization occurs inside a monitor ? What levels of
synchronization can you apply ? The JVM uses locks in conjunction with monitors. A
monitor is basically a guardian that watches over a sequence of synchronized code and
ensuring that only one thread at a time executes a synchronized piece of code. Each
monitor is associated with an object reference. The thread is not allowed to execute the
code until it obtains the lock.
16. What’s a deadlock ? A condition that occurs when two processes are waiting for
each other to complete, before proceeding. The result is that both processes wait endlessly.
17. How do you ensure that N threads can access N resources without deadlock
? A very simple way to avoid deadlock while using N threads is to impose an ordering on
the locks and force each thread to follow that ordering. Thus, if all threads lock and unlock
the mutexes in the same order, no deadlocks can arise.

Java Collections
18. What are the basic interfaces of Java Collections Framework ? Java Collections
Framework provides a well designed set of interfaces and classes that support operations on
a collections of objects. The most basic interfaces that reside in the Java Collections
Framework are:
• Collection, which represents a group of objects known as its elements.
• Set, which is a collection that cannot contain duplicate elements.
• List, which is an ordered collection and can contain duplicate elements.
• Map, which is an object that maps keys to values and cannot contain duplicate keys.
19. Why Collection doesn’t extend Cloneable and Serializable interfaces
? The Collection interface specifies groups of objects known as elements. Each concrete
implementation of a Collection can choose its own way of how to maintain and order its
elements. Some collections allow duplicate keys, while some other collections don’t. The
semantics and the implications of either cloning or serialization come into play when dealing
with actual implementations. Thus, the concrete implementations of collections should
decide how they can be cloned or serialized.
20. What is an Iterator ? The Iterator interface provides a number of methods that are
able to iterate over any Collection. Each Java Collection contains the iterator method that
returns an Iterator instance. Iterators are capable of removing elements from the
underlying collection during the iteration. 21. What differences exist between Iterator
and ListIterator ? The differences of these elements are listed below:
• An Iterator can be used to traverse the Set and List collections, while
the ListIterator can be used to iterate only over Lists.
• The Iterator can traverse a collection only in forward direction, while
the ListIterator can traverse a List in both directions.
• The ListIterator implements the Iterator interface and contains extra functionality, such
as adding an element, replacing an element, getting the index position for previous and
next elements, etc.
22. What is difference between fail-fast and fail-safe ? The Iterator's fail-safe
property works with the clone of the underlying collection and thus, it is not affected by any
modification in the collection. All the collection classes in [Link] package are fail-fast,
while the collection classes in [Link] are fail-safe. Fail-fast iterators throw
a ConcurrentModificationException , while fail-safe iterator never throws such an exception.
23. How HashMap works in Java ? A HashMap in Java stores key-value pairs.
The HashMap requires a hash function and uses hashCode and equals methods, in order to put
and retrieve elements to and from the collection respectively. When the put method is
invoked, the HashMap calculates the hash value of the key and stores the pair in the
appropriate index inside the collection. If the key exists, its value is updated with the new
value. Some important characteristics of a HashMap are its capacity, its load factor and the
threshold resizing.
24. What is the importance of hashCode() and equals() methods ? In Java,
a HashMap uses the hashCode and equals methods to determine the index of the key-value pair
and to detect duplicates. More specifically, the hashCodemethod is used in order to
determine where the specified key will be stored. Since different keys may produce the
same hash value, the equals method is used, in order to determine whether the specified
key actually exists in the collection or not. Therefore, the implementation of both methods
is crucial to the accuracy and efficiency of the HashMap.
25. What differences exist between HashMap and Hashtable ? Both
the HashMap and Hashtable classes implement the Map interface and thus, have very similar
characteristics. However, they differ in the following features:
• A HashMap allows the existence of null keys and values, while a Hashtable doesn’t allow
neither null keys, nor null values.
• A Hashtable is synchronized, while a HashMap is not. Thus, HashMap is preferred in single-
threaded environments, while a Hashtable is suitable for multi-threaded environments.
• A HashMap provides its set of keys and a Java application can iterate over them. Thus,
a HashMap is fail-fast. On the other hand, a Hashtable provides an Enumeration of its keys.
• The Hashtable class is considered to be a legacy class.
26. What is difference between Array and ArrayList ? When will you use Array
over ArrayList ? The Array and ArrayList classes differ on the following features:
• Arrays can contain primitive or objects, while an ArrayList can contain only objects.
• Arrays have fixed size, while an ArrayList is dynamic.
• An ArrayListprovides more methods and features, such as addAll, removeAll, iterator,
etc.
• For a list of primitive data types, the collections use autoboxing to reduce the coding
effort. However, this approach makes them slower when working on fixed size primitive
data types.
27. What is difference between ArrayList and LinkedList ? Both
the ArrayList and LinkedList classes implement the List interface, but they differ on the
following features:
• An ArrayList is an index based data structure backed by an Array. It provides random
access to its elements with a performance equal to O(1). On the other hand,
a LinkedList stores its data as list of elements and every element is linked to its previous
and next element. In this case, the search operation for an element has execution time
equal to O(n).
• The Insertion, addition and removal operations of an element are faster in
a LinkedList compared to an ArrayList, because there is no need of resizing an array or
updating the index when an element is added in some arbitrary position inside the
collection.
• A LinkedList consumes more memory than an ArrayList, because every node in
a LinkedList stores two references, one for its previous element and one for its next
element.
Check also our article ArrayList vs. LinkedList.
28. What is Comparable and Comparator interface ? List their differences. Java
provides the Comparableinterface, which contains only one method, called compareTo. This
method compares two objects, in order to impose an order between them. Specifically, it
returns a negative integer, zero, or a positive integer to indicate that the input object is less
than, equal or greater than the existing object. Java provides the Comparator interface,
which contains two methods, called compare and equals. The first method compares its two
input arguments and imposes an order between them. It returns a negative integer, zero,
or a positive integer to indicate that the first argument is less than, equal to, or greater
than the second. The second method requires an object as a parameter and aims to decide
whether the input object is equal to the comparator. The method returns true, only if the
specified object is also a comparator and it imposes the same ordering as the comparator.
29. What is Java Priority Queue ? The PriorityQueue is an unbounded queue, based on
a priority heap and its elements are ordered in their natural order. At the time of its
creation, we can provide a Comparator that is responsible for ordering the elements of
the PriorityQueue. A PriorityQueue doesn’t allow null values, those objects that doesn’t
provide natural ordering, or those objects that don’t have any comparator associated with
them. Finally, the Java PriorityQueue is not thread-safe and it requires O(log(n)) time for its
enqueing and dequeing operations.
30. What do you know about the big-O notation and can you give some
examples with respect to different data structures ? The Big-O notation simply
describes how well an algorithm scales or performs in the worst case scenario as the
number of elements in a data structure increases. The Big-O notation can also be used to
describe other behavior such as memory consumption. Since the collection classes are
actually data structures, we usually use the Big-O notation to chose the best
implementation to use, based on time, memory and performance. Big-O notation can give a
good indication about performance for large amounts of data.
31. What is the tradeoff between using an unordered array versus an ordered
array ? The major advantage of an ordered array is that the search times have time
complexity of O(log n), compared to that of an unordered array, which is O (n). The
disadvantage of an ordered array is that the insertion operation has a time complexity of
O(n), because the elements with higher values must be moved to make room for the new
element. Instead, the insertion operation for an unordered array takes constant time of
O(1).
32. What are some of the best practices relating to the Java Collection
framework ?
• Choosing the right type of the collection to use, based on the application’s needs, is very
crucial for its performance. For example if the size of the elements is fixed and know a
priori, we shall use an Array, instead of an ArrayList.
• Some collection classes allow us to specify their initial capacity. Thus, if we have an
estimation on the number of elements that will be stored, we can use it to avoid
rehashing or resizing.
• Always use Generics for type-safety, readability, and robustness. Also, by using Generics
you avoid the ClassCastException during runtime.
• Use immutable classes provided by the Java Development Kit (JDK) as a key in a Map, in
order to avoid the implementation of the hashCode and equals methods for our custom
class.
• Program in terms of interface not implementation.
• Return zero-length collections or arrays as opposed to returning a null in case the
underlying collection is actually empty.
33. What’s the difference between Enumeration and Iterator interfaces
? Enumeration is twice as fast as compared to an Iterator and uses very less memory.
However, the Iterator is much safer compared to Enumeration, because other threads are
not able to modify the collection object that is currently traversed by the iterator.
Also, Iteratorsallow the caller to remove elements from the underlying collection,
something which is not possible with Enumerations.
34. What is the difference between HashSet and TreeSet ? The HashSet is
Implemented using a hash table and thus, its elements are not ordered. The add, remove,
and contains methods of a HashSet have constant time complexity O(1). On the other hand,
a TreeSet is implemented using a tree structure. The elements in a TreeSet are sorted, and
thus, the add, remove, and contains methods have time complexity of O(logn).

Garbage Collectors
35. What is the purpose of garbage collection in Java, and when is it used ? The
purpose of garbage collection is to identify and discard those objects that are no longer
needed by the application, in order for the resources to be reclaimed and reused.
36. What does [Link]() and [Link]() methods do ? These methods can be
used as a hint to the JVM, in order to start a garbage collection. However, this it is up to
the Java Virtual Machine (JVM) to start the garbage collection immediately or later in time.
37. When is the finalize() called ? What is the purpose of finalization ? The finalize
method is called by the garbage collector, just before releasing the object’s memory. It is
normally advised to release resources held by the object inside the finalize method.
38. If an object reference is set to null, will the Garbage Collector immediately
free the memory held by that object ? No, the object will be available for garbage
collection in the next cycle of the garbage collector.
39. What is structure of Java Heap ? What is Perm Gen space in Heap ? The JVM
has a heap that is the runtime data area from which memory for all class instances and
arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed
by an automatic memory management system which is known as a garbage collector. Heap
memory consists of live and dead objects. Live objects are accessible by the application and
will not be a subject of garbage collection. Dead objects are those which will never be
accessible by the application, but have not been collected by the garbage collector yet.
Such objects occupy the heap memory space until they are eventually collected by the
garbage collector.
40. What is the difference between Serial and Throughput Garbage collector
? The throughput garbage collector uses a parallel version of the young generation
collector and is meant to be used with applications that have medium to large data sets. On
the other hand, the serial collector is usually adequate for most small applications (those
requiring heaps of up to approximately 100MB on modern processors).
41. When does an Object becomes eligible for Garbage collection in Java ? A Java
object is subject to garbage collection when it becomes unreachable to the program in
which it is currently used.
42. Does Garbage collection occur in permanent generation space in JVM
? Garbage Collection does occur in PermGen space and if PermGen space is full or cross a
threshold, it can trigger a full garbage collection. If you look carefully at the output of the
garbage collector, you will find that PermGen space is also garbage collected. This is the
reason why correct sizing of PermGen space is important to avoid frequent full garbage
collections. Also check our article Java 8: PermGen to Metaspace.

Exception Handling
43. What are the two types of Exceptions in Java ? Which are the differences
between them ? Java has two types of exceptions: checked exceptions and unchecked
exceptions. Unchecked exceptions do not need to be declared in a method or a
constructor’s throws clause, if they can be thrown by the execution of the method or the
constructor, and propagate outside the method or constructor boundary. On the other
hand, checked exceptions must be declared in a method or a constructor’s throws clause.
See here for tips on Java exception handling.
44. What is the difference between Exception and Error in java
? Exception and Error classes are both subclasses of the Throwable class. The Exception class
is used for exceptional conditions that a user’s program should catch. The Error class
defines exceptions that are not excepted to be caught by the user program.
45. What is the difference between throw and throws ? The throw keyword is used
to explicitly raise a exception within the program. On the contrary, the throws clause is
used to indicate those exceptions that are not handled by a method. Each method must
explicitly specify which exceptions does not handle, so the callers of that method can guard
against possible exceptions. Finally, multiple exceptions are separated by a comma.
45. What is the importance of finally block in exception handling ? A finally block
will always be executed, whether or not an exception is actually thrown. Even in the case
where the catch statement is missing and an exception is thrown, the finally block will still
be executed. Last thing to mention is that the finally block is used to release resources like
I/O buffers, database connections, etc.
46. What will happen to the Exception object after exception handling
? The Exception object will be garbage collected in the next garbage collection.
47. How does finally block differ from finalize() method ? A finally block will be
executed whether or not an exception is thrown and is used to release those resources held
by the application. Finalize is a protected method of the Object class, which is called by the
Java Virtual Machine (JVM) just before an object is garbage collected.

Java Applets
48. What is an Applet ? A java applet is program that can be included in a HTML page
and be executed in a java enabled client browser. Applets are used for creating dynamic
and interactive web applications.
49. Explain the life cycle of an Applet. An applet may undergo the following states:
• Init: An applet is initialized each time is loaded.
• Start: Begin the execution of an applet.
• Stop: Stop the execution of an applet.
• Destroy: Perform a final cleanup, before unloading the applet.
50. What happens when an applet is loaded ? First of all, an instance of the applet’s
controlling class is created. Then, the applet initializes itself and finally, it starts running.
51. What is the difference between an Applet and a Java Application ? Applets are
executed within a java enabled browser, but a Java application is a standalone Java
program that can be executed outside of a browser. However, they both require the
existence of a Java Virtual Machine (JVM). Furthermore, a Java application requires a main
method with a specific signature, in order to start its execution. Java applets don’t need
such a method to start their execution. Finally, Java applets typically use a restrictive
security policy, while Java applications usually use more relaxed security policies.
52. What are the restrictions imposed on Java applets ? Mostly due to security
reasons, the following restrictions are imposed on Java applets:
• An applet cannot load libraries or define native methods.
• An applet cannot ordinarily read or write files on the execution host.
• An applet cannot read certain system properties.
• An applet cannot make network connections except to the host that it came from.
• An applet cannot start any program on the host that’s executing it.
53. What are untrusted applets ? Untrusted applets are those Java applets that cannot
access or execute local system files. By default, all downloaded applets are considered as
untrusted.
54. What is the difference between applets loaded over the internet and applets
loaded via the file system ?Regarding the case where an applet is loaded over the
internet, the applet is loaded by the applet classloader and is subject to the restrictions
enforced by the applet security manager. Regarding the case where an applet is loaded
from the client’s local disk, the applet is loaded by the file system loader. Applets loaded via
the file system are allowed to read files, write files and to load libraries on the client. Also,
applets loaded via the file system are allowed to execute processes and finally, applets
loaded via the file system are not passed through the byte code verifier.
55. What is the applet class loader, and what does it provide ? When an applet is
loaded over the internet, the applet is loaded by the applet classloader. The class loader
enforces the Java name space hierarchy. Also, the class loader guarantees that a unique
namespace exists for classes that come from the local file system, and that a unique
namespace exists for each network source. When a browser loads an applet over the net,
that applet’s classes are placed in a private namespace associated with the applet’s origin.
Then, those classes loaded by the class loader are passed through the [Link] verifier
checks that the class file conforms to the Java language specification . Among other things,
the verifier ensures that there are no stack overflows or underflows and that the
parameters to all bytecode instructions are correct.
56. What is the applet security manager, and what does it provide ? The applet
security manager is a mechanism to impose restrictions on Java applets. A browser may
only have one security manager. The security manager is established at startup, and it
cannot thereafter be replaced, overloaded, overridden, or extended.

Swing
57. What is the difference between a Choice and a List ? A Choice is displayed in a
compact form that must be pulled down, in order for a user to be able to see the list of all
available choices. Only one item may be selected from a Choice. A List may be displayed in
such a way that several List items are visible. A List supports the selection of one or more
List items.
58. What is a layout manager ? A layout manager is the used to organize the
components in a container.
59. What is the difference between a Scrollbar and a JScrollPane ? A Scrollbar is
a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own
events and performs its own scrolling.
60. Which Swing methods are thread-safe ? There are only three thread-safe
methods: repaint, revalidate, and invalidate.
61. Name three Component subclasses that support
painting. The Canvas, Frame, Panel, and Applet classes support painting.
62. What is clipping ? Clipping is defined as the process of confining paint operations to
a limited area or shape.
63. What is the difference between a MenuItem and a CheckboxMenuItem
? The CheckboxMenuItem class extends the MenuItem class and supports a menu item that may
be either checked or unchecked.
64. How are the elements of a BorderLayout organized ? The elements of
a BorderLayout are organized at the borders (North, South, East, and West) and the center
of a container.
65. How are the elements of a GridBagLayout organized ? The elements of
a GridBagLayout are organized according to a grid. The elements are of different sizes and
may occupy more than one row or column of the grid. Thus, the rows and columns may
have different sizes.
66. What is the difference between a Window and a Frame ? The Frame class
extends the Window class and defines a main application window that can have a menu
bar.
67. What is the relationship between clipping and repainting ? When a window is
repainted by the AWT painting thread, it sets the clipping regions to the area of the window
that requires repainting.
68. What is the relationship between an event-listener interface and an event-
adapter class ? An event-listener interface defines the methods that must be
implemented by an event handler for a particular event. An event adapter provides a
default implementation of an event-listener interface.
69. How can a GUI component handle its own events ? A GUI component can
handle its own events, by implementing the corresponding event-listener interface and
adding itself as its own event listener.
70. What advantage do Java’s layout managers provide over traditional
windowing systems ? Java uses layout managers to lay out components in a consistent
manner, across all windowing platforms. Since layout managers aren’t tied to absolute
sizing and positioning, they are able to accomodate platform-specific differences among
windowing systems.
71. What is the design pattern that Java uses for all Swing components ? The
design pattern used by Java for all Swing components is the Model View Controller (MVC)
pattern.

JDBC
72. What is JDBC ? JDBC is an abstraction layer that allows users to choose between
databases. JDBC enables developers to write database applications in Java, without having
to concern themselves with the underlying details of a particular database.
73. Explain the role of Driver in JDBC. The JDBC Driver provides vendor-specific
implementations of the abstract classes provided by the JDBC API. Each driver must
provide implementations for the following classes of the [Link]
package:Connection, Statement, PreparedStatement, CallableStatement, ResultSet and Driver.
74. What is the purpose [Link] method ? This method is used to method is
used to load the driver that will establish a connection to the database.
75. What is the advantage of PreparedStatement over Statement
? PreparedStatements are precompiled and thus, their performance is much better. Also,
PreparedStatement objects can be reused with different input values to their queries.
76. What is the use of CallableStatement ? Name the method, which is used to
prepare a CallableStatement.A CallableStatement is used to execute stored procedures.
Stored procedures are stored and offered by a database. Stored procedures may take input
values from the user and may return a result. The usage of stored procedures is highly
encouraged, because it offers security and [Link] method that prepares
a CallableStatement is the following:
1 [Link]();
77. What does Connection pooling mean ? The interaction with a database can be
costly, regarding the opening and closing of database connections. Especially, when the
number of database clients increases, this cost is very high and a large number of
resources is consumed.A pool of database connections is obtained at start up by the
application server and is maintained in a pool. A request for a connection is served by
a connection residing in the pool. In the end of the connection, the request is returned to
the pool and can be used to satisfy future requests.

Remote Method Invocation (RMI)


78. What is RMI ? The Java Remote Method Invocation (Java RMI) is a Java API that
performs the object-oriented equivalent of remote procedure calls (RPC), with support for
direct transfer of serialized Java classes and distributed garbage collection. Remote Method
Invocation (RMI) can also be seen as the process of activating a method on a remotely
running object. RMI offers location transparency because a user feels that a method is
executed on a locally running object. Check some RMI Tips here.
79. What is the basic principle of RMI architecture ? The RMI architecture is based
on a very important principle which states that the definition of the behavior and the
implementation of that behavior, are separate concepts. RMI allows the code that defines
the behavior and the code that implements the behavior to remain separate and to run on
separate JVMs.
80. What are the layers of RMI Architecture ? The RMI architecture consists of the
following layers:
• Stub and Skeleton layer: This layer lies just beneath the view of the developer. This layer
is responsible for intercepting method calls made by the client to the interface and
redirect these calls to a remote RMI Service.
• Remote Reference Layer: The second layer of the RMI architecture deals with the
interpretation of references made from the client to the server’s remote objects. This
layer interprets and manages references made from clients to the remote service
objects. The connection is a one-to-one (unicast) link.
• Transport layer: This layer is responsible for connecting the two JVM participating in the
service. This layer is based on TCP/IP connections between machines in a network. It
provides basic connectivity, as well as some firewall penetration strategies.
81. What is the role of Remote Interface in RMI ? The Remote interface serves to
identify interfaces whose methods may be invoked from a non-local virtual machine. Any
object that is a remote object must directly or indirectly implement this interface. A class
that implements a remote interface should declare the remote interfaces being
implemented, define the constructor for each remote object and provide an implementation
for each remote method in all remote interfaces.
82. What is the role of the [Link] Class ? The [Link] class
provides methods for storing and obtaining references to remote objects in the remote
object registry. Each method of the Naming class takes as one of its arguments a name
that is a String in URL format.
83. What is meant by binding in RMI ? Binding is the process of associating or
registering a name for a remote object, which can be used at a later time, in order to look
up that remote object. A remote object can be associated with a name using the bind or
rebind methods of the Naming class.
84. What is the difference between using bind() and rebind() methods of
Naming Class ? The bind method bind is responsible for binding the specified name to a
remote object, while the rebind method is responsible for rebinding the specified name to a
new remote object. In case a binding exists for that name, the binding is replaced.
85. What are the steps involved to make work a RMI program ? The following
steps must be involved in order for a RMI program to work properly:
• Compilation of all source files.
• Generatation of the stubs using rmic.
• Start the rmiregistry.
• Start the RMIServer.
• Run the client program.
86. What is the role of stub in RMI ? A stub for a remote object acts as a client’s local
representative or proxy for the remote object. The caller invokes a method on the local
stub, which is responsible for executing the method on the remote object. When a stub’s
method is invoked, it undergoes the following steps:
• It initiates a connection to the remote JVM containing the remote object.
• It marshals the parameters to the remote JVM.
• It waits for the result of the method invocation and execution.
• It unmarshals the return value or an exception if the method has not been successfully
executed.
• It returns the value to the caller.
87. What is DGC ? And how does it work ? DGC stands for Distributed Garbage
Collection. Remote Method Invocation (RMI) uses DGC for automatic garbage collection.
Since RMI involves remote object references across JVM’s, garbage collection can be quite
difficult. DGC uses a reference counting algorithm to provide automatic memory
management for remote objects.
88. What is the purpose of using RMISecurityManager in RMI
? RMISecurityManager provides a security manager that can be used by RMI applications,
which use downloaded code. The class loader of RMI will not download any classes from
remote locations, if the security manager has not been set.
89. Explain Marshalling and demarshalling. When an application wants to pass its
memory objects across a network to another host or persist it to storage, the in-memory
representation must be converted to a suitable format. This process is called marshalling
and the revert operation is called demarshalling.
90. Explain Serialization and Deserialization. Java provides a mechanism, called
object serialization where an object can be represented as a sequence of bytes and
includes the object’s data, as well as information about the object’s type, and the types of
data stored in the object. Thus, serialization can be seen as a way of flattening objects, in
order to be stored on disk, and later, read back and reconstituted. Deserialisation is the
reverse process of converting an object from its flattened state to a live object.

Servlets
91. What is a Servlet ? The servlet is a Java programming language class used to
process client requests and generate dynamic web content. Servlets are mostly used to
process or store data submitted by an HTML form, provide dynamic content and manage
state information that does not exist in the stateless HTTP protocol.
92. Explain the architechure of a Servlet. The core abstraction that must be
implemented by all servlets is the [Link] interface. Each servlet must
implement it either directly or indirectly, either by extending [Link] or
[Link]. Finally, each servlet is able to serve multiple requests in
parallel using multithreading.
93. What is the difference between an Applet and a Servlet ? An Applet is a client
side java program that runs within a Web browser on the client machine. On the other
hand, a servlet is a server side component that runs on the web [Link] applet can use
the user interface classes, while a servlet does not have a user interface. Instead, a servlet
waits for client’s HTTP requests and generates a response in every request.
94. What is the difference between GenericServlet and HttpServlet
? GenericServlet is a generalized and protocol-independent servlet that implements the
Servlet and ServletConfig interfaces. Those servlets extending the GenericServlet class shall
override the service method. Finally, in order to develop an HTTP servlet for use on the
Web that serves requests using the HTTP protocol, your servlet must extend the
HttpServlet instead. Check Servlet examples here.
95. Explain the life cycle of a Servlet. On every client’s request, the Servlet Engine
loads the servlets and invokes its init methods, in order for the servlet to be initialized.
Then, the Servlet object handles all subsequent requests coming from that client, by
invoking the service method for each request separately. Finally, the servlet is removed by
calling the server’s destroy method.
96. What is the difference between doGet() and doPost() ? doGET: The GET method
appends the name-value pairs on the request’s URL. Thus, there is a limit on the number of
characters and subsequently on the number of values that can be used in a client’s request.
Furthermore, the values of the request are made visible and thus, sensitive information
must not be passed in that way. doPOST: The POST method overcomes the limit imposed by
the GET request, by sending the values of the request inside its body. Also, there is no
limitations on the number of values to be sent across. Finally, the sensitive information
passed through a POST request is not visible to an external client.
97. What is meant by a Web Application ? A Web application is a dynamic extension of
a Web or application server. There are two types of web applications: presentation-oriented
and service-oriented. A presentation-oriented Web application generates interactive web
pages, which contain various types of markup language and dynamic content in response
to requests. On the other hand, a service-oriented web application implements the endpoint
of a web service. In general, a Web application can be seen as a collection of servlets
installed under a specific subset of the server’s URL namespace.
98. What is a Server Side Include (SSI) ? Server Side Includes (SSI) is a simple
interpreted server-side scripting language, used almost exclusively for the Web, and is
embedded with a servlet tag. The most frequent use of SSI is to include the contents of
one or more files into a Web page on a Web server. When a Web page is accessed by a
browser, the Web server replaces the servlet tag in that Web page with the hyper text
generated by the corresponding servlet.
99. What is Servlet Chaining ? Servlet Chaining is the method where the output of one
servlet is sent to a second servlet. The output of the second servlet can be sent to a third
servlet, and so on. The last servlet in the chain is responsible for sending the response to
the client.
100. How do you find out what client machine is making a request to your
servlet ? The ServletRequest class has functions for finding out the IP address or host
name of the client machine. getRemoteAddr() gets the IP address of the client machine and
getRemoteHost() gets the host name of the client machine. See example here.
101. What is the structure of the HTTP response ? The HTTP response consists of
three parts:
• Status Code: describes the status of the response. It can be used to check if the
request has been successfully completed. In case the request failed, the status code can
be used to find out the reason behind the failure. If your servlet does not return a status
code, the success status code, HttpServletResponse.SC_OK, is returned by default.
• HTTP Headers: they contain more information about the response. For example, the
headers may specify the date/time after which the response is considered stale, or the
form of encoding used to safely transfer the entity to the user. See how to retrieve
headers in Servlet here.
• Body: it contains the content of the response. The body may contain HTML code, an
image, etc. The body consists of the data bytes transmitted in an HTTP transaction
message immediately following the headers.
102. What is a cookie ? What is the difference between session and cookie ? A
cookie is a bit of information that the Web server sends to the browser. The browser stores
the cookies for each Web server in a local file. In a future request, the browser, along with
the request, sends all stored cookies for that specific Web [Link] differences between
session and a cookie are the following:
• The session should work, regardless of the settings on the client browser. The client may
have chosen to disable cookies. However, the sessions still work, as the client has no
ability to disable them in the server side.
• The session and cookies also differ in the amount of information the can store. The
HTTP session is capable of storing any Java object, while a cookie can only store String
objects.
103. Which protocol will be used by browser and servlet to communicate ? The
browser communicates with a servlet by using the HTTP protocol.
104. What is HTTP Tunneling ? HTTP Tunneling is a technique by which,
communications performed using various network protocols are encapsulated using the
HTTP or HTTPS protocols. The HTTP protocol therefore acts as a wrapper for a channel
that the network protocol being tunneled uses to communicate. The masking of other
protocol requests as HTTP requests is HTTP Tunneling.
105. What’s the difference between sendRedirect and forward methods ? The
sendRedirect method creates a new request, while the forward method just forwards a
request to a new target. The previous request scope objects are not available after a
redirect, because it results in a new request. On the other hand, the previous request scope
objects are available after forwarding. FInally, in general, the sendRedirect method is
considered to be slower compare to the forward method.
106. What is URL Encoding and URL Decoding ? The URL encoding procedure is
responsible for replacing all the spaces and every other extra special character of a URL,
into their corresponding Hex representation. In correspondence, URL decoding is the exact
opposite procedure.

JSP
107. What is a JSP Page ? A Java Server Page (JSP) is a text document that contains
two types of text: static data and JSP elements. Static data can be expressed in any text-
based format, such as HTML or XML. JSP is a technology that mixes static content with
dynamically-generated content. See JSP example here.
108. How are the JSP requests handled ? On the arrival of a JSP request, the browser
first requests a page with a .jsp extension. Then, the Web server reads the request and
using the JSP compiler, the Web server converts the JSP page into a servlet class. Notice
that the JSP file is compiled only on the first request of the page, or if the JSP file has
[Link] generated servlet class is invoked, in order to handle the browser’s request.
Once the execution of the request is over, the servlet sends a response back to the client.
See how to get Request parameters in a JSP.
109. What are the advantages of JSP ? The advantages of using the JSP technology
are shown below:
• JSP pages are dynamically compiled into servlets and thus, the developers can easily
make updates to presentation code.
• JSP pages can be pre-compiled.
• JSP pages can be easily combined to static templates, including HTML or XML fragments,
with code that generates dynamic content.
• Developers can offer customized JSP tag libraries that page authors access using an
XML-like syntax.
• Developers can make logic changes at the component level, without editing the
individual pages that use the application’s logic.
110. What are Directives ? What are the different types of Directives available in
JSP ? Directives are instructions that are processed by the JSP engine, when the page is
compiled to a servlet. Directives are used to set page-level instructions, insert data from
external files, and specify custom tag libraries. Directives are defined between < %@ and %
> .The different types of directives are shown below:
• Include directive : it is used to include a file and merges the content of the file with the
current page.
• Page directive : it is used to define specific attributes in the JSP page, like error page
and buffer.
• Taglib : it is used to declare a custom tag library which is used in the page.
111. What are JSP actions ? JSP actions use constructs in XML syntax to control the
behavior of the servlet engine. JSP actions are executed when a JSP page is requested.
They can be dynamically inserted into a file, re-use JavaBeans components, forward the
user to another page, or generate HTML for the Java [Link] of the available actions
are listed below:
• jsp:include – includes a file, when the JSP page is requested.
• jsp:useBean – finds or instantiates a JavaBean.
• jsp:setProperty – sets the property of a JavaBean.
• jsp:getProperty – gets the property of a JavaBean.
• jsp:forward – forwards the requester to a new page.
• jsp:plugin – generates browser-specific code.
112. What are Scriptlets ? In Java Server Pages (JSP) technology, a scriptlet is a piece
of Java-code embedded in a JSP page. The scriptlet is everything inside the tags. Between
these tags, a user can add any valid scriplet.
113. What are Decalarations ? Declarations are similar to variable declarations in Java.
Declarations are used to declare variables for subsequent use in expressions or scriptlets.
To add a declaration, you must use the sequences to enclose your declarations.
114. What are Expressions ? A JSP expression is used to insert the value of a scripting
language expression, converted into a string, into the data stream returned to the client, by
the web server. Expressions are defined between <% = and %> tags.
115. What is meant by implicit objects and what are they ? JSP implicit objects are
those Java objects that the JSP Container makes available to developers in each page. A
developer can call them directly, without being explicitly declared. JSP Implicit Objects are
also called pre-defined [Link] following objects are considered implicit in a JSP page:
• application
• page
• request
• response
• session
• exception
• out
• config
• pageContext

Want more Java interview questions?


Are you still with us? Wow, that was a huge article about different types of questions that
can be used in a Java interview. If you enjoyed this, then subscribe to our newsletter to
enjoy weekly updates and complimentary whitepapers! Also, check out our courses for
more advanced training!
So, what other Java interview questions are there? Let us know in the comments and we
will include them in the article! Happy coding!

Core Java Interview Questions

1. What if the main method is declared as private?

Answer:
The program compiles properly but at runtime it will give “Main method not public.”
message.

2. Q. What is meant by pass by reference and pass by value in Java?

Answer:
Pass by reference means, passing the address itself rather than passing the value. Pass by
value means passing a copy of the value.

3. Q. If you’re overriding the method equals() of an object, which other method you
might also consider?

Answer:
hashCode()

4. Q. What is Byte Code?

Or

5. Q. What gives java it’s “write once and run anywhere” nature?

Answer:
All Java programs are compiled into class files that contain bytecodes. These byte codes
can be run in any platform and hence java is said to be platform independent.

6. Q. Expain the reason for each keyword of public static void main(String args[])?

Answer:
• public – main(..) is the first method called by java environment when a program is
executed so it has to accessible from java environment. Hence the access specifier has
to be public.
• static : Java environment should be able to call this method without creating an
instance of the class , so this method must be declared as static.
• void : main does not return anything so the return type must be void
The argument String indicates the argument type which is given at the command line and
arg is an array for string given during command line.

7. Q. What are the differences between == and .equals() ?

Or

8. Q. what is difference between == and equals

Or

9. Q. Difference between == and equals method

Or

10. Q. What would you use to compare two String variables – the operator == or the
method equals()?

Or

11. Q. How is it possible for two String objects with identical values not to be equal
under the == operator?

Answer:
The == operator compares two objects to determine if they are the same object in memory
i.e. present in the same memory location. It is possible for two String objects to have the
same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean
equals(Object obj) is provided by the Object class and can be overridden. The default
implementation returns true only if the object is compared with itself, which is equivalent to
the equality operator == being used to compare aliases to the object. String, BitSet, Date,
and File override the equals() method. For two String objects, value equality means that
they contain the same character sequence. For the Wrapper classes, value equality means
that the primitive values are equal.
01 public class EqualsTest {

02
03 public static void main(String[] args) {

04

05 String s1 = “abc”;

06 String s2 = s1;

07 String s5 = “abc”;

08 String s3 = new String(”abc”);

09 String s4 = new String(”abc”);

[Link](”== comparison : ” + (s1


10
== s5));

[Link](”== comparison : ” + (s1


11
== s2));

[Link](”Using equals method : ”


12
+ [Link](s2));

[Link](”== comparison : ” + s3
13
== s4);

[Link](”Using equals method : ”


14
+ [Link](s4));

15 }

16 }

Output
1 == comparison : true

2 == comparison : true

3 Using equals method : true

4 false

5 Using equals method : true

12. Q. What if the static modifier is removed from the signature of the main method?

Or

13. Q. What if I do not provide the String array as the argument to the method?
Answer:
Program compiles. But at runtime throws an error “NoSuchMethodError”.

14. Q. Why oracle Type 4 driver is named as oracle thin driver?

Answer:
Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver
includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in
Java, so it is platform independent, can be downloaded to a browser at runtime, and does
not require any Oracle software on the client side. This driver requires a TCP/IP listener on
the server side, and the client connection string uses the TCP/IP port address, not the
TNSNAMES entry for the database name.

15. Q. What is the difference between final, finally and finalize? What do you
understand by the java final keyword?

Or

16. Q. What is final, finalize() and finally?

Or

17. Q. What is finalize() method?

Or

18. Q. What does it mean that a class or member is final?

Answer:
• final – declare constant
• finally – handles exception
• finalize – helps in garbage collection
Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final
class may not be subclassed. This is done for security reasons with basic classes like String
and Integer. It also allows the compiler to make some optimizations, and makes thread
safety a little easier to achieve. A final method can’t be overridden when its class is
inherited. You can’t change value of a final variable (is a constant). finalize() method is
used just before an object is destroyed and garbage collected. finally, a key word used in
exception handling and will be executed whether or not an exception is thrown. For
example, closing of open connections is done in the finally method.

19. Q. What is the Java API?


Answer:
The Java API is a large collection of ready-made software components that provide many
useful capabilities, such as graphical user interface (GUI) widgets.

20. Q. What is the GregorianCalendar class?

Answer:
The GregorianCalendar provides support for traditional Western calendars.

21. Q. What is the ResourceBundle class?

Answer:
The ResourceBundle class is used to store locale-specific resources that can be loaded by a
program to tailor the program’s appearance to the particular locale in which it is being run.

22. Q. Why there are no global variables in Java?

Answer:
Global variables are globally accessible. Java does not support globally accessible variables
due to following reasons:
• The global variables breaks the referential transparency
• Global variables create collisions in namespace.

23. Q. How to convert String to Number in java program?

Answer:
The valueOf() function of Integer class is is used to convert string to Number. Here is the
code example:
1 String numString = “1000″;

2 int id=[Link](numString).intValue();

24. Q. What is the SimpleTimeZone class?

Answer:
The SimpleTimeZone class provides support for a Gregorian calendar.

25. Q. What is the difference between a while statement and a do statement?


Answer:
A while statement (pre test) checks at the beginning of a loop to see whether the next loop
iteration should occur. A do while statement (post test) checks at the end of a loop to see
whether the next iteration of a loop should occur. The do statement will always execute the
loop body at least once.

26. Q. What is the Locale class?

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

27. Q. Describe the principles of OOPS.

Answer:
There are three main principals of oops which are called Polymorphism, Inheritance and
Encapsulation.

28. Q. Explain the Inheritance principle.

Answer:
Inheritance is the process by which one object acquires the properties of another object.
Inheritance allows well-tested procedures to be reused and enables changes to make once
and have effect in all relevant places

29. Q. What is implicit casting?

Answer:
Implicit casting is the process of simply assigning one entity to another without any
transformation guidance to the compiler. This type of casting is not permitted in all kinds of
transformations and may not work for all scenarios.
Example
1 int i = 1000;

2 long j = i; //Implicit casting

30. Q. Is sizeof a keyword in java?

Answer:
The sizeof is not a keyword.

31. Q. What is a native method?

Answer:
A native method is a method that is implemented in a language other than Java.

32. Q. In [Link](), what is System, out and println?

Answer:
System is a predefined final class, out is a PrintStream object and println is a built-in
overloaded method in the out object.

33. Q. What are Encapsulation, Inheritance and Polymorphism

Or

34. Q. Explain the Polymorphism principle. Explain the different forms


of Polymorphism.

Answer:
Polymorphism in simple terms means one name many forms. Polymorphism enables one
entity to be used as a general category for different types of actions. The specific action is
determined by the exact nature of the situation.
Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

35. Q. What is explicit casting?

Answer:
Explicit casting in the process in which the complier are specifically informed to about
transforming the object.
Example
1 long i = 700.20;

2 int j = (int) i; //Explicit casting


36. Q. What is the Java Virtual Machine (JVM)?

Answer:
The Java Virtual Machine is software that can be ported onto various hardware-based
platforms

37. Q. What do you understand by downcasting?

Answer:
The process of Downcasting refers to the casting from a general to a more specific type,
i.e. casting down the hierarchy

38. Q. What are Java Access Specifiers?

Or

39. Q. What is the difference between public, private, protected and default Access
Specifiers?

Or

40. Q. What are different types of access modifiers?

Answer:
Access specifiers are keywords that determine the type of access to the member of a class.
These keywords are for allowing privileges to parts of a program such as functions and
variables. These are:
• Public: accessible to all classes
• Protected: accessible to the classes within the same package and any subclasses.
• Private: accessible only to the class to which they belong
• Default: accessible to the class to which they belong and to subclasses within the same
package

41. Q. Which class is the superclass of every class?

Answer:
Object.

42. Q. Name primitive Java types.


Answer:
The 8 primitive types are byte, char, short, int, long, float, double, and boolean. Additional
is String.

43. Q. What is the difference between static and non-static variables?

Or

44. Q. What are “class variables”?

Or

45. Q. What is static in java?

Or

46. Q. What is a static method?

Answer:
A static variable is associated with the class as a whole rather than with specific instances
of a class. Each object will share a common copy of the static variables i.e. there is only
one copy per class, no matter how many objects are created from it. Class variables or
static variables are declared with the static keyword in a class. These are declared outside a
class and stored in static memory. Class variables are mostly used for constants. Static
variables are always called by the class name. This variable is created when the program
starts and gets destroyed when the programs stops. The scope of the class variable is same
an instance variable. Its initial value is same as instance variable and gets a default value
when it’s not initialized corresponding to the data type. Similarly, a static method is a
method that belongs to the class rather than any object of the class and doesn’t apply to an
object or even require that any objects of the class have been instantiated. Static methods
are implicitly final, because overriding is done based on the type of the object, and static
methods are attached to a class, not an object. A static method in a superclass can be
shadowed by another static method in a subclass, as long as the original method was not
declared final. However, you can’t override a static method with a non-static method. In
other words, you can’t change a static method into an instance method in a subclass.
Non-static variables take on unique values with each object instance.

47. Q. What is the difference between the boolean & operator and the && operator?

Answer:
If an expression involving the boolean & operator is evaluated, both operands are
evaluated, whereas the && operator is a short cut operator. When an expression involving
the && operator is evaluated, the first operand is evaluated. If the first operand returns a
value of true then the second operand is evaluated. If the first operand evaluates to false,
the evaluation of the second operand is skipped.

48. Q. How does Java handle integer overflows and underflows?

Answer:
It uses those low order bytes of the result that can fit into the size of the type allowed by
the operation.

49. Q. What if I write static public void instead of public static void?

Answer:
Program compiles and runs properly.

50. Q. What is the difference between declaring a variable and defining a variable?

Answer:
In declaration we only mention the type of the variable and its name without initializing it.
Defining means declaration + initialization. E.g. String s; is just a declaration while String s
= new String (”bob”); Or String s = “bob”; are both definitions.

51. Q. What type of parameter passing does Java support?

Answer:
In Java the arguments (primitives and objects) are always passed by value. With objects,
the object reference itself is passed by value and so both the original reference and
parameter copy both refer to the same object.

52. Q. Explain the Encapsulation principle.

Answer:
Encapsulation is a process of binding or wrapping the data and the codes that operates on
the data into a single entity. This keeps the data safe from outside interface and misuse.
Objects allow procedures to be encapsulated with their data to reduce potential
interference. One way to think about encapsulation is as a protective wrapper that prevents
code and data from being arbitrarily accessed by other code defined outside the wrapper.

53. Q. What do you understand by a variable?


Answer:
Variable is a named memory location that can be easily referred in the program. The
variable is used to hold the data and it can be changed during the course of the execution
of the program.

54. Q. What do you understand by numeric promotion?

Answer:
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric
type, so that integral and floating-point operations may take place. In the numerical
promotion process the byte, char, and short values are converted to int values. The int
values are also converted to long values, if necessary. The long and float values are
converted to double values, as required.

55. Q. What do you understand by casting in java language? What are the types of
casting?

Answer:
The process of converting one data type to another is called Casting. There are two types
of casting in Java; these are implicit casting and explicit casting.

56. Q. What is the first argument of the String array in main method?

Answer:
The String array is empty. It does not have any element. This is unlike C/C++ where the
first element by default is the program name. If we do not provide any arguments on the
command line, then the String array of main method will be empty but not null.

57. Q. How can one prove that the array is not null but empty?

Answer:
Print [Link]. It will print 0. That means it is empty. But if it would have been null then
it would have thrown a NullPointerException on attempting to print [Link].

58. Q. Can an application have multiple classes having main method?

Answer:
Yes. While starting the application we mention the class name to be run. The JVM will look
for the main method only in the class whose name you have mentioned. Hence there is not
conflict amongst the multiple classes having main method.

59. Q. When is static variable loaded? Is it at compile time or runtime? When exactly
a static block is loaded in Java?

Answer:
Static variable are loaded when classloader brings the class to the JVM. It is not necessary
that an object has to be created. Static variables will be allocated memory space when they
have been loaded. The code in a static block is loaded/executed only once i.e. when the
class is first initialized. A class can have any number of static blocks. Static block is not
member of a class, they do not have a return statement and they cannot be called directly.
Cannot contain this or super. They are primarily used to initialize static fields.

60. Q. Can I have multiple main methods in the same class?

Answer:
We can have multiple overloaded main methods but there can be only one main method
with the following signature :
1 public static void main(String[] args) {}

No the program fails to compile. The compiler says that the main method is already defined
in the class.

61. Q. Explain working of Java Virtual Machine (JVM)?

Answer:
JVM is an abstract computing machine like any other real computing machine which first
converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and
Interpreter reads byte codes.

62. Q. How can I swap two variables without using a third variable?

Answer:
Add two variables and assign the value into First variable. Subtract the Second value with
the result Value. and assign to Second variable. Subtract the Result of First Variable With
Result of Second Variable and Assign to First Variable. Example:
1 int a=5,b=10;a=a+b; b=a-b; a=a-b;

An other approach to the same question


You use an XOR swap. (BEST APPROACH) as in case of using above approach it may goes
over/under flow. For example:
1 int a = 5; int b = 10;

2 a = a ^ b;

3 b = a ^ b;

4 a = a ^ b;

63. Q. What is data encapsulation?

Answer:
Encapsulation may be used by creating ‘get’ and ’set’ methods in a class (JAVABEAN) which
are used to access the fields of the object. Typically the fields are made private while the
get and set methods are public. Encapsulation can be used to validate the data that is to be
stored, to do calculations on data that is stored in a field or fields, or for use in
introspection (often the case when using javabeans in Struts, for instance). Wrapping of
data and function into a single unit is called as data encapsulation. Encapsulation is nothing
but wrapping up the data and associated methods into a single unit in such a way that data
can be accessed with the help of associated methods. Encapsulation provides data security.
It is nothing but data hiding.

64. Q. What is reflection API? How are they implemented?

Answer:
Reflection is the process of introspecting the features and state of a class at runtime and
dynamically manipulate at run time. This is supported using Reflection API with built-in
classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we
can get the class name, by using the getName method.

65. Q. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap?
Is this the OS heap or the heap maintained by the JVM? Why

Answer:
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references
to those objects are on the STACK.

66. Q. What is phantom memory?

Answer:
Phantom memory is false memory. Memory that does not exist in reality.

67. Q. Can a method be static and synchronized?

Answer:
A static method can be synchronized. If you do so, the JVM will obtain a lock on the
[Link].
Class instance associated with the object. It is similar to saying:
1 synchronized([Link]) {

2}

68. Q. What is difference between String and StringTokenizer?

Answer:
A StringTokenizer is utility class used to break up string.
Example:
1 StringTokenizer st = new StringTokenizer(”Hello World”);

2 while ([Link]()) {

3 [Link]([Link]());

4}

Output:
1 Hello

2 World

69. Question: What is transient variable?

Answer:
Transient variable can’t be serialize. For example if a variable is declared as transient in a
Serializable class and the class is written to an ObjectStream, the value of the variable can’t
be written to the stream instead when the class is retrieved from the ObjectStream the
value of the variable becomes null.
Note
01 transient

02
03 identifies a variable not to be written out when an

04

05 instance is serialized (It can't be copied to remove

06

07 system)

08

09

10

11 volatile

12

13 indicates that the field is used by synchronized threads

14

15 and that the compiler should not attempt to perform

16

17 optimizations with it.

18

19

20

21 When more than one thread share a (volatile) data it is

22

checked every time. Every thread keeps the latest value


23
of volatile variable

70. Question: Name the containers which uses Border Layout as their default layout?

Answer:
Containers which uses Border Layout as their default are: window, Frame and Dialog
classes.

71. Question: What do you understand by Synchronization?

Answer:
Synchronization is a process of controlling the access of shared resources by the multiple
threads in such a manner that only one thread can access one resource at a time. In non
synchronized multithreaded application, it is possible for one thread to modify a shared
object while another thread is in the process of using or updating the object’s value.
Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
1 public synchronized void Method1 () {

3 // Appropriate method-related code.

5}

E.g. Synchronizing a block of code inside a function:


1 public myFunction (){

2 synchronized (this) {

3 // Synchronized code here.

4 }

5}

Reference: Core Java Interview Questions from our JCG partner Sunil Gulabani at
the Sunil Gulabani blog.
Collections in Java – Tutorial
DECEMBER 10, 2017 BY PANKAJ 56 COMMENTS

Collections in Java are used in almost every application. Java Collections Framework is
one of the core part of Java programming language. Java Collections tutorial will
explain Java Collections Framework in detail.

Collections in Java
1. What is Java Collections Framework?
• Benefits of Java Collections Framework
2. Java Collections Interfaces
• Collection Interface
• Iterator Interface
• Set Interface
• List Interface
• Queue Interface
• Dequeue Interface
• Map Interface
• ListIterator Interface
• SortedSet Interface
• SortedMap Interface
3. Java Collections Classes
• HashSet Class
• TreeSet Class
• ArrayList Class
• LinkedList Class
• HashMap Class
• TreeMap Class
• PriorityQueue Class
4. Collections class
5. Synchronized Wrappers
6. Unmodifiable wrappers
7. Thread Safe Collections
8. Collections API Algorithms
• Sorting
• Shuffling
• Searching
• Composition
• Min and Max values
9. Java 8 Collections API Features
10. Collection classes in a Nutshell
What is Java Collections Framework?
Collections are like containers that groups multiple items in a single unit. For example; a
jar of chocolates, list of names etc. Collections are used almost in every programming
language and when Java arrived, it also came with few Collection
classes; Vector, Stack, Hashtable, Array. Java 1.2 provided Collections
Framework that is architecture to represent and manipulate Collections in java in a
standard way. Java Collections Framework consists of following parts:

• Interfaces: Java Collections Framework interfaces provides the abstract data type
to represent collection. [Link] is the root interface of
Collections Framework. It is on the top of Collections framework hierarchy. It
contains some important methods such
as size(), iterator(), add(), remove(), clear() that every Collection
class must implement. Some other important interfaces
are [Link], [Link], [Link] and [Link].
Map. Map is the only interface that doesn’t inherits from Collection interface but it’s
part of Collections framework. All the collections framework interfaces are present
in [Link] package.
• Implementation Classes: Collections in Java provides core implementation
classes for collections. We can use them to create different types of collections in
java program. Some important collection classes
are ArrayList, LinkedList, HashMap, TreeMap, HashSet, [Link]
classes solve most of our programming needs but if we need some special
collection class, we can extend them to create our custom collection class.

Java 1.5 came up with thread-safe collection classes that allowed to modify
Collections while iterating over it, some of them
are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet
. These classes are in [Link] package. All the collection classes are
present in [Link] and [Link] package.

• Algorithms: Algorithms are useful methods to provide some common


functionalities, for example searching, sorting and shuffling.
Below class diagram shows Collections Framework hierarchy. For simplicity I have
included only commonly used interfaces and classes.

Benefits of Java Collections Framework


Java Collections framework have following benefits:

• Reduced Development Effort – It comes with almost all common types of


collections and useful methods to iterate and manipulate the data. So we can
concentrate more on business logic rather than designing our collection APIs.
• Increased Quality – Using core collection classes that are well tested increases
our program quality rather than using any home developed data structure.
• Reusability and Interoperability
• Reduce effort – to learn any new API if we use core collection API classes.

Java Collections Interfaces


Java collection interfaces are the foundation of the Java Collections Framework. Note
that all the core collection interfaces are generic; for example public interface
Collection<E>. The <E> syntax is for Generics and when we declare Collection, we
should use it to specify the type of Object it can contain. It helps in reducing run-time
errors by type-checking the Objects at compile-time.

To keep the number of core collection interfaces manageable, the Java platform doesn’t
provide separate interfaces for each variant of each collection type. If an unsupported
operation is invoked, a collection implementation throws
an UnsupportedOperationException.
Collection Interface
This is the root of the collection hierarchy. A collection represents a group of objects
known as its elements. The Java platform doesn’t provide any direct implementations of
this interface.

The interface has methods to tell you how many elements are in the collection
(size, isEmpty), to check whether a given object is in the collection (contains), to
add and remove an element from the collection (add, remove), and to provide an
iterator over the collection (iterator).

Collection interface also provides bulk operations methods that work on entire collection
– containsAll, addAll, removeAll, retainAll, clear.

The toArray methods are provided as a bridge between collections and older APIs
that expect arrays on input.

Iterator Interface
Iterator interface provides methods to iterate over any Collection. We can get iterator
instance from a Collection using iterator method. Iterator takes the place
of Enumeration in the Java Collections Framework. Iterators allow the caller to
remove elements from the underlying collection during the iteration. Iterators in
collection classes implement Iterator Design Pattern.

Set Interface
Set is a collection that cannot contain duplicate elements. This interface models the
mathematical set abstraction and is used to represent sets, such as the deck of cards.

The Java platform contains three general-purpose Set


implementations: HashSet, TreeSet, and LinkedHashSet. Set interface doesn’t
allow random-access to an element in the Collection. You can use iterator or foreach
loop to traverse the elements of a Set.

List Interface
List is an ordered collection and can contain duplicate elements. You can access any
element from it’s index. List is more like array with dynamic length. List is one of the
most used Collection type. ArrayListand LinkedList are implementation classes of
List interface.
List interface provides useful methods to add an element at specific index,
remove/replace element based on index and to get a sub-list using index.

List strList = new ArrayList<>();

//add at last

[Link](0, "0");

//add at specified index

[Link](1, "1");

//replace

[Link](1, "2");

//remove

[Link]("1");

Collections class provide some useful algorithm for List


– sort, shuffle, reverse, binarySearch etc.

Queue Interface
Queue is a collection used to hold multiple elements prior to processing. Besides basic
Collection operations, a Queue provides additional insertion, extraction, and inspection
operations.

Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out)
manner. Among the exceptions are priority queues, which order elements according to
a supplied comparator or the elements’ natural ordering. Whatever the ordering used,
the head of the queue is the element that would be removed by a call to remove or poll.
In a FIFO queue, all new elements are inserted at the tail of the queue.

Dequeue Interface
A linear collection that supports element insertion and removal at both ends. The name
deque is short for “double ended queue” and is usually pronounced “deck”. Most Deque
implementations place no fixed limits on the number of elements they may contain, but
this interface supports capacity-restricted deques as well as those with no fixed size
limit.

This interface defines methods to access the elements at both ends of the deque.
Methods are provided to insert, remove, and examine the element.

Map Interface
Java Map is an object that maps keys to values. A map cannot contain duplicate keys:
Each key can map to at most one value.

The Java platform contains three general-purpose Map


implementations: HashMap, TreeMap, and LinkedHashMap.

The basic operations of Map are put, get, containsKey, containsValue, size,
and isEmpty.

ListIterator Interface
An iterator for lists that allows the programmer to traverse the list in either direction,
modify the list during iteration, and obtain the iterator’s current position in the list.

A ListIterator has no current element; its cursor position always lies between the
element that would be returned by a call to previous() and the element that would be
returned by a call to next().

SortedSet Interface
SortedSet is a Set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering. Sorted sets are used for
naturally ordered sets, such as word lists and membership rolls.

SortedMap Interface
Map that maintains its mappings in ascending key order. This is the Map analog of
SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs,
such as dictionaries and telephone directories.
Java Collections Classes
Java Collections framework comes with many implementation classes for the interfaces.
Most common implementations are ArrayList, HashMap and HashSet. Java 1.5
included Concurrent implementations; for example ConcurrentHashMap and
CopyOnWriteArrayList. Usually Collection classes are not thread-safe and their iterator
is fail-fast. In this section, we will learn about commonly used collection classes.

HashSet Class
Java HashSet is the basic implementation the Set interface that is backed by
a HashMap. It makes no guarantees for iteration order of the set and permits
the null element.

This class offers constant time performance for basic operations


(add, remove, contains and size), assuming the hash function disperses the
elements properly among the buckets. We can set the initial capacity and load factor for
this collection. The load factor is a measure of how full the hash map is allowed to get
before its capacity is automatically increased.

TreeSet Class
A NavigableSet implementation based on a TreeMap. The elements are ordered
using their natural ordering, or by a Comparator provided at set creation time,
depending on which constructor is used.

Refer: Java Comparable Comparator

This implementation provides guaranteed log(n) time cost for the basic operations (add,
remove and contains).

Note that the ordering maintained by a set (whether or not an explicit comparator is
provided) must be consistent with equals if it is to correctly implement the Set interface.
(See Comparable or Comparator for a precise definition of consistent with equals.) This
is so because the Set interface is defined in terms of the equals operation, but a
TreeSet instance performs all element comparisons using its compareTo (or compare)
method, so two elements that are deemed equal by this method are, from the
standpoint of the set, equal.

ArrayList Class
Java ArrayList is the resizable-array implementation of the List interface. Implements all
optional list operations, and permits all elements, including null. In addition to
implementing the List interface, this class provides methods to manipulate the size of
the array that is used internally to store the list. (This class is roughly equivalent to
Vector, except that it is unsynchronized.)

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The
add operation runs in amortized constant time, that is, adding n elements requires O(n)
time. All of the other operations run in linear time (roughly speaking). The constant
factor is low compared to that for the LinkedList implementation.

Further reading: Java ArrayList and Iterator

LinkedList Class
Doubly-linked list implementation of the List and Deque interfaces. Implements all
optional list operations, and permits all elements (including null).

All of the operations perform as could be expected for a doubly-linked list. Operations
that index into the list will traverse the list from the beginning or the end, whichever is
closer to the specified index.

HashMap Class
Hash table based implementation of the Map interface. This implementation provides all
of the optional map operations, and permits null values and the null key. HashMap class
is roughly equivalent to Hashtable, except that it is unsynchronized and permits null.
This class makes no guarantees for the order of the map.

This implementation provides constant-time performance for the basic operations


(get and put). It provides constructors to set initial capacity and load factor for the
collection.

Further Read: HashMap vs ConcurrentHashMap

TreeMap Class
A Red-Black tree based NavigableMap implementation. The map is sorted according to
the natural ordering of its keys, or by a Comparator provided at map creation time,
depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the containsKey, get, put
and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and
Rivest’s Introduction to Algorithms.

Note that the ordering maintained by a tree map, like any sorted map, and whether or
not an explicit comparator is provided, must be consistent with equals if this sorted map
is to correctly implement the Map interface. (See Comparable or Comparator for a
precise definition of consistent with equals.) This is so because the Map interface is
defined in terms of the equals operation, but a sorted map performs all key comparisons
using its compareTo (or compare) method, so two keys that are deemed equal by this
method are, from the standpoint of the sorted map, equal. The behavior of a sorted map
is well-defined even if its ordering is inconsistent with equals; it just fails to obey the
general contract of the Map interface.

PriorityQueue Class
Queue processes it’s elements in FIFO order but sometimes we want elements to be
processed based on their priority. We can use PriorityQueue in this case and we need
to provide a Comparator implementation while instantiation the PriorityQueue.
PriorityQueue doesn’t allow null values and it’s unbounded. For more details about this,
please head over to Java Priority Queue where you can check it’s usage with a
sample program.

Collections class
This class consists exclusively of static methods that operate on or return collections. It
contains polymorphic algorithms that operate on collections, “wrappers”, which return a
new collection backed by a specified collection, and a few other odds and ends.

This class contains methods for collection framework algorithms, such as binary search,
sorting, shuffling, reverse etc.

Synchronized Wrappers
The synchronization wrappers add automatic synchronization (thread-safety) to an
arbitrary collection. Each of the six core collection interfaces — Collection, Set, List,
Map, SortedSet, and SortedMap — has one static factory method.

public static Collection synchronizedCollection(Collection c);

public static Set synchronizedSet(Set s);

public static List synchronizedList(List list);


public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);

public static SortedSet synchronizedSortedSet(SortedSet s);

public static <K,V> SortedMap<K,V>


synchronizedSortedMap(SortedMap<K,V> m);

Each of these methods returns a synchronized (thread-safe) Collection backed up by


the specified collection.

Unmodifiable wrappers
Unmodifiable wrappers take away the ability to modify the collection by intercepting all
the operations that would modify the collection and throwing
an UnsupportedOperationException. It’s main usage are;

• To make a collection immutable once it has been built. In this case, it’s good
practice not to maintain a reference to the backing collection. This absolutely
guarantees immutability.
• To allow certain clients read-only access to your data structures. You keep a
reference to the backing collection but hand out a reference to the wrapper. In this
way, clients can look but not modify, while you maintain full access.

These methods are;

public static Collection unmodifiableCollection(Collection<?


extends T> c);

public static Set unmodifiableSet(Set<? extends T> s);

public static List unmodifiableList(List<? extends T> list);

public static <K,V> Map<K, V> unmodifiableMap(Map<? extends K,


? extends V> m);

public static SortedSet unmodifiableSortedSet(SortedSet<?


extends T> s);

public static <K,V> SortedMap<K, V>


unmodifiableSortedMap(SortedMap<K, ? extends V> m);

Thread Safe Collections


Java 1.5 Concurrent package ([Link]) contains thread-safe
collection classes that allow collections to be modified while iterating. By design iterator
is fail-fast and throws ConcurrentModificationException. Some of these classes
are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

Read these posts to learn about them in more detail.

• Avoid ConcurrentModificationException
• CopyOnWriteArrayList Example
• HashMap vs ConcurrentHashMap

Collections API Algorithms


Java Collections Framework provides algorithm implementations that are commonly
used such as sorting and searching. Collections class contain these method
implementations. Most of these algorithms work on List but some of them are applicable
for all kinds of collections.

Sorting
The sort algorithm reorders a List so that its elements are in ascending order according
to an ordering relationship. Two forms of the operation are provided. The simple form
takes a List and sorts it according to its elements’ natural ordering. The second form of
sort takes a Comparator in addition to a List and sorts the elements with the
Comparator.

Shuffling
The shuffle algorithm destroys any trace of order that may have been present in a List.
That is, this algorithm reorders the List based on input from a source of randomness
such that all possible permutations occur with equal likelihood, assuming a fair source
of randomness. This algorithm is useful in implementing games of chance.

Searching
The binarySearch algorithm searches for a specified element in a sorted List. This
algorithm has two forms. The first takes a List and an element to search for (the “search
key”). This form assumes that the List is sorted in ascending order according to the
natural ordering of its elements. The second form takes a Comparator in addition to the
List and the search key, and assumes that the List is sorted into ascending order
according to the specified Comparator. The sort algorithm can be used to sort the List
prior to calling binarySearch.
Composition
The frequency and disjoint algorithms test some aspect of the composition of one or
more Collections.

• frequency: counts the number of times the specified element occurs in the
specified collection
• disjoint: determines whether two Collections are disjoint; that is, whether they
contain no elements in common

Min and Max values


The min and the max algorithms return, respectively, the minimum and maximum
element contained in a specified Collection. Both of these operations come in two
forms. The simple form takes only a Collection and returns the minimum (or maximum)
element according to the elements’ natural ordering.
The second form takes a Comparator in addition to the Collection and returns the
minimum (or maximum) element according to the specified Comparator.

Java 8 Collections API Features


Java 8 biggest changes are related to Collection APIs. Some of the important changes
and improvements are:

1. Introduction of Stream API for sequential as well as parallel processing, you


should read Java Stream API Tutorial for more details.
2. Iterable interface has been extended with forEach() default method for iterating
over a collection.
3. Lambda Expression and Functional interfaces are mostly beneficial with Collection
API classes.

Collection classes in a Nutshell


Below table provides basic details of commonly used collection classes.

Download URL: Java Collection Classes


Collection Ordering Random Key- Duplicate Null Element Thread

Access Value Elements Safety

ArrayList Yes Yes No Yes Yes No

LinkedList Yes No No Yes Yes No

HashSet No No No No Yes No

TreeSet Yes No No No No No

HashMap No Yes Yes No Yes No


TreeMap Yes Yes Yes No No No

Vector Yes Yes No Yes Yes Yes

Hashtable No Yes Yes No No Yes

Properties No Yes Yes No No Yes

Stack Yes No No Yes Yes Yes

CopyOnWriteArrayList Yes Yes No Yes Yes Yes


ConcurrentHashMap No Yes Yes No No Yes

CopyOnWriteArraySet No No No No Yes Yes

I hope this tutorial explains most of the topics in java collections framework, please share your opinion with comments.
Java Threading interview questions?
Table Of Contents
1. What do we understand by the term concurrency?
2. What is the difference between processes and threads?
3. In Java, what is a process and a thread?
4. What is a scheduler?
5. How many threads does a Java program have at least?
6. How can a Java application access the current thread?
7. What properties does each Java thread have?
8. What is the purpose of thread groups?
9. What states can a thread have and what is the meaning of each state?
10. How do we set the priority of a thread?
11. How is a thread created in Java?
12. How do we stop a thread in Java?
13. Why should a thread not be stopped by calling its method stop()?
14. Is it possible to start a thread twice?
15. What is the output of the following code?
16. What is a daemon thread?
17. Is it possible to convert a normal user thread into a daemon thread after it has been started?
18. What do we understand by busy waiting?
19. How can we prevent busy waiting?
20. Can we use [Link]() for real-time processing?
21. How can a thread be woken up that has been put to sleep before using [Link]()?
22. How can a thread query if it has been interrupted?
23. How should an InterruptedException be handled?
24. After having started a child thread, how do we wait in the parent thread for the termination of the
child thread?
25. What is the output of the following program?
26. What happens when an uncaught exception leaves the run() method?
27. What is a shutdown hook?
28. For what purposes is the keyword synchronized used?
29. What intrinsic lock does a synchronized method acquire?
30. Can a constructor be synchronized?
31. Can primitive values be used for intrinsic locks?
32. Are intrinsic locks reentrant?
33. What do we understand by an atomic operation?
34. Is the statement c++ atomic?
35. What operations are atomic in Java?
36. Is the following implementation thread-safe?
37. What do we understand by a deadlock?
38. What are the requirements for a deadlock situation?
39. Is it possible to prevent deadlocks at all?
40. Is it possible to implement a deadlock detection?
41. What is a livelock?
42. What do we understand by thread starvation?
43. Can a synchronized block cause thread starvation?
44. What do we understand by the term race condition?
45. What do we understand by fair locks?
46. Which two methods that each object inherits from [Link] can be used to implement a
simple producer/consumer scenario?
47. What is the difference between notify() and notifyAll()?
48. How it is determined which thread wakes up by calling notify()?
49. Is the following code that retrieves an integer value from some queue implementation correct?
50. Is it possible to check whether a thread holds a monitor lock on some given object?
51. What does the method [Link]() do?
52. What do you have to consider when passing object instances from one thread to another?
53. Which rules do you have to follow in order to implement an immutable class?
54. What is the purpose of the class [Link]?
55. What are possible use cases for [Link]?
56. Is it possible to improve the performance of an application by the usage of multi-threading? Name
some examples.
57. What do we understand by the term scalability?
58. Is it possible to compute the theoretical maximum speed up for an application by using multiple
processors?
59. What do we understand by lock contention?
60. Which techniques help to reduce lock contention?
61. Which technique to reduce lock contention can be applied to the following code?
62. Explain by an example the technique lock splitting.
63. What kind of technique for reducing lock contention is used by the SDK class ReadWriteLock?
64. What do we understand by lock striping?
65. What do we understand by a CAS operation?
66. Which Java classes use the CAS operation?
67. Provide an example why performance improvements for single-threaded applications can cause
performance degradation for multi-threaded applications.
68. Is object pooling always a performance improvement for multi-threaded applications?
69. What is the relation between the two interfaces Executor and ExecutorService?
70. What happens when you submit() a new task to an ExecutorService instance whose queue is already
full?
71. What is a ScheduledExecutorService?
72. Do you know an easy way to construct a thread pool with 5 threads that executes some tasks that
return a value?
73. What is the difference between the two interfaces Runnable and Callable?
74. Which are use cases for the class [Link]?
75. What is the difference between HashMap and Hashtable particularly with regard to thread-safety?
76. Is there a simple way to create a synchronized instance of an arbitrary implementation of Collection,
List or Map?
77. What is a semaphore?
78. What is a CountDownLatch?
79. What is the difference between a CountDownLatch and a CyclicBarrier?
80. What kind of tasks can be solved by using the Fork/Join framework?
81. Is it possible to find the smallest number within an array of numbers using the Fork/Join-Framework?
82. What is the difference between the two classes RecursiveTask and RecursiveAction?
83. Is it possible to perform stream operations in Java 8 with a thread pool?
84. How can we access the thread pool that is used by parallel stream operations?
72. What do we understand by the term concurrency?
Concurrency is the ability of a program to execute several computations simultaneously.
This can be achieved by distributing the computations over the available CPU cores of a
machine or even over different machines within the same network.

73. What is the difference between processes and threads?


A process is an execution environment provided by the operating system that has its own
set of private resources (e.g. memory, open files, etc.). Threads, in contrast to processes,
live within a process and share their resources (memory, open files, etc.) with the other
threads of the process. The ability to share resources between different threads makes
thread more suitable for tasks where performance is a significant requirement.

74. In Java, what is a process and a thread?


In Java, processes correspond to a running Java Virtual Machine (JVM) whereas threads live
within the JVM and can be created and stopped by the Java application dynamically at
runtime.

75. What is a scheduler?


A scheduler is the implementation of a scheduling algorithm that manages access of
processes and threads to some limited resource like the processor or some I/O channel.
The goal of most scheduling algorithms is to provide some kind of load balancing for the
available processes/threads that guarantees that each process/thread gets an appropriate
time frame to access the requested resource exclusively.

76. How many threads does a Java program have at least?


Each Java program is executed within the main thread; hence each Java application has at
least one thread.

77. 6. How can a Java application access the current thread?


The current thread can be accessed by calling the static method currentThread() of the JDK
class [Link] :
1 public class MainThread {

3 public static void main(String[] args) {

4 long id = [Link]().getId();
5 String name = [Link]().getName();

6 ...

7 }

8}

78. What properties does each Java thread have?


Each Java thread has the following properties:
• an identifier of type long that is unique within the JVM
• a name of type String
• a priority of type int
• a state of type [Link]
• a thread group the thread belongs to

79. What is the purpose of thread groups?


Each thread belongs to a group of threads. The JDK class [Link] provides
some methods to handle a whole group of Threads. With these methods we can, for
example, interrupt all threads of a group or set their maximum priority.

80. What states can a thread have and what is the meaning of each state?
• NEW: A thread that has not yet started is in this state.
• RUNNABLE: A thread executing in the Java virtual machine is in this state.
• BLOCKED: A thread that is blocked waiting for a monitor lock is in this state.
• WAITING: A thread that is waiting indefinitely for another thread to perform a particular
action is in this state.
• TIMED_WAITING: A thread that is waiting for another thread to perform an action for up to
a specified waiting time is in this state.
• TERMINATED: A thread that has exited is in this state.

81. How do we set the priority of a thread?


The priority of a thread is set by using the method setPriority(int) . To set the priority to
the maximum value, we use the constant Thread.MAX_PRIORITY and to set it to the minimum
value we use the constant Thread.MIN_PRIORITY because these values can differ between
different JVM implementations.

82. How is a thread created in Java?


Basically, there are two ways to create a thread in Java.
The first one is to write a class that extends the JDK class [Link] and call its
method start() :
01 public class MyThread extends Thread {

02

03 public MyThread(String name) {

04 super(name);

05 }

06

07 @Override

08 public void run() {

[Link]("Executing thread
09
"+[Link]().getName());

10 }

11

12 public static void main(String[] args) throws InterruptedException {

13 MyThread myThread = new MyThread("myThread");

14 [Link]();

15 }

16 }

The second way is to implement the interface [Link] and pass this
implementation as a parameter to the constructor of [Link] :
01 public class MyRunnable implements Runnable {

02

03 public void run() {

[Link]("Executing thread
04
"+[Link]().getName());

05 }

06
07 public static void main(String[] args) throws InterruptedException {

08 Thread myThread = new Thread(new MyRunnable(), "myRunnable");

09 [Link]();

10 }

11 }

83. How do we stop a thread in Java?


To stop a thread one can use a volatile reference pointing to the current thread that can be
set to null by other threads to indicate the current thread should stop its execution:
01 private static class MyStopThread extends Thread {

02 private volatile Thread stopIndicator;

03

04 public void start() {

05 stopIndicator = new Thread(this);

06 [Link]();

07 }

08

09 public void stopThread() {

10 stopIndicator = null;

11 }

12

13 @Override

14 public void run() {

15 Thread thisThread = [Link]();

16 while(thisThread == stopIndicator) {

17 try {

18 [Link](1000);
19 } catch (InterruptedException e) {

20 }

21 }

22 }

23 }

84. Why should a thread not be stopped by calling its method stop() ?

A thread should not be stopped by using the deprecated


methods stop() of [Link] , as a call of this method causes the thread to unlock
all monitors it has acquired. If any object protected by one of the released locks was in an
inconsistent state, this state gets visible to all other threads. This can cause arbitrary
behavior when other threads work this this inconsistent object.

85. Is it possible to start a thread twice?


No, after having started a thread by invoking its start() method, a second invocation
of start() will throw an IllegalThreadStateException .

86. What is the output of the following code?


01 public class MultiThreading {

02

03 private static class MyThread extends Thread {

04

05 public MyThread(String name) {

06 super(name);

07 }

08

09 @Override

10 public void run() {

11 [Link]([Link]().getName());
12 }

13 }

14

15 public static void main(String[] args) {

16 MyThread myThread = new MyThread("myThread");

17 [Link]();

18 }

19 }

The code above produces the output “main” and not “myThread”. As can be seen in line
two of the main() method, we invoke by mistake the method run() instead of start() .
Hence, no new thread is started, but the method run() gets executed within the main
thread.

87. What is a daemon thread?


A daemon thread is a thread whose execution state is not evaluated when the JVM decides
if it should stop or not. The JVM stops when all user threads (in contrast to the daemon
threads) are terminated. Hence daemon threads can be used to implement for example
monitoring functionality as the thread is stopped by the JVM as soon as all user threads
have stopped:
01 public class Example {

02

03 private static class MyDaemonThread extends Thread {

04

05 public MyDaemonThread() {

06 setDaemon(true);

07 }

08

09 @Override

10 public void run() {


11 while (true) {

12 try {

13 [Link](1);

14 } catch (InterruptedException e) {

15 [Link]();

16 }

17 }

18 }

19 }

20

21 public static void main(String[] args) throws InterruptedException {

22 Thread thread = new MyDaemonThread();

23 [Link]();

24 }

25 }

The example application above terminates even though the daemon thread is still running
in its endless while loop.

88. Is it possible to convert a normal user thread into a daemon thread after it has
been started?
A user thread cannot be converted into a daemon thread once it has been started. Invoking
the method [Link](true) on an already running thread instance causes
a IllegalThreadStateException .

89. What do we understand by busy waiting?


Busy waiting means implementations that wait for an event by performing some active
computations that let the thread/process occupy the processor although it could be
removed from it by the scheduler. An example for busy waiting would be to spend the
waiting time within a loop that determines the current time again and again until a certain
point in time is reached:
01 Thread thread = new Thread(new Runnable() {
02 @Override

03 public void run() {

04 long millisToStop = [Link]() + 5000;

05 long currentTimeMillis = [Link]();

06 while (millisToStop > currentTimeMillis) {

07 currentTimeMillis = [Link]();

08 }

09 }

10 });

90. How can we prevent busy waiting?


One way to prevent busy waiting is to put the current thread to sleep for a given amount of
time. This can be done by calling the method [Link](long) by passing the
number of milliseconds to sleep as an argument.

91. Can we use [Link]() for real-time processing?


The number of milliseconds passed to an invocation of [Link](long) is only an
indication for the scheduler how long the current thread does not need to be executed. It
may happen that the scheduler lets the thread execute again a few milliseconds earlier or
later depending on the actual implementation. Hence an invocation
of [Link]() should not be used for real-time processing.

92. How can a thread be woken up that has been put to sleep before
using [Link]() ?
The method interrupt() of [Link] interrupts a sleeping thread. The interrupted
thread that has been put to sleep by calling [Link]() is woken up by
an InterruptedException :
01 public class InterruptExample implements Runnable {

02

03 public void run() {

04 try {
05 [Link](Long.MAX_VALUE);

06 } catch (InterruptedException e) {

[Link]("["+[Link]().getName()+"]
07
Interrupted by exception!");

08 }

09 }

10

11 public static void main(String[] args) throws InterruptedException {

12 Thread myThread = new Thread(new InterruptExample(), "myThread");

13 [Link]();

14

[Link]("["+[Link]().getName()+"]
15
Sleeping in main thread for 5s...");

16 [Link](5000);

17

[Link]("["+[Link]().getName()+"]
18
Interrupting myThread");

19 [Link]();

20 }

21 }

93. How can a thread query if it has been interrupted?


If the thread is not within a method like [Link]() that would throw
an InterruptedException , the thread can query if it has been interrupted by calling either
the static method [Link]() or the method isInterrupted() that it has inherited
from [Link].

94. How should an InterruptedException be handled?


Methods like sleep() and join() throw an InterruptedException to tell the caller that
another thread has interrupted this thread. In most cases this is done in order to tell the
current thread to stop its current computations and to finish them unexpectedly. Hence
ignoring the exception by catching it and only logging it to the console or some log file is
often not the appropriate way to handle this kind of exception. The problem with this
exception is, that the method run() of the Runnable interface does not allow
that run() throws any exceptions. So just rethrowing it does not help. This means the
implementation of run() has to handle this checked exception itself and this often leads to
the fact that it its caught and ignored.

95. After having started a child thread, how do we wait in the parent thread for the
termination of the child thread?
Waiting for a thread’s termination is done by invoking the method join() on the thread’s
instance variable:
1 Thread thread = new Thread(new Runnable() {

2 @Override

3 public void run() {

5 }

6 });

7 [Link]();

8 [Link]();

96. What is the output of the following program?


01 public class MyThreads {

02

03 private static class MyDaemonThread extends Thread {

04

05 public MyDaemonThread() {

06 setDaemon(true);

07 }

08
09 @Override

10 public void run() {

11 try {

12 [Link](1000);

13 } catch (InterruptedException e) {

14 }

15 }

16 }

17

18 public static void main(String[] args) throws InterruptedException {

19 Thread thread = new MyDaemonThread();

20 [Link]();

21 [Link]();

22 [Link]([Link]());

23 }

24 }

The output of the above code is “false”. Although the instance of MyDaemonThread is a
daemon thread, the invocation of join() causes the main thread to wait until the execution
of the daemon thread has finished. Hence calling isAlive() on the thread instance reveals
that the daemon thread is no longer running.

97. What happens when an uncaught exception leaves the run() method?
I can happen that an unchecked exception escapes from the run() method. In this case
the thread is stopped by the Java Virtual Machine. It is possible to catch this exception by
registering an instance that implements the interface UncaughtExceptionHandler as an
exception handler.
This is either done by invoking the static
method [Link]([Link]) , which
tells the JVM to use the provided handler in case there was no specific handler registerd on
the thread itself, or by
invoking setUncaughtExceptionHandler([Link]) on the thread
instance itself.
98. What is a shutdown hook?
A shutdown hook is a thread that gets executed when the JVM shuts down. It can be
registered by invoking addShutdownHook(Runnable) on the Runtime instance:
1 [Link]().addShutdownHook(new Thread() {

2 @Override

3 public void run() {

5 }

6 });

99. For what purposes is the keyword synchronized used?


When you have to implement exclusive access to a resource, like some static value or some
file reference, the code that works with the exclusive resource can be embraced with a
synchronized block:
1 synchronized ([Link]) {

2 counter++;

3}

100. What intrinsic lock does a synchronized method acquire?


A synchronized method acquires the intrinsic lock for that method’s object and releases it
when the method returns. Even if the method throws an exception, the intrinsic lock is
released. Hence a synchronized method is equal to the following code:
1 public void method() {

2 synchronized(this) {

3 ...

4 }

5}

101. Can a constructor be synchronized?


No, a constructor cannot be synchronized. The reason why this leads to an syntax error is
the fact that only the constructing thread should have access to the object being
constructed.
102. Can primitive values be used for intrinsic locks?
No, primitive values cannot be used for intrinsic locks.

103. Are intrinsic locks reentrant?


Yes, intrinsic locks can be accessed by the same thread again and again. Otherwise code
that acquires a lock would have to pay attention that it does not accidently tries to acquire
a lock it has already acquired.

104. What do we understand by an atomic operation?


An atomic operation is an operation that is either executed completely or not at all.

105. Is the statement c++ atomic?


No, the incrementation of an integer variable consist of more than one operation. First we
have to load the current value of c, increment it and then finally store the new value back.
The current thread performing this incrementation may be interrupted in-between any of
these three steps, hence this operation is not atomic.

106. What operations are atomic in Java?


The Java language provides some basic operations that are atomic and that therefore can
be used to make sure that concurrent threads always see the same value:
• Read and write operations to reference variables and primitive variables (except long
and double)
• Read and write operations for all variables declared as volatile

107. Is the following implementation thread-safe?


01 public class DoubleCheckedSingleton {

02 private DoubleCheckedSingleton instance = null;

03

04 public DoubleCheckedSingleton getInstance() {

05 if(instance == null) {

06 synchronized ([Link]) {

07 if(instance == null) {

08 instance = new DoubleCheckedSingleton();


09 }

10 }

11 }

12 return instance;

13 }

14 }

The code above is not thread-safe. Although it checks the value of instance once again
within the synchronized block (for performance reasons), the JIT compiler can rearrange
the bytecode in a way that the reference to instance is set before the constructor has
finished its execution. This means the method getInstance() returns an object that may
not have been initialized completely. To make the code thread-safe, the keyword volatile
can be used since Java 5 for the instance variable. Variables that are marked as volatile get
only visible to other threads once the constructor of the object has finished its execution
completely.

108. What do we understand by a deadlock?


A deadlock is a situation in which two (or more) threads are each waiting on the other
thread to free a resource that it has locked, while the thread itself has locked a resource
the other thread is waiting on:
Thread 1: locks resource A, waits for resource B
Thread 2: locks resource B, waits for resource A

109. What are the requirements for a deadlock situation?


In general the following requirements for a deadlock can be identified:
• Mutual exclusion: There is a resource which can be accessed only by one thread at any
point in time.
• Resource holding: While having locked one resource, the thread tries to acquire another
lock on some other exclusive resource.
• No preemption: There is no mechanism, which frees the resource if one thread holds the
lock for a specific period of time.
• Circular wait: During runtime a constellation occurs in which two (or more) threads are
each waiting on the other thread to free a resource that it has locked.

110. Is it possible to prevent deadlocks at all?


In order to prevent deadlocks one (or more) of the requirements for a deadlock has to be
eliminated:
• Mutual exclusion: In some situation it is possible to prevent mutual exclusion by using
optimistic locking.
• Resource holding: A thread may release all its exclusive locks, when it does not succeed
in obtaining all exclusive locks.
• No preemption: Using a timeout for an exclusive lock frees the lock after a given amount
of time.
• Circular wait: When all exclusive locks are obtained by all threads in the same sequence,
no circular wait occurs.

111. Is it possible to implement a deadlock detection?


When all exclusive locks are monitored and modelled as a directed graph, a deadlock
detection system can search for two threads that are each waiting on the other thread to
free a resource that it has locked. The waiting threads can then be forced by some kind of
exception to release the lock the other thread is waiting on.

112. What is a livelock?


A livelock is a situation in which two or more threads block each other by responding to an
action that is caused by another thread. In contrast to a deadlock situation, where two or
more threads wait in one specific state, the threads that participate in a livelock change
their state in a way that prevents progress on their regular work. An example would be a
situation in which two threads try to acquire two locks, but release a lock they have
acquired when they cannot acquire the second lock. It may now happen that both threads
concurrently try to acquire the first thread. As only one thread succeeds, the second thread
may succeed in acquiring the second lock. Now both threads hold two different locks, but
as both want to have both locks, they release their lock and try again from the beginning.
This situation may now happen again and again.

113. What do we understand by thread starvation?


Threads with lower priority get less time for execution than threads with higher priority.
When the threads with lower priority performs a long enduring computations, it may
happen that these threads do not get enough time to finish their computations just in time.
They seem to “starve” away as threads with higher priority steal them their computation
time.

114. Can a synchronized block cause thread starvation?


The order in which threads can enter a synchronized block is not defined. So in theory it
may happen that in case many threads are waiting for the entrance to a synchronized
block, some threads have to wait longer than other threads. Hence they do not get enough
computation time to finish their work in time.

115. What do we understand by the term race condition?


A race condition describes constellations in which the outcome of some multi-threaded
implementation depends on the exact timing behavior of the participating threads. In most
cases it is not desirable to have such a kind of behavior, hence the term race condition also
means that a bug due to missing thread synchronization leads to the differing outcome. A
simple example for a race condition is the incrementation of an integer variable by two
concurrent threads. As the operation consists of more than one single and atomic
operation, it may happen that both threads read and increment the same value. After this
concurrent incrementation the amount of the integer variable is not increased by two but
only by one.

116. What do we understand by fair locks?


A fair lock takes the waiting time of the threads into account when choosing the next
thread that passes the barrier to some exclusive resource. An example implementation of a
fair lock is provided by the Java SDK: [Link] . If the
constructor with the boolean flag set to true is used, the ReentrantLock grants access to
the longest-waiting thread.

117. Which two methods that each object inherits from [Link] can be
used to implement a simple producer/consumer scenario?
When a worker thread has finished its current task and the queue for new tasks is empty, it
can free the processor by acquiring an intrinsic lock on the queue object and by calling the
method wait() . The thread will be woken up by some producer thread that has put a new
task into the queue and that again acquires the same intrinsic lock on the queue object and
calls notify() on it.

118. What is the difference between notify() and notifyAll() ?

Both methods are used to wake up one or more threads that have put themselves to sleep
by calling wait() . While notify() only wakes up one of the waiting
threads, notifyAll() wakes up all waiting threads.

119. How it is determined which thread wakes up by calling notify() ?

It is not specified which threads will be woken up by calling notify() if more than one
thread is waiting. Hence code should not rely on any concrete JVM implementation.

120. Is the following code that retrieves an integer value from some queue
implementation correct?
01 public Integer getNextInt() {

02 Integer retVal = null;

03 synchronized (queue) {
04 try {

05 while ([Link]()) {

06 [Link]();

07 }

08 } catch (InterruptedException e) {

09 [Link]();

10 }

11 }

12 synchronized (queue) {

13 retVal = [Link]();

14 if (retVal == null) {

15 [Link]("retVal is null");

16 throw new IllegalStateException();

17 }

18 }

19 return retVal;

20 }

Although the code above uses the queue as object monitor, it does not behave correctly in
a multi-threaded environment. The reason for this is that it has two separate synchronized
blocks. When two threads are woken up in line 6 by another thread that calls notifyAll() ,
both threads enter one after the other the second synchronized block. It this second block
the queue has now only one new value, hence the second thread will poll on an empty
queue and get null as return value.

121. Is it possible to check whether a thread holds a monitor lock on some


given object?
The class [Link] provides the static method [Link](Object) that
returns true if and only if the current thread holds the lock on the object given as argument
to the method invocation.

122. What does the method [Link]() do?


An invocation of the static method [Link]() gives the scheduler a hint that the
current thread is willing to free the processor. The scheduler is free to ignore this hint. As it
is not defined which thread will get the processor after the invocation of [Link]() , it
may even happen that the current thread becomes the “next” thread to be executed.

123. What do you have to consider when passing object instances from one
thread to another?
When passing objects between threads, you will have to pay attention that these objects
are not manipulated by two threads at the same time. An example would be
a Map implementation whose key/value pairs are modified by two concurrent threads. In
order to avoid problems with concurrent modifications you can design an object to be
immutable.

124. Which rules do you have to follow in order to implement an immutable


class?
• All fields should be final and private.
• There should be not setter methods.
• The class itself should be declared final in order to prevent subclasses to violate the
principle of immutability.
• If fields are not of a primitive type but a reference to another object:
• There should not be a getter method that exposes the reference directly to the caller.
• Don’t change the referenced objects (or at least changing these references is not
visisble to clients of the object).

125. What is the purpose of the class [Link] ?

As memory is shared between different threads, ThreadLocal provides a way to store and
retrieve values for each thread separately. Implementations of ThreadLocal store and
retrieve the values for each thread independently such that when thread A stores the value
A1 and thread B stores the value B1 in the same instance of ThreadLocal , thread A later on
retrieves value A1 from this ThreadLocal instance and thread B retrieves value B1.

126. What are possible use cases for [Link] ?

Instances of ThreadLocal can be used to transport information throughout the application


without the need to pass this from method to method. Examples would be the
transportation of security/login information within an instance of ThreadLocal such that it is
accessible by each method. Another use case would be to transport transaction information
or in general objects that should be accessible in all methods without passing them from
method to method.
127. Is it possible to improve the performance of an application by the usage of
multi-threading? Name some examples.
If we have more than one CPU core available, the performance of an application can be
improved by multi-threading if it is possible to parallelize the computations over the
available CPU cores. An example would be an application that should scale all images that
are stored within a local directory structure. Instead of iterating over all images one after
the other, a producer/consumer implementation can use a single thread to scan the
directory structure and a bunch of worker threads that perform the actual scaling operation.
Another example would be an application that mirrors some web page. Instead of loading
one HTML page after the other, a producer thread can parse the first HTML page and issue
the links it found into a queue. The worker threads monitor the queue and load the web
pages found by the parser. While the worker threads wait for the page to get loaded
completely, other threads can use the CPU to parse the already loaded pages and issue
new requests.

128. What do we understand by the term scalability?


Scalability means the ability of a program to improve the performance by adding further
resources to it.

129. Is it possible to compute the theoretical maximum speed up for an


application by using multiple processors?
Amdahl’s law provides a formula to compute the theoretical maximum speed up by
providing multiple processors to an application. The theoretical speedup is computed
by S(n) = 1 / (B + (1-B)/n) where n denotes the number of processors and B the
fraction of the program that cannot be executed in parallel. When n converges against
infinity, the term (1-B)/n converges against zero. Hence the formula can be reduced in this
special case to 1/B . As we can see, the theoretical maximum speedup behaves reciprocal
to the fraction that has to be executed serially. This means the lower this fraction is, the
more theoretical speedup can be achieved.

130. What do we understand by lock contention?


Lock contention occurs, when two or more threads are competing in the acquisition of a
lock. The scheduler has to decide whether it lets the thread, which has to wait sleeping and
performs a context switch to let another thread occupy the CPU, or if letting the waiting
thread busy-waiting is more efficient. Both ways introduce idle time to the inferior thread.

131. Which techniques help to reduce lock contention?


In some cases lock contention can be reduced by applying one of the following techniques:
• The scope of the lock is reduced.
• The number of times a certain lock is acquired is reduced (lock splitting).
• Using hardware supported optimistic locking operations instead of synchronization.
• Avoid synchronization where possible.
• Avoid object pooling.

132. Which technique to reduce lock contention can be applied to the following
code?
1 synchronized (map) {

2 UUID randomUUID = [Link]();

3 Integer value = [Link](42);

4 String key = [Link]();

5 [Link](key, value);

6}

The code above performs the computation of the random UUID and the conversion of the
literal 42 into an Integer object within the synchronized block, although these two lines of
code are local to the current thread and do not affect other threads. Hence they can be
moved out of the synchronized block:
1 UUID randomUUID = [Link]();

2 Integer value = [Link](42);

3 String key = [Link]();

4 synchronized (map) {

5 [Link](key, value);

6}

133. Explain by an example the technique lock splitting.


Lock splitting may be a way to reduce lock contention when one lock is used to synchronize
access to different aspects of the same application. Suppose we have a class that
implements the computation of some statistical data of our application. A first version of
this class uses the keyword synchronized in each method signature in order to guard the
internal state before corruption by multiple concurrent threads. This also means that each
method invocation may cause lock contention as other threads may try to acquire the same
lock simultaneously. But it may be possible to split the lock on the object instance into a
few smaller locks for each type of statistical data within each method. Hence thread T1 that
tries to increment the statistical data D1 does not have to wait for the lock while thread T2
simultaneously updates the data D2.
134. What kind of technique for reducing lock contention is used by the SDK
class ReadWriteLock?
The SDK class ReadWriteLock uses the fact that concurrent threads do not have to acquire a
lock when they want to read a value when no other thread tries to update the value. This is
implemented by a pair of locks, one for read-only operations and one for writing
operations. While the read-only lock may be obtained by more than one thread, the
implementation guarantees that all read operation see an updated value once the write lock
is released.

135. What do we understand by lock striping?


In contrast to lock splitting, where we introduce different locks for different aspects of the
application, lock striping uses multiple locks to guard different parts of the same data
structure. An example for this technique is the class ConcurrentHashMap from
JDK’s [Link] package. The Map implementation uses internally different
buckets to store its values. The bucket is chosen by the value’s key. ConcurrentHashMap now
uses different locks to guard different hash buckets. Hence one thread that tries to access
the first hash bucket can acquire the lock for this bucket, while another thread can
simultaneously access a second bucket. In contrast to a synchronized version
of HashMap this technique can increase the performance when different threads work on
different buckets.

136. What do we understand by a CAS operation?


CAS stands for compare-and-swap and means that the processor provides a separate
instruction that updates the value of a register only if the provided value is equal to the
current value. CAS operations can be used to avoid synchronization as the thread can try to
update a value by providing its current value and the new value to the CAS operation. If
another thread has meanwhile updated the value, the thread’s value is not equal to the
current value and the update operation fails. The thread then reads the new value and tries
again. That way the necessary synchronization is interchanged by an optimistic spin
waiting.

137. Which Java classes use the CAS operation?


The SDK classes in the
package [Link] like AtomicInteger or AtomicBoolean use internally the
CAS operation to implement concurrent incrementation.
01 public class CounterAtomic {

02 private AtomicLong counter = new AtomicLong();

03
04 public void increment() {

05 [Link]();

06 }

07

08 public long get() {

09 return [Link]();

10 }

11 }

138. Provide an example why performance improvements for single-threaded


applications can cause performance degradation for multi-threaded applications.
A prominent example for such optimizations is a List implementation that holds the
number of elements as a separate variable. This improves the performance for single-
threaded applications as the size() operation does not have to iterate over all elements
but can return the current number of elements directly. Within a multi-threaded application
the additional counter has to be guarded by a lock as multiple concurrent threads may
insert elements into the list. This additional lock can cost performance when there are more
updates to the list than invocations of the size() operation.

139. Is object pooling always a performance improvement for multi-threaded


applications?
Object pools that try to avoid the construction of new objects by pooling them can improve
the performance of single-threaded applications as the cost for object creation is
interchanged by requesting a new object from the pool. In multi-threaded applications such
an object pool has to have synchronized access to the pool and the additional costs of lock
contention may outweigh the saved costs of the additional construction and garbage
collection of the new objects. Hence object pooling may not always improve the overall
performance of a multi-threaded application.

140. What is the relation between the two interfaces Executor and
ExecutorService?
The interface Executor only defines one method: execute(Runnable) . Implementations of
this interface will have to execute the given Runnable instance at some time in the future.
The ExecutorService interface is an extension of the Executor interface and provides
additional methods to shut down the underlying implementation, to await the termination
of all submitted tasks and it allows submitting instances of Callable .
141. What happens when you submit() a new task to an ExecutorService
instance whose queue is already full?
As the method signature of submit() indicates, the ExecutorService implementation is
supposed to throw a RejectedExecutionException .

142. What is a ScheduledExecutorService?


The interface ScheduledExecutorService extends the interface ExecutorService and adds
method that allow to submit new tasks to the underlying implementation that should be
executed a given point in time. There are two methods to schedule one-shot tasks and two
methods to create and execute periodic tasks.

143. Do you know an easy way to construct a thread pool with 5 threads that
executes some tasks that return a value?
The SDK provides a factory and utility class Executors whose static
method newFixedThreadPool(int nThreads) allows the creation of a thread pool with a fixed
number of threads (the implementation of MyCallable is omitted):
public static void main(String[] args) throws InterruptedException,
01
ExecutionException {

02 ExecutorService executorService = [Link](5);

03 Future<Integer>[] futures = new Future[5];

04 for (int i = 0; i < [Link]; i++) {

05 futures[i] = [Link](new MyCallable());

06 }

07 for (int i = 0; i < [Link]; i++) {

08 Integer retVal = futures[i].get();

09 [Link](retVal);

10 }

11 [Link]();

12 }

144. What is the difference between the two interfaces Runnable and Callable?
The interface Runnable defines the method run() without any return value whereas the
interface Callable allows the method call() to return a value and to throw an exception.

145. Which are use cases for the class [Link] ?

Instances of the class [Link] are used to represent results of


asynchronous computations whose result are not immediately available. Hence the class
provides methods to check if the asynchronous computation has finished, canceling the
task and to the retrieve the actual result. The latter can be done with the
two get() methods provided. The first get() methods takes no parameter and blocks until
the result is available whereas the second get() method takes a timeout parameter that
lets the method invocation return if the result does not get available within the given
timeframe.

146. What is the difference between HashMap and Hashtable particularly with
regard to thread-safety?
The methods of Hashtable are all synchronized. This is not the case for
the HashMap implementation. Hence Hashtable is thread-safe whereas HashMap is not
thread-safe. For single-threaded applications it is therefore more efficient to use the
“newer” HashMap implementation.

147. Is there a simple way to create a synchronized instance of an arbitrary


implementation of Collection , List or Map ?
The utility class Collections provides the
methods synchronizedCollection(Collection) , synchronizedList(List) and synchronizedMap(
Map) that return a thread-safe collection/list/map that is backed by the given instance.

148. What is a semaphore?


A semaphore is a data structure that maintains a set of permits that have to be acquired by
competing threads. Semaphores can therefore be used to control how many threads access
a critical section or resource simultaneously. Hence the constructor
of [Link] takes as first parameter the number of permits the
threads compete about. Each invocation of its acquire() methods tries to obtain one of the
available permits. The method acquire() without any parameter blocks until the next permit
gets available. Later on, when the thread has finished its work on the critical resource, it
can release the permit by invoking the method release() on an instance of Semaphore.

149. What is a CountDownLatch ?

The SDK class CountDownLatch provides a synchronization aid that can be used to
implement scenarios in which threads have to wait until some other threads have reached
the same state such that all thread can start. This is done by providing a synchronized
counter that is decremented until it reaches the value zero. Having reached zero
the CountDownLatch instance lets all threads proceed. This can be either used to let all
threads start at a given point in time by using the value 1 for the counter or to wait until a
number of threads has finished. In the latter case the counter is initialized with the number
of threads and each thread that has finished its work counts the latch down by one.

150. What is the difference between a CountDownLatch and a CyclicBarrier ?

Both SDK classes maintain internally a counter that is decremented by different threads.
The threads wait until the internal counter reaches the value zero and proceed from there
on. But in contrast to the CountDownLatch the class CyclicBarrier resets the internal value
back to the initial value once the value reaches zero. As the name indicates instances
of CyclicBarrier can therefore be used to implement use cases where threads have to wait
on each other again and again.

151. What kind of tasks can be solved by using the Fork/Join framework?
The base class of the Fork/Join Framework [Link] is basically a
thread pool that executes instances of [Link] . The
class ForkJoinTask provides the two methods fork() and join() . While fork() is used to
start the asynchronous execution of the task, the method join() is used to await the result
of the computation. Hence the Fork/Join framework can be used to implement divide-and-
conquer algorithms where a more complex problem is divided into a number of smaller and
easier to solve problems.

152. Is it possible to find the smallest number within an array of numbers using
the Fork/Join-Framework?
The problem of finding the smallest number within an array of numbers can be solved by
using a divide-and-conquer algorithm. The smallest problem that can be solved very easily
is an array of two numbers as we can determine the smaller of the two numbers directly by
one comparison. Using a divide-and-conquer approach the initial array is divided into two
parts of equal length and both parts are provided to two instances of RecursiveTask that
extend the class ForkJoinTask . By forking the two tasks they get executed and either solve
the problem directly, if their slice of the array has the length two, or they again recursively
divide the array into two parts and fork two new RecursiveTasks. Finally each task instance
returns its result (either by having it computed directly or by waiting for the two subtasks).
The root tasks then returns the smallest number in the array.

153. What is the difference between the two


classes RecursiveTask and RecursiveAction ?
In contrast to RecursiveTask the method compute() of RecursiveAction does not have to
return a value. Hence RecursiveAction can be used when the action works directly on some
data structure without having to return the computed value.

154. Is it possible to perform stream operations in Java 8 with a thread pool?


Collections provide the method parallelStream() to create a stream that is processed by a
thread pool. Alternatively you can call the intermediate method parallel() on a given
stream to convert a sequential stream to a parallel counterpart.

155. How can we access the thread pool that is used by parallel stream
operations?
The thread pool used for parallel stream operations can be accessed
by [Link]() . This way we can query its level of parallelism
with [Link]() . The level cannot be changed at runtime but it can be
configured by providing the following JVM parameter: -
[Link]=5 .
Ok, so now you are ready for your interview! Don’t forget to check our FREE Academy
course Java Concurrency Essentials!
If you enjoyed this, then subscribe to our newsletter to enjoy weekly updates and
complimentary whitepapers! Also, check out JCG Academy for more advanced training!
You are welcome to contribute with your comments and we will include them in the article!
JDBC Tutorial – The ULTIMATE Guide
This tutorial is about JDBC (Java Database Connectivity), an API provided by Oracle that
allows programmers to handle different databases from Java applications: it allows
developers to establish connections to databases, defines how a specific client can access a
given database, provides mechanisms for reading, inserting, updating and deleting entries of
data in a database and takes care of transactions composed of different SQL statements.

In this article we will explain the main JDBC components like Statements, Result Sets or
Stored Procedures.

JDBC needs drivers for the different databases that programmers may want to work with;
we will explain this in detail and we will provide some examples.
JDBC comes together with Java since the beginning of times; the first release came with
the JDK 1.1 on February 1997 and since then, JDBC has been an important part of Java.
The main packages where JDBC is contained
are[Link]
[Link] and[Link]
[Link].
All the information about the last JDBC release (4.2) and its development and maintenance
can be found in the JSR 221.
All examples shown in this article have been implemented using Java 8 update 0_25 and
the Eclipse SDK version Luna 4.4. At the end of the article you can download all these
examples and some more!

Table of Contents
1. Components
2. Connections
3. Data types
4. Drivers
5. Databases
6. Result sets
7. Stored procedures
8. Statements
9. Batch commands
10. Transactions
11. CRUD commands
12. Java 8
13. Sql libraries built upon JDBC
14. Unit Testing
15. Summary
16. Download
17. Links

1. Components
The JDBC API allows programmers and Java applications to interact with databases. It
supports executing different SQL statements and handling results coming from different
data sources.
In this section we will try to summarize and list the most important JDBC components that
are part of every Java application, all of them will be explained in more detail in the next
chapters.
• First of all, Java applications need to create and establish a connection ao a specific database.
This is done using a Driver Manager, for example, one instance of the
interface [Link], or directly via a JDBC data source. For this purpose, the
[Link] can be used. As already mentioned, we will explain these
components in more in detail in the next chapters.
• Once we are connected against a database, we can use our [Link] for executing
CRUD (create, read, update, delete) SQL statements or operations. These statements are
explained afterwards in this tutorial.
• In order to execute these these operations, programmers can
use [Link] and [Link] classes. The last ones are more
efficient when executing the same statement several times and provide other benefits that we will
list in this tutorial.
The interface JDBC connection provides mechanisms to create statement instances:
PreparedStatement countriesStatement = [Link]("UPDATE
1
COUNTRIES SET NAME = ? WHERE ID = ?");
2 [Link](1, "Spain");
3 [Link](2, 123456789);
• Operations like Insert, update or delete return back the number of modified rows and nothing
else:
// countriesStatement belongs to the class Statement, returning number of
1
updated rows
2 int n = [Link]();
• Selection operations (queries) return results as rows inside a [Link]. Rows are
retrieved by name or number; results metadata is also available:
1 // countriesStatement belongs to the class Statement
ResultSet rs = [Link]("SELECT NAME, POPULATION
2
FROM COUNTRIES");
3 //rs contains the results in rows plus some metadata
4 ...
• Normally, JDBC uses connection pools for managing connections. There are different
implementations for connection pools like C3P0 or DBCP. These are groups of JDBC
connections that are used or borrowed from the applications when needed and released when the
task is finished. There is a lot of documentation about how to use and configure connection pools
within JDBC, a good tutorial can be found in the following
link[Link] .
• Other features are available while working with JDBC: Stored Procedures, Callable
Statements, Batch Processing…all these will be described in this tutorial.
2. Connections
In order to connect to a database we need to use a [Link] object. We can do
this using the getConnection() method of the [Link] class. This methods
receives the database host and credentials as parameters.
This snippet shows how to create a connection for a local MySQL database.
1 //MySQL driver is loaded
2 [Link]( "[Link]" );
3 //Connection object is created using the db host and credentials
Connection connect =
4
[Link]("jdbc:mysql://localhost/countries?"
5 + "user=root&password=root" );
A connection objects allows programmers to do the following actions:
• Creation of JDBC Statements: Using a connection object is possible to
create Statement , PreparedStatement or CallableStatement instances that offer methods to
execute different SQL statements. Here is an example of the creation of a PreparedStatement :
//the connection conn is used to create a prepared statement with the given
1
sql operation
2 PreparedStatement updateStmt = [Link]( sql );
This statement can execute the sql update passed as parameter.
• Offers the possibility to commit or rollback a given transaction. JDBC connection supports
two different ways of working: autocommit=true and autocommit=false . The first one commits
all transactions directly to the database, the second one needs an special command in order to
commit or rollback the transactions. We will see this is more detail in the related chapter in this
tutorial. The following piece of code shows how to change the auto commit mode of a JDBC
connection :
1 //it changes the mode to auto commit=false
2 [Link]( false );
• Possibility to get meta information about the database that is been used.
• Other options like batch processing, stored procedures, etc.
We will explain all these features in detail, for the moment it is good to know what a JDBC
Connection is and what can be done using JDBC Connections.

3. Data types
JDBC converts the Java data types into proper JDBC types before using them in the
database. There is a default mapping between Java and JDBC data types that provides
consistency between database implementations and drivers.

The following table contains these mappings.


SQL JDBC/Java setter getter

VARCHAR [Link] setString getString

CHAR [Link] setString getString

LONGVARCHAR [Link] setString getString

BIT boolean setBoolean getBoolean

NUMERIC BigDecimal setBigDecimal getBigDecimal

TINYINT byte setByte getByte

SMALLINT short setShort getShort

INTEGER int setInt getInt

BIGINT long setLong getLong

REAL float setFloat getFloat

FLOAT float setFloat getFloat

DOUBLE double setDouble getDouble

VARBINARY byte[ ] setBytes getBytes

BINARY byte[ ] setBytes getBytes

DATE [Link] setDate getDate

TIME [Link] setTime getTime

TIMESTAMP [Link] setTimestamp getTimestamp

CLOB [Link] setClob getClob

BLOB [Link] setBlob getBlob

ARRAY [Link] setARRAY getARRAY

REF [Link] SetRef getRef

STRUCT [Link] SetStruct getStruct


Null values are treated differently in SQL and in Java. When handling with SQL null values
in Java it is good to follow some best practices like avoiding the usage of primitive types,
since they cannot be null but converted to their default values like 0 for int, false for
booleans, etc.
Instead of that, the usage of wrapper classes for the primitive types is recommended. The
class ResultSet contains a method called wasNull() that is very useful in these scenarios.
Here is an example of its usage:
1 Statement stmt = [Link]( );
2 String sql = "SELECT NAME, POPULATION FROM COUNTRIES";
3 ResultSet rs = [Link](sql);
4
5 int id = [Link](1);
6 if( [Link]( ) ) {
7 id = 0;
8}

4. 4. Drivers
The JDBC Driver Manager, [Link] , is one of the most important elements
of the JDBC API. It is the basic service for handling a list of JDBC Drivers. It contains
mechanisms and objects that allow Java applications to connect to a desired JDBC driver. It
is in charge of managing the different types of JDBC database drivers. Summarizing the
main task of the Driver Manager is to be aware of the list of available drivers and to handle
the connection between the specific selected driver and the database.
The most frequently used method of this class is [Link]() . This
method establishes a connection to a database.
Here is an example of its use:
1 // Create the connection with the default credentials
[Link] conn =
2
[Link]("jdbc:hsqldb:mem:mydb", "SA", "" );
We can register drivers using the method [Link](). :
1 new [Link]();
2 [Link]( new [Link]() );
We can also load a driver by calling the [Link]() method:
1 // Loading the HSQLDB JDBC driver
2 [Link]( "[Link]" );
3
4 ...
5
6 // connection to JDBC using mysql driver
7 [Link]( "[Link]" );
The main difference is that the method registerDriver() needs that the driver is available
at compile time, loading the driver class does not require that the driver is available at
compile time. After JDBC 4, there is no real need of calling these methods and applications
do not need to register drivers individually neither to load the driver classes. It is also not
recommended to register drivers manually using the method registerDriver() .
Other interesting methods of the DriverManager class are getDriver(String url) , that tries
to locate the driver by a given string and getDrivers() that returns an enumeration of all
the drivers that has been previously registered in the Driver Manager:
1 Enumeration drivers = [Link]();
2 while( [Link]() )
3{
4 Driver driver = [Link]();
5 [Link]( [Link]() );
6}

5. 5. Databases
JDBC supports a large list of databases. It abstracts its differences and ways of working by
using different Drivers. The DriverManager class is in charge of loading the proper database,
after this is loaded, the code that access the database for querying and modifying data will
remain (more or less) unchanged.
Here is a list of supported databases in JDBC (officially registered within
Oracle):[Link]
In this chapter we are going to show how to use to different databases: MySQL and
HSQLDB. The first one is very well known by programmers and wide used, the second one,
HSQLDB, is a database very helpful for testing purposes that offers in memory capabilities.
We will see how to use both and we will discover that except of the loading of the proper
JDBC driver, the rest of the application remains unchanged:
MySQL example:
01 public static void main( String[] args ) throws ClassNotFoundException,
SQLException
02 {
03
04 // connection to JDBC using mysql driver
05 [Link]( "[Link]" );
Connection connect =
06
[Link]("jdbc:mysql://localhost/countries?"
07 + "user=root&password=root" );
08
09
10 selectAll( connect );
11
// close resources, in case of exception resources are not
12
properly cleared
13 ...
14
15 }
16
17 /**
18 * select statement and print out results in a JDBC result set
19 *
20 * @param conn
21 * @throws SQLException
22 */
private static void selectAll( [Link] conn
23
) throws SQLException
24 {
25 Statement statement = [Link]();
26
ResultSet resultSet = [Link]( "select * from
27
COUNTRIES" );
28
29 while( [Link]() )
30 {
31 String name = [Link]( "NAME" );
32 String population = [Link]( "POPULATION" );
33
34 [Link]( "NAME: " + name );
35 [Link]( "POPULATION: " + population );
36 }
37
38 }
In memory (HSQLDB) example:
01 public static void main( String[] args ) throws ClassNotFoundException,
SQLException
02 {
03
04 // Loading the HSQLDB JDBC driver
05 [Link]( "[Link]" );
06
07 // Create the connection with the default credentials
[Link] conn =
08
[Link]( "jdbc:hsqldb:mem:mydb", "SA", "" );
09
10 // Create a table in memory
String countriesTableSQL = "create memory table COUNTRIES (NAME
11
varchar(256) not null primary key, POPULATION varchar(256) not null);";
12
13 // execute the statement using JDBC normal Statements
14 Statement st = [Link]();
15 [Link]( countriesTableSQL );
16
// nothing is in the database because it is just in memory, non
17
persistent
18 selectAll( conn );
19
// after some insertions, the select shows something different, in
20
the next execution these
21 // entries will not be there
22 insertRows( conn );
23 selectAll( conn );
24
25 }
26
27 ...
28
29 /**
30 * select statement and print out results in a JDBC result set
31 *
32 * @param conn
33 * @throws SQLException
34 */
private static void selectAll( [Link] conn
35
) throws SQLException
36 {
37 Statement statement = [Link]();
38
ResultSet resultSet = [Link]( "select * from
39
COUNTRIES" );
40
41 while( [Link]() )
42 {
43 String name = [Link]( "NAME" );
44 String population = [Link]( "POPULATION" );
45
46 [Link]( "NAME: " + name );
47 [Link]( "POPULATION: " + population );
48 }
49
50 }
As we can see in last programs, the code of the selectAll methods is completely the
same, only the JDBC Driver loading and connection creation changes; you can imagine how
powerful this is when working in different environments. The HSQLDB version of the code
contains also the piece of code in charge of creating the in memory database and inserting
some rows, but this is just for showing and clarity purposes and can be done differently.

6. 6. Result sets
The class [Link] represents a result set of database table. It is created,
normally; by executing an SQL query (select statement using Statement or
PreparedStatement). It contains rows of data, where the data is stored. These data can be
accessed by index (starting by 1) or by attribute name:
01 // creating the result set
02 ResultSet resultSet = [Link]( "select * from COUNTRIES" );
03
04 // iterating through the results rows
05
06 while( [Link]() )
07 {
08 // accessing column values by index or name
09 String name = [Link]( "NAME" );
10 int population = [Link]( "POPULATION" );
11
12 [Link]( "NAME: " + name );
13 [Link]( "POPULATION: " + population );
14
15
16 // accessing column values by index or name
17 String name = [Link]( 1 );
18 int population = [Link]( 2 );
19
20 [Link]( "NAME: " + name );
21 [Link]( "POPULATION: " + population );
22
23
24 }
As shown before, ResultSets contain getter methods for retrieving column values for
different Java types. It also contains a cursor pointing to the current row of data. Initially,
the cursor is pointing before the first row. The next method moves the cursor to the next
row: [Link]() .
It is possible to create ResultSets with default properties like a cursor that moves forward
only and that is not updatable. If programmers would like to use other kind of properties he
can specify so in the creation of the Statement that is going to produce the result sets by
changing the arguments passed:
1 /**
* indicating result sets properties that will be created from this
2
statement: type,
3 * concunrrency and holdability
4 */
Statement statement = [Link]( ResultSet.
5
TYPE_SCROLL_INSENSITIVE,
6 ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT );
Using this kind of result sets it is possible to move the cursor in both directions and to
update or insert new data into the database using the result set with this purpose.

7. 7. Stored procedures
In this chapter we are going to explain what stored procedures are and how we can use
them within JDBC. For the examples we are going to use MySQL based stored procedures.
Stored procedures are sets of SQL statements as part of a logical unit of executiion and
performing a defined task. They are very useful while encapsulating a group of operations
to be executed on a database.
First of all we are going to create a procedure in our MySQL database, following script will
help us with this task:
01 delimiter //
02
03 CREATE PROCEDURE spanish (OUT population_out INT)
04 BEGIN
05 SELECT COUNT(*) INTO population_out FROM countries;
06 END//
07
08
09 delimiter ;
10
11 CALL simpleproc(@a);
Basically the script above creates a procedure called Spanish with one output attribute of
the type int and without input parameters. The procedure returns the count of all countries
in the database.
Once we have created the procedure we can work with it from our Java [Link]
order to call Stored Procedures we need to use special statements of the
interface [Link], these statements allow programmers to execute
stored procedures indicating the output attributes and input parameters to be used. In our
simple example, only output attributes are configured. Here is an example:
01 CallableStatement callableStatement = null;
02
03 // the procedure should be created in the database
04 String spanishProcedure = "{call spanish(?)}";
05
06 // callable statement is used
07 callableStatement = [Link]( spanishProcedure );
08
09 // out parameters, also in parameters are possible, not in this case
10 [Link]( 1, [Link] );
11
12 // execute using the callable statement method executeUpdate
13 [Link]();
14
15 // attributes are retrieved by index
16 String total = [Link]( 1 );
17
18 [Link]( "amount of spanish countries " + total );
We can appreciate how to indicate where to store the output of the procedure and how to
execute it using the method [Link]() . Stored procedures
are supported in most of the databases but their syntax and behavior may differ, that is
why there may be differences in the Java applications handling stored procedures
depending on the databases where the procedures are stored.

8. 8. Statements
As already mentioned in this tutorial, JDBC uses the interface [Link] to
execute different SQL queries and operations like insert, update or delete. This is the basic
interface that contains all the basic methods
like [Link](String) or [Link](String) .
Implementations of this interface are recommended when programmers do not need to
execute same query multiple times or when queries and statements do not need to be
parameterized. In general, we can say that this interface is suitable when executing DDL
statements (Create, Alter, Drop). These statements are not executed multiple times
normally and do not need to support different parameters.
In case programmers need better efficiency when repeating SQL queries or
parameterization they should use [Link] . This interface inherits the
basic statement interface mentioned before and offers parameterization. Because of this
functionalitiy, this interface is safer against SQL injection attacks. Here is a piece of code
showing an example of this interface:
01 [Link]( "Updating rows for " + name + "..." );
02
03 String sql = "UPDATE COUNTRIES SET POPULATION=? WHERE NAME=?";
04
05 PreparedStatement updateStmt = [Link]( sql );
06
07 // Bind values into the parameters.
08 [Link]( 1, 10000000 ); // population
09 [Link]( 2, name ); // name
10
11 // update prepared statement using executeUpdate
12 int numberRows = [Link]();
13
14 [Link]( numberRows + " rows updated..." );
Another benefit of using prepared statements is the possibility to handle non standard
objects by using the setObject() method. Here is an example:
01 PreparedStatement updateStmt2 = [Link]( sql );
02
// Bind values into the parameters using setObject, can be used for any
03
kind and type of
04 // parameter.
05 [Link]( 1, 10000000 ); // population
06 [Link]( 2, name ); // name
07
08 // update prepared statement using executeUpdate
09 numberRows = [Link]();
10
11 [Link]( numberRows + " rows updated..." );
12 [Link]();
As mentioned in the chapter related to stored procedures, another interface is available for
this purpose, it is called [Link] and extends the PreparedStatement
one.

9. 9. Batch commands
JDBC offers the possibility to execute a list of SQL statements as a batch, that is, all in a
row. Depending on what type of Statements the programmers are using the code may
differ but the general idea is the same. In the next snippet is shown how to use batch
processing with [Link] :
01 Statement statement = null;
02
03 statement = [Link]();
04
05 // adding batchs to the statement
[Link]( "update COUNTRIES set POPULATION=9000000 where
06
NAME='USA'" );
[Link]( "update COUNTRIES set POPULATION=9000000 where
07
NAME='GERMANY'" );
[Link]( "update COUNTRIES set POPULATION=9000000 where
08
NAME='ARGENTINA'" );
09
10 // usage of the executeBatch method
11 int[] recordsUpdated = [Link]();
12
13 int total = 0;
14 for( int recordUpdated : recordsUpdated )
15 {
16 total += recordUpdated;
17 }
18
19 [Link]( "total records updated by batch " + total );
And using [Link] :
01 String sql = "update COUNTRIES set POPULATION=? where NAME=?";
02
03 PreparedStatement preparedStatement = null;
04
05 preparedStatement = [Link]( sql );
06
07 [Link]( 1, 1000000 );
08 [Link]( 2, "SPAIN" );
09
10 // adding batches
11 [Link]();
12
13 [Link]( 1, 1000000 );
14 [Link]( 2, "USA" );
15
16 // adding batches
17 [Link]();
18
19 // executing all batchs
20 int[] updatedRecords = [Link]();
21 int total = 0;
22 for( int recordUpdated : updatedRecords )
23 {
24 total += recordUpdated;
25 }
26
27 [Link]( "total records updated by batch " + total );
We can see that the differences are basically the way the SQL query parameters are used
and how the queries are built, but the idea of executing several statements on one row is
the same. In the first case by using the method [Link]() ,
using [Link]() and [Link]() in the
second one.

10. 10. Transactions


JDBC supports transactions and contains methods and functionalities to implement
transaction based applications. We are going to list the most important ones in this chapter.
• [Link](boolean) : This method receives a Boolean as parameter,
in case of true (which is the default behavior), all SQL statements will be persisted automatically
in the database. In case of false, changes will not be persisted automatically, this will be done by
using the method [Link]() .
• [Link]() . This method can be only used if the auto commit is set to false
or disabled; that is, it only works on non automatic commit mode. When executing this method
all changes since last commit / rollback will be persisted in the database.
• [Link]() . This method can be used only when auto commit is
disabled. It undoes or reverts all changes done in the current transaction.
And here is an example of usage where we can see how to disable the auto commit mode
by using the method setAutoCommit(false) . All changes are committed when
calling commit() and current transaction changes are rolled back by using the
method rollback() :
01 [Link]( "[Link]" );
02 Connection connect = null;
03 try
04 {
05 // connection to JDBC using mysql driver
connect =
06
[Link]( "jdbc:mysql://localhost/countries?"
07 + "user=root&password=root" );
08 [Link]( false );
09
10 [Link]( "Inserting row for Japan..." );
String sql = "INSERT INTO COUNTRIES (NAME,POPULATION) VALUES ('JAPAN',
11
'45000000')";
12
13 PreparedStatement insertStmt = [Link]( sql );
14
15 // insert statement using executeUpdate
16 [Link]( sql );
17 [Link]();
18
19 [Link]( "Updating row for Japan..." );
// update statement using executeUpdate -> will cause an error, update
20
will not be
21 // executed becaues the row does not exist
22 sql = "UPDATE COUNTRIES SET POPULATION='1000000' WHERE NAME='JAPAN'";
23 PreparedStatement updateStmt = [Link]( sql );
24
25 [Link]( sql );
26 [Link]();
27
28 }
29 catch( SQLException ex )
30 {
31 [Link]();
32 //undoes all changes in current transaction
33 [Link]();
34 }
35 finally
36 {
37 [Link]();
38 }

11. 11. CRUD commands


CRUD comes from Create, Read, Update and Delete. JDBC supports all these operations
and commands, in this chapter we are going to show difference snippets of Java code
performing all of them:
Create Statement. It is possible to create databases using JDBC, here is an example of
creation of a in memory database:
1 // Create a table in memory
String countriesTableSQL = "create memory table COUNTRIES (NAME
2
varchar(256) not null primary key, POPULATION varchar(256) not null);";
3
4 // execute the statement using JDBC normal Statements
5 Statement st = [Link]();
6 [Link]( countriesTableSQL );
Insert Statement. Inserts are supported in JDBC. Programmers can use normal SQL syntax
and pass them to the different statement classes that JDBC offers
like Statement , PreparedStatement or CallableStatement . Here are a couple of examples:
01 Statement insertStmt = [Link]();
02
String sql = "INSERT INTO COUNTRIES (NAME,POPULATION) VALUES ('SPAIN',
03
'45Mill')";
04 [Link]( sql );
05
06 sql = "INSERT INTO COUNTRIES (NAME,POPULATION) VALUES ('USA', '200Mill')";
07 [Link]( sql );
08
sql = "INSERT INTO COUNTRIES (NAME,POPULATION) VALUES ('GERMANY',
09
'90Mill')";
10 [Link]( sql );
These statements return the number of inserted rows. The same is applicable to update
statements, here is an example of how to update a set of rows in a database:
1 [Link]( "Updating rows for " + name + "..." );
2
3 Statement updateStmt = [Link]();
4
5 // update statement using executeUpdate

6 String sql = "UPDATE COUNTRIES SET POPULATION='10000000' WHERE NAME='" +


name + "'";
7 int numberRows = [Link]( sql );
8
9 [Link]( numberRows + " rows updated..." );
The output would be:
1 Updating rows for SPAIN...
2 4 rows updated...
Select Statement. It is possible to execute any (almost) kind of SQL query using JDBC
statements. Here is a very simple example that reads all the rows of a given table and
prints them out in the standard console:
01 Statement statement = [Link]();
02
03 ResultSet resultSet = [Link]( "select * from COUNTRIES" );
04
05 while( [Link]() )
06 {
07 String name = [Link]( "NAME" );
08 String population = [Link]( "POPULATION" );
09 [Link]( "NAME: " + name );
10 [Link]( "POPULATION: " + population );
11 }
The output of this would be (depending on the database state):
1 NAME: GERMANY
2 POPULATION: 90Mill
3 NAME: SPAIN
4 POPULATION: 45Mill
5 NAME: USA
6 POPULATION: 200Mill
Delete statement. Finally, JDBC supports deletion of rows and dropping of tables and other
SQL elements. Here is a snippet showing the deletion of all rows with an specific criteria (in
this case, the name has to be “JAPAN”):
1 [Link]( "Deleting rows for JAPAN..." );
2 String sql = "DELETE FROM COUNTRIES WHERE NAME='JAPAN'";
3 PreparedStatement deleteStmt = [Link]( sql );
4
5 // delete statement using executeUpdate
6 int numberRows = [Link]( sql );
7
8 [Link]( numberRows + " rows deleted..." );
Delete statements return the number of affected rows, in this case the output would be
(depending on the database state):
1 Deleting rows for JAPAN...
2 0 rows deleted...
These examples are all very simple ones; they have been written for learning purposes but
you can imagine that you can execute more complicated SQL queries just by changing the
argument passed to the executeQuery() or executeUpdate() methods.

12. 12. Java 8


Java 8 does not contain any major change related to JDBC or the JDBC framework. But
several features of Java 8 can be applied when working with JDBC with very good results.
We are going to show some of them. For example it is possible to execute select queries in
a very different way as we are used to. Here is an example of how we do it without Java 8
features, it is more or less the same as we did in all our examples during this article:
01 // we always need to write this code
02 [Link]( "using Java 7" );
03 // connection to JDBC using mysql driver
04 [Link]( "[Link]" );
Connection connect =
05
[Link]( "jdbc:mysql://localhost/countries?"
06 + "user=root&password=root" );
07
08 // select query
PreparedStatement statement = [Link]( "select * from
09
COUNTRIES" );
10 ResultSet resultSet = [Link]();
11
12 // iterating results
13 while( [Link]() )
14 {
15 // access via name
16 Object name = [Link]( 1 );
17 Object population = [Link]( 2 );
18
19 [Link]( "Name: " + name );
20 [Link]( "Population: " + population );
21 }
22
// close resources, in case of exception resources are not properly
23
cleared
24 [Link]();
25 [Link]();
26 [Link]();
And here is a version that does the same but using Lambdas.
// select method is called and lambda expression is provided, this
1
expression will be used
2 // in the handle method of the functional interface
3 select( connect, "select * from COUNTRIES", ( resultSet ) -> {
4 [Link]( [Link]( 1 ) );
5 [Link]( [Link]( 2 ) );
6 } );
The piece of code shown above contains a select method call where the first parameter is
the Connection object, the second parameter is an SQL query and the third one is a
Lambda expression. This Lambda expression receives one parameter (instance
of ResultSet ) and prints out its first two attributes, but anything can be done with this
result set in the body of the Lambda expression. Here is the implementation of
the select() method:
public static void select( Connection connect, String sql, ResultSetHandler
01
handler ) throws SQLException
02 {
03 PreparedStatement statement = [Link]( sql );
04
05 try (ResultSet rs = [Link]())
06 {
07 while( [Link]() )
08 {
09 [Link]( rs );
10 }
11
12 }
13 }
And the functional interface ResultSetHandler :
01 @FunctionalInterface
02 public interface ResultSetHandler
03 {
04
05 /**
06 * This method will be executed by the lambda expression
07 *
08 * @param resultSet
09 * @throws SQLException
10 */
11 public void handle( ResultSet resultSet ) throws SQLException;
12
13 }
We can see here that the code is clearer and reduced drastically (or not) when using some
of the new Java 8 features.

13. 13. Sql libraries built upon JDBC


JDBC is used by several well known Java libraries to build their APIs. In this section we are
going to list some of them:
• HSQLDB (Hyper SQL Database) is a relational database management system that offers in
memory and persistent storage. It has a JDBC driver (as shown in some of the examples). It is
very useful for testing purposes because of its non persistent features and supports almost all the
SQL core features. For more information please visit[Link]
• DBUnit is an extension of JUnit. It is very useful for unit testing when databases are involved.
This framework takes care of the databases state between tests and abstract several databases
properties when testing. For downloading the sources and more documentation please
visit [Link]
• DBUtils is an Apache Commons library implemented with the goal of make the usage of
JDBC much easier. Some of the features that this library contains are: clean up of resources,
reduction of code quantity, easier and automatic population of result sets. This library is small,
transparent and fast and should be used by developers who want to work directly with JDBC.
Java 1.6 or higher is needed for using this library. For more
documentation[Link]
• Spring Data also contains a module related to JDBC. It is called Spring Data JDBC
Extensions. It offers support for the most used features of JDBC. It offers special features for
working with Oracle databases. If you want to learn more about this library please
visit [Link]
• JOOQ is a very interesting framework from the company datageekery that uses JDBC; it
generates Java code from SQL databases and offers an API to establish JDBC connections,
querying data and handle the results in an easy way. For more information please visit their git
hub account: [Link] .

14. 14. Unit Testing


When it comes to unit testing and databases there are always several questions open:
• What environment do we use for testing?
• Do we test with real data?
• Or do we use synthetic generated data?
• How do we test our databases without the proper credentials?
Several libraries can help us with these tasks. In this chapter we are going to list some of
them and provide some useful links where more information can be found:
• DBUnit: as stated before, DBUnit is a testing framework that works in collaboration with
Junit. For more information [Link]
• TestNG: This testing framework covers a lot of testing scenarios like unit testing, functional
testing, integration testing, etc. It is based on annotations. For more information about this
framework please visit their web site: [Link]
• JOOQ. This framewok provides JDBC mocking and testing capabilities. It is very well
documented and easy to use. For more information please visit [Link]

15. 15. Summary


JDBC (Java Database Connectivity) is the standard API for Database connectivity between
Java and a huge number of databases and data sources (from SQL based databases to
Excel spreadsheets). In this tutorial we tried to explain the JDBC architecture and how to
use it; we listed the main components that JDBC uses and we listed some of the drivers for
different wide used databases like MySql.
The most important points to remember are:
• Drivers are components that enable a Java application to work with a database. JDBC requires
drivers for every specific database. A list of available drivers for JDBC can be found
at [Link]
• SQL statements are sent directly to the database servers every time. JDBC contains a
mechanism called PreparedStatement with predetermined execution path that provides more
efficiency and better use of the resources.
• Result Sets are the representation used for rows coming out from a query.
• Stored Procedures are sets of SQL statements grouped together, they can be called by name
without the need to call each separately.
• Transactions are groups of SQL statements. A transaction ends
when commit() or rollback() are called. This grouping allow different to work in parallel.
• CRUD commands are create , read , update and delete commands. JDBC provide
mechanisms to execute these commands.
The tutorial contains some information related to new possibilities coming out with Java 8
related to JDBC like JOOQ; we also mentioned some important libraries implemented using
JDBC like Spring-Data or Apache DBUtils.

16. 16. Download


Download
You can download the full source code of this tutorial here: jdbc_ultimate_tutorial.

17. 17. Links


Apart of all the links and resources pointed during this article, if you are interested in
learning more about the JDBC API and its features and mechanisms, the best up to date
information source that you can find are the ones in the official Oracle web site:
• [Link]
• [Link]
40 Java Collections Interview Questions and
Answers
Java Collections Framework are the fundamental aspect of java programming language. It’s
one of the important topic for java interview questions. Here I am listing some important
questions and answers for java collections framework.

1. What is Java Collections Framework? List out some benefits of Collections framework?
2. What is the benefit of Generics in Collections Framework?
3. What are the basic interfaces of Java Collections Framework?
4. Why Collection doesn’t extend Cloneable and Serializable interfaces?
5. Why Map interface doesn’t extend Collection interface?
6. What is an Iterator?
7. What is difference between Enumeration and Iterator interface?
8. Why there is not method like [Link]() to add elements to the collection?
9. Why Iterator don’t have a method to get next element directly without moving the
cursor?
10. What is different between Iterator and ListIterator?
11. What are different ways to iterate over a list?
12. What do you understand by iterator fail-fast property?
13. What is difference between fail-fast and fail-safe?
14. How to avoid ConcurrentModificationException while iterating a collection?
15. Why there are no concrete implementations of Iterator interface?
16. What is UnsupportedOperationException?
17. How HashMap works in Java?
18. What is the importance of hashCode() and equals() methods?
19. Can we use any class as Map key?
20. What are different Collection views provided by Map interface?
21. What is difference between HashMap and Hashtable?
22. How to decide between HashMap and TreeMap?
23. What are similarities and difference between ArrayList and Vector?
24. What is difference between Array and ArrayList? When will you use Array over ArrayList?
25. What is difference between ArrayList and LinkedList?
26. Which collection classes provide random access of it’s elements?
27. What is EnumSet?
28. Which collection classes are thread-safe?
29. What are concurrent Collection Classes?
30. What is BlockingQueue?
31. What is Queue and Stack, list their differences?
32. What is Collections Class?
33. What is Comparable and Comparator interface?
34. What is difference between Comparable and Comparator interface?
35. How can we sort a list of Objects?
36. While passing a Collection as argument to a function, how can we make sure the
function will not be able to modify it?
37. How can we create a synchronized collection from given collection?
38. What are common algorithms implemented in Collections Framework?
39. What is Big-O notation? Give some examples?
40. What are best practices related to Java Collections Framework?

Java Collections Interview Questions Answers


1. What is Java Collections Framework? List out some benefits of Collections
framework?
Collections are used in every programming language and initial java release contained
few classes for collections: Vector, Stack, Hashtable, Array. But looking at the larger
scope and usage, Java 1.2 came up with Collections Framework that group all the
collections interfaces, implementations and algorithms. Java Collections have come
through a long way with usage of Generics and Concurrent Collection classes for thread-
safe operations. It also includes blocking interfaces and their implementations in java
concurrent package. Some of the benefits of collections framework are:
1. Reduced development effort by using core collection classes rather than
implementing our own collection classes.
2. Code quality is enhanced with the use of well tested collections framework
classes.
3. Reduced effort for code maintenance by using collection classes shipped with
JDK.
4. Reusability and Interoperability

2. What is the benefit of Generics in Collections Framework?


Java 1.5 came with Generics and all collection interfaces and implementations use it
heavily. Generics allow us to provide the type of Object that a collection can contain, so
if you try to add any element of other type it throws compile time error. This avoids
ClassCastException at Runtime because you will get the error at compilation. Also
Generics make code clean since we don’t need to use casting and instanceof operator. It
also adds up to runtime benefit because the bytecode instructions that do type checking
are not generated.

3. What are the basic interfaces of Java Collections Framework?


Collection is the root of the collection hierarchy. A collection represents a group of
objects known as its elements. The Java platform doesn’t provide any direct
implementations of this interface.
Set is a collection that cannot contain duplicate elements. This interface models the
mathematical set abstraction and is used to represent sets, such as the deck of cards.
List is an ordered collection and can contain duplicate elements. You can access any
element from it’s index. List is more like array with dynamic length.
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each
key can map to at most one value.
Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap and ListIterator.

4. Why Collection doesn’t extend Cloneable and Serializable interfaces?


Collection interface specifies group of Objects known as elements. How the elements are
maintained is left up to the concrete implementations of Collection. For example, some
Collection implementations like List allow duplicate elements whereas other
implementations like Set don’t. A lot of the Collection implementations have a public
clone method. However, it does’t really make sense to include it in all implementations
of Collection. This is because Collection is an abstract representation. What matters is
the implementation.
The semantics and the implications of either cloning or serializing come into play when
dealing with the actual implementation; so concrete implementation should decide how
it should be cloned or serialized, or even if it can be cloned or serialized.
So mandating cloning and serialization in all implementations is actually less flexible and
more restrictive. The specific implementation should make the decision as to whether it
can be cloned or serialized.

5. Why Map interface doesn’t extend Collection interface?


Although Map interface and it’s implementations are part of Collections Framework, Map
are not collections and collections are not Map. Hence it doesn’t make sense for Map to
extend Collection or vice versa.
If Map extends Collection interface, then where are the elements? Map contains key-
value pairs and it provides methods to retrieve list of Keys or values as Collection but it
doesn’t fit into the “group of elements” paradigm.

6. What is an Iterator?
Iterator interface provides methods to iterate over any Collection. We can get iterator
instance from a Collection using iterator method. Iterator takes the place of Enumeration
in the Java Collections Framework. Iterators allow the caller to remove elements from
the underlying collection during the iteration.

7. What is difference between Enumeration and Iterator interface?


Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very
basic and fits to basic needs. But Iterator is much safer as compared to Enumeration
because it always denies other threads to modify the collection object which is being
iterated by it.
Iterator takes the place of Enumeration in the Java Collections Framework. Iterators
allow the caller to remove elements from the underlying collection that is not possible
with Enumeration. Iterator method names have been improved to make it’s functionality
clear.

8. Why there is not method like [Link]() to add elements to the collection?
The semantics are unclear, given that the contract for Iterator makes no guarantees
about the order of iteration. Note, however, that ListIterator does provide an add
operation, as it does guarantee the order of the iteration.

9. Why Iterator don’t have a method to get next element directly without moving the
cursor?
It can be implemented on top of current Iterator interface but since it’s use will be rare,
it doesn’t make sense to include it in the interface that everyone has to implement.

10. What is different between Iterator and ListIterator?


1. We can use Iterator to traverse Set and List collections whereas ListIterator can be
used with Lists only.
2. Iterator can traverse in forward direction only whereas ListIterator can be used to
traverse in both the directions.
3. ListIterator inherits from Iterator interface and comes with extra functionalities like
adding an element, replacing an element, getting index position for previous and next
elements.

11. What are different ways to iterate over a list?


We can iterate over a list in two different ways – using iterator and using for-each loop.
01 List<String> strList = new ArrayList<>();

02 //using for-each loop

03 for(String obj : strList){

04 [Link](obj);

05 }

06 //using iterator

07 Iterator<String> it = [Link]();

08 while([Link]()){

09 String obj = [Link]();

10 [Link](obj);
11 }

Using iterator is more thread-safe because it makes sure that if underlying list elements
are modified, it will throw ConcurrentModificationException .

12. What do you understand by iterator fail-fast property?


Iterator fail-fast property checks for any modification in the structure of the underlying
collection everytime we try to get the next element. If there are any modifications found,
it throws ConcurrentModificationException . All the implementations of Iterator in
Collection classes are fail-fast by design except the concurrent collection classes like
ConcurrentHashMap and CopyOnWriteArrayList.

13. What is difference between fail-fast and fail-safe?


Iterator fail-safe property work with the clone of underlying collection, hence it’s not
affected by any modification in the collection. By design, all the collection classes
in [Link] package are fail-fast whereas collection classes in [Link] are
fail-safe. Fail-fast iterators throw ConcurrentModificationException whereas fail-safe
iterator never throws ConcurrentModificationException. Check this post
for CopyOnWriteArrayList Example.

14. How to avoid ConcurrentModificationException while iterating a collection?


We can use concurrent collection classes to avoid ConcurrentModificationException while
iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.
Check this post for ConcurrentHashMap Example.

15. Why there are no concrete implementations of Iterator interface?


Iterator interface declare methods for iterating a collection but it’s implementation is
responsibility of the Collection implementation classes. Every collection class that returns
an iterator for traversing has it’s own Iterator implementation nested class.
This allows collection classes to chose whether iterator is fail-fast or fail-safe. For
example ArrayList iterator is fail-fast whereas CopyOnWriteArrayList iterator is fail-safe.

16. What is UnsupportedOperationException?


UnsupportedOperationException is the exception used to indicate that the operation is not
supported. It’s used extensively in JDK classes, in collections
framework [Link] throws this exception for
all add and remove operations.

17. How HashMap works in Java?


HashMap stores key-value pair in [Link] static nested class implementation.
HashMap works on hashing algorithm and uses hashCode() and equals() method
in put and get [Link] we call put method by passing key-value pair, HashMap
uses Key hashCode() with hashing to find out the index to store the key-value pair. The
Entry is stored in the LinkedList, so if there are already existing entry, it uses equals()
method to check if the passed key already exists, if yes it overwrites the value else it
creates a new entry and store this key-value [Link] we call get method by passing
Key, again it uses the hashCode() to find the index in the array and then use equals()
method to find the correct Entry and return it’s value. Below image will explain these
detail clearly.

The other important things to know about HashMap are capacity, load factor, threshold
resizing. HashMap initial default capacity is 32 and load factor is 0.75. Threshold is
capacity multiplied by load factor and whenever we try to add an entry, if map size is
greater than threshold, HashMap rehashes the contents of map into a new array with a
larger capacity. The capacity is always power of 2, so if you know that you need to store
a large number of key-value pairs, for example in caching data from database, it’s good
idea to initialize the HashMap with correct capacity and load factor.

18. What is the importance of hashCode() and equals() methods?


HashMap uses Key object hashCode() and equals() method to determine the index to
put the key-value pair. These methods are also used when we try to get value from
HashMap. If these methods are not implemented correctly, two different Key’s might
produce same hashCode() and equals() output and in that case rather than storing it at
different location, HashMap will consider them same and overwrite [Link] all the
collection classes that doesn’t store duplicate data use hashCode() and equals() to find
duplicates, so it’s very important to implement them correctly. The implementation of
equals() and hashCode() should follow these rules.
1. If [Link](o2) , then [Link]() == [Link]() should always be true .
2. If [Link]() == [Link] is true, it doesn’t mean that [Link](o2) will
be true .
19. Can we use any class as Map key?We can use any class as Map Key, however
following points should be considered before using them.
0. If the class overrides equals() method, it should also override hashCode() method.
1. The class should follow the rules associated with equals() and hashCode() for all
instances. Please refer earlier question for these rules.
2. If a class field is not used in equals(), you should not use it in hashCode() method.
3. Best practice for user defined key class is to make it immutable, so that hashCode()
value can be cached for fast performance. Also immutable classes make sure that
hashCode() and equals() will not change in future that will solve any issue with
mutability.
For example, let’s say I have a class MyKey that I am using for HashMap key.
01 //MyKey name argument passed is used for equals() and hashCode()

02 MyKey key = new MyKey('Pankaj'); //assume hashCode=1234

03 [Link](key, 'Value');

04

05 // Below code will change the key hashCode() and equals()

06 // but it's location is not changed.

07 [Link]('Amit'); //assume new hashCode=7890

08

09 //below will return null, because HashMap will try to look for key

10 //in the same index as it was stored but since key is mutated,

11 //there will be no match and it will return null.

12 [Link](new MyKey('Pankaj'));

9. This is the reason why String and Integer are mostly used as HashMap keys.

20. What are different Collection views provided by Map interface?


Map interface provides three collection views:
1. Set keySet(): Returns a Set view of the keys contained in this map. The set is backed
by the map, so changes to the map are reflected in the set, and vice-versa. If the
map is modified while an iteration over the set is in progress (except through the
iterator’s own remove operation), the results of the iteration are undefined. The set
supports element removal, which removes the corresponding mapping from the map,
via the [Link], [Link], removeAll, retainAll, and clear operations. It
does not support the add or addAll operations.
2. Collection values(): Returns a Collection view of the values contained in this map.
The collection is backed by the map, so changes to the map are reflected in the
collection, and vice-versa. If the map is modified while an iteration over the collection
is in progress (except through the iterator’s own remove operation), the results of the
iteration are undefined. The collection supports element removal, which removes the
corresponding mapping from the map, via the [Link], [Link],
removeAll, retainAll and clear operations. It does not support the add or addAll
operations.
3. Set<[Link]<K, V>> entrySet(): Returns a Set view of the mappings
contained in this map. The set is backed by the map, so changes to the map are
reflected in the set, and vice-versa. If the map is modified while an iteration over the
set is in progress (except through the iterator’s own remove operation, or through the
setValue operation on a map entry returned by the iterator) the results of the
iteration are undefined. The set supports element removal, which removes the
corresponding mapping from the map, via the [Link], [Link],
removeAll, retainAll and clear operations. It does not support the add or addAll
operations.

21. What is difference between HashMap and Hashtable?


HashMap and Hashtable both implements Map interface and looks similar, however there
are following difference between HashMap and Hashtable.
1. HashMap allows null key and values whereas Hashtable doesn’t allow null key and
values.
2. Hashtable is synchronized but HashMap is not synchronized. So HashMap is better for
single threaded environment, Hashtable is suitable for multi-threaded environment.
3. LinkedHashMapwas introduced in Java 1.4 as a subclass of HashMap, so incase you
want iteration order, you can easily switch from HashMap to LinkedHashMap but that
is not the case with Hashtable whose iteration order is unpredictable.
4. HashMap provides Set of keys to iterate and hence it’s fail-fast but Hashtable provides
Enumeration of keys that doesn’t support this feature.
5. Hashtable is considered to be legacy class and if you are looking for modifications of
Map while iterating, you should use ConcurrentHashMap.

22. How to decide between HashMap and TreeMap?


For inserting, deleting, and locating elements in a Map, the HashMap offers the best
alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap
is your better alternative. Depending upon the size of your collection, it may be faster to
add elements to a HashMap, then convert the map to a TreeMap for sorted key
traversal.

23. What are similarities and difference between ArrayList and Vector?
ArrayList and Vector are similar classes in many ways.
1. Both are index based and backed up by an array internally.
2. Both maintains the order of insertion and we can get the elements in the order of
insertion.
3. The iterator implementations of ArrayList and Vector both are fail-fast by design.
4. ArrayList and Vector both allows null values and random access to element using
index number.
These are the differences between ArrayList and Vector.
5. Vector is synchronized whereas ArrayList is not synchronized. However if you are
looking for modification of list while iterating, you should use CopyOnWriteArrayList.
6. ArrayList is faster than Vector because it doesn’t have any overhead because of
synchronization.
7. ArrayList is more versatile because we can get synchronized list or read-only list from
it easily using Collections utility class.

24. What is difference between Array and ArrayList? When will you use Array over
ArrayList?
Arrays can contain primitive or Objects whereas ArrayList can contain only Objects.
Arrays are fixed size whereas ArrayList size is dynamic.
Arrays doesn’t provide a lot of features like ArrayList, such as addAll, removeAll, iterator
[Link] ArrayList is the obvious choice when we work on list, there are few times
when array are good to use.
1. If the size of list is fixed and mostly used to store and traverse them.
2. For list of primitive data types, although Collections use autoboxing to reduce the
coding effort but still it makes them slow when working on fixed size primitive data
types.
3. If you are working on fixed multi-dimensional situation, using [][] is far more easier
than List<List<>>

25. What is difference between ArrayList and LinkedList?


ArrayList and LinkedList both implement List interface but there are some differences
between them.
1. ArrayList is an index based data structure backed by Array, so it provides random
access to it’s elements with performance as O(1) but LinkedList stores data as list of
nodes where every node is linked to it’s previous and next node. So even though
there is a method to get the element using index, internally it traverse from start to
reach at the index node and then return the element, so performance is O(n) that is
slower than ArrayList.
2. Insertion, addition or removal of an element is faster in LinkedList compared to
ArrayList because there is no concept of resizing array or updating index when
element is added in middle.
3. LinkedList consumes more memory than ArrayList because every node in LinkedList
stores reference of previous and next elements.
26. Which collection classes provide random access of it’s elements?
ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements.
Download java collections pdffor more information.

27. What is EnumSet?


[Link] is Set implementation to use with enum types. All of the elements in
an enum set must come from a single enum type that is specified, explicitly or implicitly,
when the set is created. EnumSet is not synchronized and null elements are not allowed.
It also provides some useful methods like copyOf(Collection c), of(E first, E… rest) and
complementOf(EnumSet s).Check this post for java enum tutorial.

28. Which collection classes are thread-safe?


Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-
safe and can be used in multi-threaded environment. Java 1.5 Concurrent API included
some collection classes that allows modification of collection while iteration because they
work on the clone of the collection, so they are safe to use in multi-threaded
environment.

29. What are concurrent Collection Classes?


Java 1.5 Concurrent package ( [Link] ) contains thread-safe collection
classes that allow collections to be modified while iterating. By design iterator is fail-fast
and throws ConcurrentModificationException. Some of these classes
are CopyOnWriteArrayList , ConcurrentHashMap , CopyOnWriteArraySet .Read these posts to
learn about them in more detail.
1. Avoid ConcurrentModificationException
2. CopyOnWriteArrayList Example
3. HashMap vs ConcurrentHashMap

30. What is BlockingQueue?


[Link] is a Queue that supports operations that wait for the
queue to become non-empty when retrieving and removing an element, and wait for
space to become available in the queue when adding an [Link]
interface is part of java collections framework and it’s primarily used for implementing
producer consumer problem. We don’t need to worry about waiting for the space to be
available for producer or object to be available for consumer in BlockingQueue as it’s
handled by implementation classes of [Link] provides several
BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue,
PriorityBlockingQueue, SynchronousQueue etc.
Check this post for use of BlockingQueue for producer-consumer problem.

31. What is Queue and Stack, list their differences?


Both Queue and Stack are used to store data before processing them. [Link] is
an interface whose implementation classes are present in java concurrent package.
Queue allows retrieval of element in First-In-First-Out (FIFO) order but it’s not always
the case. There is also Deque interface that allows elements to be retrieved from both
end of the queue.
Stack is similar to queue except that it allows elements to be retrieved in Last-In-First-
Out (LIFO) order.
Stack is a class that extends Vector whereas Queue is an interface.

32. What is Collections Class?


[Link] is a utility class consists exclusively of static methods that operate
on or return collections. It contains polymorphic algorithms that operate on collections,
“wrappers”, which return a new collection backed by a specified collection, and a few
other odds and [Link] class contains methods for collection framework algorithms,
such as binary search, sorting, shuffling, reverse etc.

33. What is Comparable and Comparator interface?


Java provides Comparable interface which should be implemented by any custom class if
we want to use Arrays or Collections sorting methods. Comparable interface has
compareTo(T obj) method which is used by sorting methods. We should override this
method in such a way that it returns a negative integer, zero, or a positive integer if
“this” object is less than, equal to, or greater than the object passed as [Link], in
most real life scenarios, we want sorting based on different parameters. For example, as
a CEO, I would like to sort the employees based on Salary, an HR would like to sort
them based on the age. This is the situation where we need to use Comparator interface
because [Link](Object o) method implementation can sort based on one
field only and we can’t chose the field on which we want to sort the [Link]
interface compare(Object o1, Object o2) method need to be implemented that takes two
Object argument, it should be implemented in such a way that it returns negative int if
first argument is less than the second one and returns zero if they are equal and positive
int if first argument is greater than second one.
Check this post for use of Comparable and Comparator interface to sort objects.

34. What is difference between Comparable and Comparator interface?


Comparable and Comparator interfaces are used to sort collection or array of
[Link] interface is used to provide the natural sorting of objects and we
can use it to provide sorting based on single logic.
Comparator interface is used to provide different algorithms for sorting and we can
chose the comparator we want to use to sort the given collection of objects.

35. How can we sort a list of Objects?


If we need to sort an array of Objects, we can use [Link]() . If we need to sort a
list of objects, we can use [Link]() . Both these classes have overloaded sort()
methods for natural sorting (using Comparable) or sorting based on criteria (using
Comparator). Collections internally uses Arrays sorting method, so both of them have
same performance except that Collections take sometime to convert list to array.

36. While passing a Collection as argument to a function, how can we make sure the
function will not be able to modify it?
We can create a read-only collection
using [Link](Collection c) method before passing it as
argument, this will make sure that any operation to change the collection will
throw UnsupportedOperationException .

37. How can we create a synchronized collection from given collection?


We can use [Link](Collection c) to get a synchronized
(thread-safe) collection backed by the specified collection.

38. What are common algorithms implemented in Collections Framework?


Java Collections Framework provides algorithm implementations that are commonly used
such as sorting and searching. Collections class contain these method implementations.
Most of these algorithms work on List but some of them are applicable for all kinds of
collections. Some of them are sorting, searching, shuffling, min-max values.

39. What is Big-O notation? Give some examples?


The Big-O notation describes the performance of an algorithm in terms of number of
elements in a data structure. Since Collection classes are actually data structures, we
usually tend to use Big-O notation to chose the collection implementation to use based
on time, memory and [Link] 1: ArrayList get(index i) is a constant-time
operation and doesn’t depend on the number of elements in the list. So it’s performance
in Big-O notation is O(1).
Example 2: A linear search on array or list performance is O(n) because we need to
search through entire list of elements to find the element.

40. What are best practices related to Java Collections Framework?


1. Chosing the right type of collection based on the need, for example if size is fixed, we
might want to use Array over ArrayList. If we have to iterate over the Map in order of
insertion, we need to use TreeMap. If we don’t want duplicates, we should use Set.
2. Some collection classes allows to specify the initial capacity, so if we have an estimate
of number of elements we will store, we can use it to avoid rehashing or resizing.
3. Write program in terms of interfaces not implementations, it allows us to change the
implementation easily at later point of time.
4. Always use Generics for type-safety and avoid ClassCastException at runtime.
5. Use immutable classes provided by JDK as key in Map to avoid implementation of
hashCode() and equals() for our custom class.
6. Use Collections utility class as much as possible for algorithms or to get read-only,
synchronized or empty collections rather than writing own implementation. It will
enhance code-reuse with greater stability and low maintainability.
I will keep on adding more questions on java collections framework as and when I found
them, if you found it useful please share it with others too, it motivates me in writing more
like these.

Reference: 40 Java Collections Interview Questions and Answers from our JCG
partner Pankaj Kumar at the Developer Recipes blog.
Java 8 Features Tutorial – The ULTIMATE
Guide
EDITORIAL NOTE: It’s been a while since Java 8 is out in the public and everything points
to the fact that this is a really major release.

We have provided an abundance of tutorials here at Java Code Geeks, like Playing with Java
8 – Lambdas and Concurrency, Java 8 Date Time API Tutorial : LocalDateTime and Abstract
Class Versus Interface in the JDK 8 Era.

We also referenced 15 Must Read Java 8 Tutorials from other sources. Of course, we
examined some of the shortfalls also, like The Dark Side of Java 8.

Now, it is time to gather all the major Java 8 features under one reference post for your
reading pleasure. Enjoy!

41. Table Of Contents


1. Introduction

2. New Features in Java language

2.1. Lambdas and Functional Interfaces

2.2. Interface Default and Static Methods

2.3. Method References

2.4. Repeating annotations

2.5. Better Type Inference

2.6. Extended Annotations Support

3. New Features in Java compiler

3.1. Parameter names

4. New Features in Java libraries

4.1. Optional

4.2. Streams

4.3. Date/Time API (JSR 310)

4.4. Nashorn JavaScript engine

4.5. Base64
4.6. Parallel Arrays

4.7. Concurrency

5. New Java tools

5.1. Nashorn engine: jjs

5.2. Class dependency analyzer: jdeps

6. New Features in Java runtime (JVM)

7. Conclusions

8. Resources

1. Introduction
With no doubts, Java 8 release is the greatest thing in the Java world since Java 5 (released quite a
while ago, back in 2004). It brings tons of new features to the Java as a language, its compiler, libraries,
tools and the JVM (Java virtual machine) itself. In this tutorial we are going to take a look on all these
changes and demonstrate the different usage scenarios on real examples.

The tutorial consists of several parts where each one touches the specific side of the platform:

• language
• compiler
• libraries
• tools
• runtime (JVM)

2. New Features in Java language


Java 8 is by any means a major release. One might say it took so long to finalize in order to implement
the features every Java developer was looking for. In this section we are going to cover most of them.

2.1. Lambdas and Functional Interfaces


Lambdas (also known as closures) are the biggest and most awaited language change in the whole Java 8
release. They allow us to treat functionality as a method argument (passing functions around), or treat a
code as data: the concepts every functional developer is very familiar with. Many languages on JVM
platform (Groovy, Scala, …) have had lambdas since day one, but Java developers had no choice but
hammer the lambdas with boilerplate anonymous classes.

Lambdas design discussions have taken a lot of time and community efforts. But finally, the trade-offs
have been found, leading to new concise and compact language constructs. In its simplest form, a
lambda could be represented as a comma-separated list of parameters, the –> symbol and the body.
For example:

1 [Link]( "a", "b", "d" ).forEach( e -> [Link]( e ) );

Please notice the type of argument e is being inferred by the compiler. Alternatively, you
may explicitly provide the type of the parameter, wrapping the definition in brackets. For
example:
[Link]( "a", "b", "d" ).forEach( ( String e ) -> [Link](
1
e ) );

In case lambda’s body is more complex, it may be wrapped into square brackets, as the usual function
definition in Java. For example:

1 [Link]( "a", "b", "d" ).forEach( e -> {

2 [Link]( e );

3 [Link]( e );

4 } );

Lambdas may reference the class members and local variables (implicitly making them
effectively final if they are not). For example, those two snippets are equivalent:

1 String separator = ",";

2 [Link]( "a", "b", "d" ).forEach(

3 ( String e ) -> [Link]( e + separator ) );

And:
1 final String separator = ",";

2 [Link]( "a", "b", "d" ).forEach(

3 ( String e ) -> [Link]( e + separator ) );

Lambdas may return a value. The type of the return value will be inferred by compiler.
The return statement is not required if the lambda body is just a one-liner. The two code snippets
below are equivalent:

1 [Link]( "a", "b", "d" ).sort( ( e1, e2 ) -> [Link]( e2 ) );

And:
1 [Link]( "a", "b", "d" ).sort( ( e1, e2 ) -> {

2 int result = [Link]( e2 );


3 return result;

4 } );

Language designers put a lot of thought on how to make already existing functionality lambda-friendly.
As a result, the concept of functional interfaces has emerged. The function interface is an interface
with just one single method. As such, it may be implicitly converted to a lambda expression.
The [Link] and [Link] are two great examples of
functional interfaces. In practice, the functional interfaces are fragile: if someone adds just one another
method to the interface definition, it will not be functional anymore and compilation process will fail. To
overcome this fragility and explicitly declare the intent of the interface as being functional, Java 8 adds
special annotation @FunctionalInterface (all existing interfaces in Java library have been annotated with
@FunctionalInterface as well). Let us take a look on this simple functional interface definition:

1 @FunctionalInterface

2 public interface Functional {

3 void method();

4}

One thing to keep in mind: default and static methods do not break the functional interface contract
and may be declared:

1 @FunctionalInterface

2 public interface FunctionalDefaultMethods {

3 void method();

5 default void defaultMethod() {

6 }

7}

Lambdas are the largest selling point of Java 8. It has all the potential to attract more and more
developers to this great platform and provide state of the art support for functional programming
concepts in pure Java. For more details please refer to official documentation.

2.2. Interface’s Default and Static Methods


Java 8 extends interface declarations with two new concepts: default and static methods. Default
methods make interfaces somewhat similar to traits but serve a bit different goal. They allow adding
new methods to existing interfaces without breaking the binary compatibility with the code written for
older versions of those interfaces.

The difference between default methods and abstract methods is that abstract methods are required to
be implemented. But default methods are not. Instead, each interface must provide so called default
implementation and all the implementers will inherit it by default (with a possibility to override this
default implementation if needed). Let us take a look on example below.

01 private interface Defaulable {

02 // Interfaces now allow default methods, the implementer may or

03 // may not implement (override) them.

04 default String notRequired() {

05 return "Default implementation";

06 }

07 }

08

09 private static class DefaultableImpl implements Defaulable {

10 }

11

12 private static class OverridableImpl implements Defaulable {

13 @Override

14 public String notRequired() {

15 return "Overridden implementation";

16 }

17 }

The interface Defaulable declares a default method notRequired() using keyword default as
part of the method definition. One of the classes, DefaultableImpl, implements this interface
leaving the default method implementation as-is. Another one, OverridableImpl , overrides the
default implementation and provides its own.

Another interesting feature delivered by Java 8 is that interfaces can declare (and provide
implementation) of static methods. Here is an example.
1 private interface DefaulableFactory {

2 // Interfaces now allow static methods

3 static Defaulable create( Supplier< Defaulable > supplier ) {

4 return [Link]();

5 }

6}

The small code snippet below glues together the default methods and static methods from
the examples above.
1 public static void main( String[] args ) {

Defaulable defaulable = [Link](


2
DefaultableImpl::new );

3 [Link]( [Link]() );

5 defaulable = [Link]( OverridableImpl::new );

6 [Link]( [Link]() );

7}

The console output of this program looks like that:


1 Default implementation

2 Overridden implementation

Default methods implementation on JVM is very efficient and is supported by the byte code instructions
for method invocation. Default methods allowed existing Java interfaces to evolve without breaking the
compilation process. The good examples are the plethora of methods added
to [Link] interface: stream(), parallelStream(), forEach(), removeIf(), …

Though being powerful, default methods should be used with a caution: before declaring method as
default it is better to think twice if it is really needed as it may cause ambiguity and compilation errors in
complex hierarchies. For more details please refer to official documentation.

2.3. Method References


Method references provide the useful syntax to refer directly to exiting methods or constructors of Java
classes or objects (instances). With conjunction of Lambdas expressions, method references make the
language constructs look compact and concise, leaving off boilerplate.
Below, considering the class Car as an example of different method definitions, let us distinguish four
supported types of method references.

01 public static class Car {

02 public static Car create( final Supplier< Car > supplier ) {

03 return [Link]();

04 }

05

06 public static void collide( final Car car ) {

07 [Link]( "Collided " + [Link]() );

08 }

09

10 public void follow( final Car another ) {

11 [Link]( "Following the " + [Link]() );

12 }

13

14 public void repair() {

15 [Link]( "Repaired " + [Link]() );

16 }

17 }

The first type of method references is constructor reference with the syntax Class::new or
alternatively, for generics, Class< T >::new. Please notice that the constructor has no arguments.

1 final Car car = [Link]( Car::new );

2 final List< Car > cars = [Link]( car );

The second type is reference to static method with the syntax Class::static_method. Please notice
that the method accepts exactly one parameter of type Car.

1 [Link]( Car::collide );
The third type is reference to instance method of arbitrary object of specific type with the
syntax Class::method. Please notice, no arguments are accepted by the method.

1 [Link]( Car::repair );

And the last, fourth type is reference to instance method of particular class instance the
syntax instance::method. Please notice that method accepts exactly one parameter of type Car.

1 final Car police = [Link]( Car::new );

2 [Link]( police::follow );

Running all those examples as a Java program produces following output on a console (the
actual Car instances might be different):

Collided
1
[Link]$Car@7a81197d

Repaired
2
[Link]$Car@7a81197d

Following the
3
[Link]$Car@7a81197d

For more examples and details on method references, please refer to official documentation.

2.4. Repeating annotations


Since Java 5 introduced the annotations support, this feature became very popular and is very widely
used. However, one of the limitations of annotation usage was the fact that the same annotation cannot
be declared more than once at the same location. Java 8 breaks this rule and introduced the repeating
annotations. It allows the same annotation to be repeated several times in place it is declared.

The repeating annotations should be themselves annotated with @Repeatable annotation. In fact, it is
not a language change but more a compiler trick as underneath the technique stays the same. Let us
take a look on quick example:

01 package [Link];

02

03 import [Link];

04 import [Link];

05 import [Link];

06 import [Link];
07 import [Link];

08

09 public class RepeatingAnnotations {

10 @Target( [Link] )

11 @Retention( [Link] )

12 public @interface Filters {

13 Filter[] value();

14 }

15

16 @Target( [Link] )

17 @Retention( [Link] )

18 @Repeatable( [Link] )

19 public @interface Filter {

20 String value();

21 };

22

23 @Filter( "filter1" )

24 @Filter( "filter2" )

25 public interface Filterable {

26 }

27

28 public static void main(String[] args) {

for( Filter filter: [Link](


29
[Link] ) ) {

30 [Link]( [Link]() );

31 }
32 }

33 }

As we can see, there is an annotation class Filter annotated with @Repeatable( [Link] ).
The Filters is just a holder of Filter annotations but Java compiler tries hard to hide its presence from
the developers. As such, the interface Filterable has Filter annotation defined twice (with no
mentions of Filters).

Also, the Reflection API provides new method getAnnotationsByType() to return repeating
annotations of some type (please notice that [Link]( [Link] ) will return
the instance of Filters injected by the compiler).

The program output looks like that:


1 filter1

2 filter2

For more details please refer to official documentation.

2.5. Better Type Inference


Java 8 compiler has improved a lot on type inference. In many cases the explicit type parameters could
be inferred by compiler keeping the code cleaner. Let us take a look on one of the examples.

01 package [Link];

02

03 public class Value< T > {

04 public static< T > T defaultValue() {

05 return null;

06 }

07

08 public T getOrDefault( T value, T defaultValue ) {

09 return ( value != null ) ? value : defaultValue;

10 }

11 }

And here is the usage of Value< String > type.


1 package [Link];

3 public class TypeInference {

4 public static void main(String[] args) {

5 final Value< String > value = new Value<>();

6 [Link]( "22", [Link]() );

7 }

8}

The type parameter of [Link]()is inferred and is not required to be provided. In Java
7, the same example will not compile and should be rewritten to Value.< String
>defaultValue().

2.6. Extended Annotations Support


Java 8 extends the context where annotation might be used. Now, it is possible to annotate mostly
everything: local variables, generic types, super-classes and implementing interfaces, even the method’s
exceptions declaration. Couple of examples are show below.

01 package [Link];

02

03 import [Link];

04 import [Link];

05 import [Link];

06 import [Link];

07 import [Link];

08 import [Link];

09

10 public class Annotations {

11 @Retention( [Link] )
12 @Target( { ElementType.TYPE_USE, ElementType.TYPE_PARAMETER } )

13 public @interface NonEmpty {

14 }

15

16 public static class Holder< @NonEmpty T > extends @NonEmpty Object {

17 public void method() throws @NonEmpty Exception {

18 }

19 }

20

21 @SuppressWarnings( "unused" )

22 public static void main(String[] args) {

final Holder< String > holder = new @NonEmpty Holder< String


23
>();

@NonEmpty Collection< @NonEmpty String > strings


24
= new ArrayList<>();

25 }

26 }

The ElementType.TYPE_USE and ElementType.TYPE_PARAMETER are two new element


types to describe the applicable annotation context. The Annotation Processing API also
underwent some minor changes to recognize those new type annotations in the Java programming
language.

3. New Features in Java compiler


3.1. Parameter names
Literally for ages Java developers are inventing different ways to preserve method parameter names
in Java byte-code and make them available at runtime (for example, Paranamer library). And finally,
Java 8 bakes this demanding feature into the language (using Reflection API
and [Link]() method) and the byte-code (using new javac compiler argument –
parameters).
01 package [Link];

02

03 import [Link];

04 import [Link];

05

06 public class ParameterNames {

07 public static void main(String[] args) throws Exception {

Method method = [Link]( "main",


08
String[].class );

09 for( final Parameter parameter: [Link]() ) {

10 [Link]( "Parameter: " + [Link]() );

11 }

12 }

13 }

If you compile this class without using –parameters argument and then run this program, you will
see something like that:

1 Parameter: arg0

With –parameters argument passed to the compiler the program output will be different (the actual
name of the parameter will be shown):

1 Parameter: args

For experienced Maven users the –parameters argument could be added to the compiler
using configuration section of the maven-compiler-plugin:
01 <plugin>

02 <groupId>[Link]</groupId>

03 <artifactId>maven-compiler-plugin</artifactId>

04 <version>3.1</version>

05 <configuration>

06 <compilerArgument>-parameters</compilerArgument>
07 <source>1.8</source>

08 <target>1.8</target>

09 </configuration>

10 </plugin>

Latest Eclipse Kepler SR2 release with Java 8 (please check out this download instructions)
support provides useful configuration option to control this compiler setting as the picture below shows.

Picture 1. Configuring Eclipse projects to support new Java 8 compiler –


parameters argument.
Additionally, to verify the availability of parameter names, there is a handy
method isNamePresent() provided by Parameter class.

4. New Features in Java libraries


Java 8 adds a lot of new classes and extends existing ones in order to provide better support of modern
concurrency, functional programming, date/time, and many more.

4.1. Optional
The famous NullPointerException is by far the most popular cause of Java application failures.
Long time ago the great Google Guava project introduced the Optionals as a solution
to NullPointerExceptions, discouraging codebase pollution with null checks and encouraging
developers to write cleaner code. Inspired by Google Guava, the Optional is now a part of Java 8
library.

Optional is just a container: it can hold a value of some type T or just be null. It provides a lot of
useful methods so the explicit null checks have no excuse anymore. Please refer to official Java 8
documentation for more details.

We are going to take a look on two small examples of Optional usages: with the nullable value and
with the value which does not allow nulls.

1 Optional< String > fullName = [Link]( null );

2 [Link]( "Full Name is set? " + [Link]() );

3 [Link]( "Full Name: " + [Link]( () -> "[none]" ) );

[Link]( [Link]( s -> "Hey " + s + "!" ).orElse( "Hey


4
Stranger!" ) );

The isPresent() method returns true if this instance of Optional has non-null value
and false otherwise. The orElseGet() method provides the fallback mechanism in
case Optional has null value by accepting the function to generate the default one.
The map() method transforms the current Optional’s value and returns the new Optionalinstance.
The orElse() method is similar to orElseGet() but instead of function it accepts the default value.
Here is the output of this program:

1 Full Name is set? false

2 Full Name: [none]

3 Hey Stranger!

Let us briefly look on another example:


1 Optional< String > firstName = [Link]( "Tom" );

2 [Link]( "First Name is set? " + [Link]() );

[Link]( "First Name: " + [Link]( () -> "[none]" )


3
);

[Link]( [Link]( s -> "Hey " + s + "!" ).orElse( "Hey


4
Stranger!" ) );

5 [Link]();

And here is the output:


1 First Name is set? true

2 First Name: Tom

3 Hey Tom!

For more details please refer to official documentation.

4.2. Streams
The newly added Stream API ([Link]) introduces real-world functional-style
programming into the Java. This is by far the most comprehensive addition to Java library intended to
make Java developers significantly more productive by allowing them to write effective, clean, and
concise code.

Stream API makes collections processing greatly simplified (but it is not limited to Java collections only
as we will see later). Let us take start off with simple class called Task.

01 public class Streams {

02 private enum Status {

03 OPEN, CLOSED

04 };

05

06 private static final class Task {

07 private final Status status;

08 private final Integer points;

09

10 Task( final Status status, final Integer points ) {

11 [Link] = status;

12 [Link] = points;

13 }

14

15 public Integer getPoints() {

16 return points;
17 }

18

19 public Status getStatus() {

20 return status;

21 }

22

23 @Override

24 public String toString() {

25 return [Link]( "[%s, %d]", status, points );

26 }

27 }

28 }

Task has some notion of points (or pseudo-complexity) and can be either OPEN or CLOSED. And then
let us introduce a small collection of tasks to play with.

1 final Collection< Task > tasks = [Link](

2 new Task( [Link], 5 ),

3 new Task( [Link], 13 ),

4 new Task( [Link], 8 )

5 );

The first question we are going to address is how many points in total all OPEN tasks have? Up to Java
8, the usual solution for it would be some sort of foreach iteration. But in Java 8 the answers is
streams: a sequence of elements supporting sequential and parallel aggregate operations.

1 // Calculate total points of all active tasks using sum()

2 final long totalPointsOfOpenTasks = tasks

3 .stream()

4 .filter( task -> [Link]() == [Link] )

5 .mapToInt( Task::getPoints )
6 .sum();

8 [Link]( "Total points: " + totalPointsOfOpenTasks );

And the output on the console looks like that:

1 Total points: 18

There are a couple of things going on here. Firstly, the tasks collection is converted to its stream
representation. Then, the filter operation on stream filters out all CLOSED tasks. On next step,
the mapToInt operation converts the stream of Tasks to the stream of Integers
using Task::getPoints method of the each task instance. And lastly, all points are summed up
using sum method, producing the final result.

Before moving on to the next examples, there are some notes to keep in mind about streams (more
details here). Stream operations are divided into intermediate and terminal operations.
Intermediate operations return a new stream. They are always lazy, executing an intermediate
operation such as filterdoes not actually perform any filtering, but instead creates a new stream that,
when traversed, contains the elements of the initial stream that match the given predicate

Terminal operations, such as forEach or sum, may traverse the stream to produce a result or a side-
effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can
no longer be used. In almost all cases, terminal operations are eager, completing their traversal of the
underlying data source.

Yet another value proposition of the streams is out-of-the box support of parallel processing. Let us take
a look on this example, which does sums the points of all the tasks.

1 // Calculate total points of all tasks

2 final double totalPoints = tasks

3 .stream()

4 .parallel()

5 .map( task -> [Link]() ) // or map( Task::getPoints )

6 .reduce( 0, Integer::sum );

8 [Link]( "Total points (all tasks): " + totalPoints );

It is very similar to the first example except the fact that we try to process all the tasks in parallel and
calculate the final result using reduce method.
Here is the console output:

1 Total points (all tasks): 26.0

Often, there is a need to performing a grouping of the collection elements by some criteria. Streams can
help with that as well as an example below demonstrates.

1 // Group tasks by their status

2 final Map< Status, List< Task > > map = tasks

3 .stream()

4 .collect( [Link]( Task::getStatus ) );

5 [Link]( map );

The console output of this example looks like that:


1 {CLOSED=[[CLOSED, 8]], OPEN=[[OPEN, 5], [OPEN, 13]]}

To finish up with the tasks example, let us calculate the overall percentage (or weight) of each task
across the whole collection, based on its points.

01 // Calculate the weight of each tasks (as percent of total points)

02 final Collection< String > result = tasks

03 .stream() // Stream< String >

04 .mapToInt( Task::getPoints ) // IntStream

05 .asLongStream() // LongStream

06 .mapToDouble( points -> points / totalPoints ) // DoubleStream

07 .boxed() // Stream< Double >

08 .mapToLong( weigth -> ( long )( weigth * 100 ) ) // LongStream

09 .mapToObj( percentage -> percentage + "%" ) // Stream< String>

10 .collect( [Link]() ); // List< String >

11

12 [Link]( result );

The console output is just here:


1 [19%, 50%, 30%]
And lastly, as we mentioned before, the Stream API is not only about Java collections. The typical I/O
operations like reading the text file line by line is a very good candidate to benefit from stream
processing. Here is a small example to confirm that.

1 final Path path = new File( filename ).toPath();

try( Stream< String > lines = [Link]( path, StandardCharsets.UTF_8 ) )


2
{

[Link]( () -> [Link]("Done!") ).forEach(


3
[Link]::println );

4}

The onClose method called on the stream returns an equivalent stream with an additional close
handler. Close handlers are run when the close() method is called on the stream.

Stream API together with Lambdas and Method References baked by Interface’s Default and
Static Methods is the Java 8 response to the modern paradigms in software development. For more
details, please refer to official documentation.

4.3. Date/Time API (JSR 310)


Java 8 makes one more take on date and time management by delivering New Date-Time API (JSR
310). Date and time manipulation is being one of the worst pain points for Java developers. The
standard [Link] followed by [Link] hasn’t improved the situation at all
(arguably, made it even more confusing).

That is how Joda-Time was born: the great alternative date/time API for Java. The Java 8’s New Date-
Time API (JSR 310)was heavily influenced by Joda-Time and took the best of it. The
new [Link] package contains all the classes for date, time, date/time, time zones,
instants, duration, and clocks manipulation. In the design of the API the immutability has been
taken into account very seriously: no change allowed (the tough lesson learnt
from [Link]). If the modification is required, the new instance of respective class will be
returned.

Let us take a look on key classes and examples of their usages. The first class is Clock which provides
access to the current instant, date and time using a time-zone. Clock can be used instead
of [Link]() and [Link]().

1 // Get the system clock as UTC offset

2 final Clock clock = [Link]();

3 [Link]( [Link]() );

4 [Link]( [Link]() );
The sample output on a console:
1 2014-04-12T[Link].282Z

2 1397315969360

Other new classes we are going to look at are LocaleDate and LocalTime. LocaleDate holds
only the date part without a time-zone in the ISO-8601 calendar system.
Respectively, LocaleTime holds only the time part without time-zone in the ISO-8601 calendar
system. Both LocaleDate and LocaleTime could be created from Clock.

01 // Get the local date and local time

02 final LocalDate date = [Link]();

03 final LocalDate dateFromClock = [Link]( clock );

04

05 [Link]( date );

06 [Link]( dateFromClock );

07

08 // Get the local date and local time

09 final LocalTime time = [Link]();

10 final LocalTime timeFromClock = [Link]( clock );

11

12 [Link]( time );

13 [Link]( timeFromClock );

The sample output on a console:


1 2014-04-12

2 2014-04-12

3 [Link].568

4 [Link].568

The LocalDateTime combines together LocaleDate and LocalTime and holds a date with time
but without a time-zone in the ISO-8601 calendar system. A quick example is shown below.

1 // Get the local date/time


2 final LocalDateTime datetime = [Link]();

3 final LocalDateTime datetimeFromClock = [Link]( clock );

5 [Link]( datetime );

6 [Link]( datetimeFromClock );

The sample output on a console:


1 2014-04-12T[Link].309

2 2014-04-12T[Link].309

If case you need a date/time for particular timezone, the ZonedDateTime is here to help. It holds a
date with time and with a time-zone in the ISO-8601 calendar system. Here are a couple of examples for
different timezones.

1 // Get the zoned date/time

2 final ZonedDateTime zonedDatetime = [Link]();

3 final ZonedDateTime zonedDatetimeFromClock = [Link]( clock );

final ZonedDateTime zonedDatetimeFromZone = [Link](


4
[Link]( "America/Los_Angeles" ) );

6 [Link]( zonedDatetime );

7 [Link]( zonedDatetimeFromClock );

8 [Link]( zonedDatetimeFromZone );

The sample output on a console:


1 2014-04-12T[Link].017-04:00[America/New_York]

2 2014-04-12T[Link].017Z

3 2014-04-12T[Link].017-07:00[America/Los_Angeles]

And finally, let us take a look on Duration class: an amount of time in terms of seconds and
nanoseconds. It makes very easy to compute the different between two dates. Let us take a look on
that.

1 // Get duration between two dates


final LocalDateTime from = [Link]( 2014,
2
[Link], 16, 0, 0, 0 );

final LocalDateTime to = [Link]( 2015,


3
[Link], 16, 23, 59, 59 );

5 final Duration duration = [Link]( from, to );

6 [Link]( "Duration in days: " + [Link]() );

7 [Link]( "Duration in hours: " + [Link]() );

The example above computes the duration (in days and hours) between two dates, 16
April 2014 and 16 April 2015. Here is the sample output on a console:
1 Duration in days: 365

2 Duration in hours: 8783

The overall impression about Java 8’s new date/time API is very, very positive. Partially, because of the
battle-proved foundation it is built upon (Joda-Time), partially because this time it was finally tackled
seriously and developer voices have been heard. For more details please refer to official
documentation.

4.4. Nashorn JavaScript engine


Java 8 comes with new Nashorn JavaScript engine which allows developing and running certain
kinds of JavaScript applications on JVM. Nashorn JavaScript engine is just another implementation of
[Link] and follows the same set of rules, permitting Java and JavaScript
interoperability. Here is a small example.

1 ScriptEngineManager manager = new ScriptEngineManager();

2 ScriptEngine engine = [Link]( "JavaScript" );

4 [Link]( [Link]().getName() );

[Link]( "Result:" + [Link]( "function f() { return 1; };


5
f() + 1;" ) );

The sample output on a console:


1 [Link]

2 Result: 2
We will get back to the Nashorn later in the section dedicated to new Java tools.

4.5. Base64
Finally, the support of Base64 encoding has made its way into Java standard library with Java 8
release. It is very easy to use as following example shows off.

01 package [Link].java8.base64;

02

03 import [Link];

04 import [Link].Base64;

05

06 public class Base64s {

07 public static void main(String[] args) {

08 final String text = "Base64 finally in Java 8!";

09

10 final String encoded = Base64

11 .getEncoder()

12 .encodeToString( [Link]( StandardCharsets.UTF_8 ) );

13 [Link]( encoded );

14

15 final String decoded = new String(

16 [Link]().decode( encoded ),

17 StandardCharsets.UTF_8 );

18 [Link]( decoded );

19 }

20 }

The console output from program run shows both encoded and decoded text:

1 QmFzZTY0IGZpbmFsbHkgaW4gSmF2YSA4IQ==
2 Base64 finally in Java 8!

There are also URL-friendly encoder/decoder and MIME-friendly encoder/decoder provided by the
Base64 class
([Link]() / [Link](), [Link]() / B
[Link]()).

4.6. Parallel Arrays


Java 8 release adds a lot of new methods to allow parallel arrays processing. Arguably, the most
important one is parallelSort() which may significantly speedup the sorting on multicore machines.
The following small example demonstrates this new method family (parallelXxx) in action.

01 package [Link];

02

03 import [Link];

04 import [Link];

05

06 public class ParallelArrays {

07 public static void main( String[] args ) {

08 long[] arrayOfLong = new long [ 20000 ];

09

10 [Link]( arrayOfLong,

11 index -> [Link]().nextInt( 1000000 ) );

12 [Link]( arrayOfLong ).limit( 10 ).forEach(

13 i -> [Link]( i + " " ) );

14 [Link]();

15

16 [Link]( arrayOfLong );

17 [Link]( arrayOfLong ).limit( 10 ).forEach(

18 i -> [Link]( i + " " ) );


19 [Link]();

20 }

21 }

This small code snippet uses method parallelSetAll() to fill up arrays with 20000 random values.
After that, the parallelSort() is being applied. The program outputs first 10 elements before and
after sorting so to ensure the array is really ordered. The sample program output may look like that
(please notice that array elements are randomly generated):

1 Unsorted: 591217 891976 443951 424479 766825 351964 242997 642839 119108 552378

2 Sorted: 39 220 263 268 325 607 655 678 723 793

4.7. Concurrency
New methods have been added to the [Link] class to
support aggregate operations based on the newly added streams facility and lambda expressions. Also,
new methods have been added to the [Link] class to support a
common pool (check also our free course on Java concurrency).

The new [Link] class has been added to provide a


capability-based lock with three modes for controlling read/write access (it might be considered as
better alternative for infamous [Link]).

New classes have been added to the [Link] package:

• DoubleAccumulator
• DoubleAdder
• LongAccumulator
• LongAdder

5. New Java tools


Java 8 comes with new set of command line tools. In this section we are going to look over most
interesting of them.

5.1. Nashorn engine: jjs


jjs is a command line based standalone Nashorn engine. It accepts a list of JavaScript source code files
as arguments and runs them. For example, let us create a file [Link] with following content:

1 function f() {

2 return 1;
3 };

5 print( f() + 1 );

To execute this fie from command, let us pass it as an argument to jjs:

1 jjs [Link]

The output on the console will be:


12

For more details please refer to official documentation.

5.2. Class dependency analyzer: jdeps


jdeps is a really great command line tool. It shows the package-level or class-level dependencies of
Java class files. It accepts .class file, a directory, or JAR file as an input. By default, jdeps outputs
the dependencies to the system output (console).

As an example, let us take a look on dependencies report for the popular Spring Framework library. To
make example short, let us analyze only one JAR file: [Link]-
[Link].
1 jdeps [Link]

This command outputs quite a lot so we are going to look on the part of it. The dependencies are
grouped by packages. If dependency is not available on a classpath, it is shown as not found.

[Link] -> C:\Program


01
Files\Java\jdk1.8.0\jre\lib\[Link]

02 [Link] ([Link])

03 -> [Link]

04 -> [Link]

05 -> [Link]

06 -> [Link]

07 -> [Link]

08 -> [Link]

09 -> [Link]

10 -> [Link] not found


11 -> [Link] not found

12 -> [Link] not found

[Link] ([Link]-
13
[Link])

14 -> [Link]

15 -> [Link]

16 -> [Link]

17 -> [Link]

For more details please refer to official documentation.

6. New Features in Java runtime (JVM)


The PermGen space is gone and has been replaced with Metaspace (JEP 122). The JVM
options -XX:PermSize and –XX:MaxPermSize have been replaced by -
XX:MetaSpaceSize and -XX:MaxMetaspaceSize respectively.

7. Conclusions
The future is here: Java 8 moves this great platform forward by delivering the features to make
developers much more productive. It is too early to move the production systems to Java 8 but in the
next couples of months its adoption should slowly start growing. Nevertheless the time is right to start
preparing your code bases to be compatible with Java 8 and to be ready to turn the switch once Java 8
proves to be safe and stable enough.

As a confirmation of community Java 8 acceptance, recently Pivotal released Spring Framework 4.0.3
with production-ready Java 8 support.

If you enjoyed this, then subscribe to our newsletter to enjoy weekly updates and
complimentary whitepapers! Also, check out our courses for more advanced training!

You are welcome to contribute with your comments about the exciting new Java 8 features!

8. Resources
Some additional resources which discuss in depth different aspects of Java 8 features:

• Java 8 Tutorials on JCG Examples: [Link]


• What’s New in JDK 8: [Link]
[Link]
• The Java Tutorials: [Link]
• WildFly 8, JDK 8, NetBeans 8, Java EE 7: [Link]
jdk8-netbeans8-javaee7-excellent-combo-enterprise-java/
• Java 8 Tutorial: [Link]
• JDK 8 Command-line Static Dependency
Checker: [Link]
• The Illuminating Javadoc of JDK
8: [Link]
• The Dark Side of Java 8: [Link]
java-8/
• Installing Java™ 8 Support in Eclipse Kepler
SR2: [Link]
• Java 8: [Link]
• Oracle Nashorn. A Next-Generation JavaScript Engine for the
JVM: [Link]
Top 20 Libraries and APIs Java Developer
should know
Posted by: Javin Paul in Core Java January 11th, 2018

One of the traits of a good and experienced Java developer is the extensive knowledge
of API, including JDK and third-party libraries. I spent a good deal of time learning API,
especially after reading Effective Java 3rd Edition, where Joshua Bloch has advised to
use existing API for development rather than writing new pieces of code for common
stuff. That advise making sense to me because of the testing exposure these 2nd party
libraries get. In this article, I am going to share some of the most useful and essential
libraries and API, a Java developer should be familiar with. Btw, I am not including
frameworks e.g. Springand Hibernate because they are pretty well known and have
specific features.
I am generally including useful libraries for day to day stuff e.g. logging libraries like
Log4j, JSON parsing libraries like Jackson, and unit testing API e.g. JUnit and Mockito.
If you need to use them in your project then you can either include JARs of these
libraries in your project’s classpath to start using them or you can use Maven for
dependency management.
When you use Maven for dependency management, then it will automatically download
these libraries, including the libraries they depend, known as the transitive dependency.
For example, if you download Spring Framework then it will also download all other
JARs on which Spring is dependent e.g. Log4j etc.
You might not realize but having the right version of dependent JARs is a big headache.
If you have wrong versions of the JAR then you will
get ClassNotFoundException or NoClassDefFoundError,
or UnsupportedClassVersionError.
20 Useful Open Source libraries for Java
Programmers
Here is my collection of some of the useful third-party libraries Java developers can use
in their application to do a lot of useful tasks. In order to use these libraries, Java
developer should also be familiar with that and this is the whole point of this article. If
you have an idea then you can research about that library and use it.
1. Logging libraries
Logging libraries are very common because you need them in every project. They are
the most important thing for server-side application because logs are only placed where
you can see what’s going on your application. Even though JDK ships with its own
logging library, there are many better alternatives are available e.g. Log4j, SLF4j, and
LogBack.
A Java developer should be familiar with pros and cons of logging library and
know why using SLF4j is better than plain Log4j. If you don’t know why I suggest you
read my earlier article on the same subject.
2. JSON parsing libraries
In today’s world of web services and internet of things (IoT), JSON has become the go-
to protocol to carry information from client to server. They have replaced the XML as
the most preferred way to transfer information in a platform-independent way.
Unfortunately JDK doesn’t have a JSON library yet but fortunately, there are many good
third-party libraries which allows you to both parse and create JSON messages e.g.
Jackson and Gson.

A Java web developer should be familiar with at least one of these libraries. If you want
to know more about Jackson and JSON, I suggest going through JSON with Java
API course from Udemy, which they are offering in just $10.99 on their New Year Sale.
3. Unit testing libraries
Unit testing is the single most important thing which separates an average developer
from a good developer. Programmers often are given excuses for not writing unit tests
but the most common
excuse for avoiding unit testing is lack of experience and knowledge of popular unit
testing library e.g. JUnit, Mockito, and PowerMock.
I have a goal in 2018 to improve my knowledge of unit testing and integration testing
libraries e.g. JUnit 5, Cucumber, Robot framework etc.
I have also signed up for a JUnit and Mockito Crash Course in Udemy. Even if you
know JUnit and basics of unit testing, you may want to refresh and upgrade your
knowledge in 2018.

4. General purpose libraries


There is a couple of very good general purpose, third-party library available to Java
developer e.g. Apache Commons and Google Guava. I always include these libraries in
my projects because they simplify a lot of tasks. As Joshua Bloch has rightly said
in Effective Java (now the 3rd edition is also available) that there is no point in re-
inventing the wheels and we should prefer using tried and tested libraries instead of
writing our own routines every now and then.
It’s just for a good Java developer to get himself familiar with Google’s Guava and
Apache commons library.
5. Http libraries
One thing I don’t like much about JDK is their lack of support for HTTP. Though you
can make HTTP connection using classes in [Link] package it’s not as easy and
seamless as by using open source, third-party libraries like Apache HttpClient and
HttpCore.
Though JDK 9 is bringing the support of HTTP 2.0 and better support for HTTP, I
strongly suggest all Java developers get familiar with popular HTTP client libraries e.g.
HttpClient and HttpCore.
You can also check What’s New in Java 9 – Modules and More to learn more about JDK
9’s HTTP 2 support.
6. XML parsing libraries
There are many XML parsing libraries exists e.g. Xerces, JAXB, JAXP, Dom4j, Xstream
etc. Xerces2 is the next generation of high performance, fully compliant XML parsers in
the Apache Xerces family. This new version of Xerces introduces the Xerces Native
Interface (XNI), a complete framework for building parser components and
configurations that is extremely modular and easy to program.

The Apache Xerces2 parser is the reference implementation of XNI but other parser
components, configurations, and parsers can be written using the Xerces Native
Interface. Dom4j is another flexible XML framework for Java application. If you want to
learn more about XML parsing in Java then I suggest you take a look at Java Web
Services and XML online course on Udemy. It’s currently available for only $10.99 on
sale.
7. Excel reading libraries
Believe it or not but all real-world application has to interact with Microsoft office in
some form or other. Many application needs to provide functionality to export data in
Excel and if you have to do same from your Java application then you need Apache POI
API.
This is a very rich library which allows you to both read and write XLS files from Java
program. You can see that link for a working example of reading Excel file in Core Java
application.
8. Bytecode libraries
If you are writing framework or libraries which generate code or interact with bytecodes
then you need a bytecode library. They allow you to read and modify bytecode
generated by an application. Some of the popular bytecode libraries in Java world are
javassist and Cglib Nodep.

The Javassist (JAVA programming ASSISTant) makes Java bytecode manipulation very
simple. It is a class library for editing bytecodes in Java. ASM is another useful bytecode
editing library.
9. Database connection pool libraries
If you are interacting with the database from Java application but not using database
connection pool libraries then you are missing something. Since creating connections at
runtime takes time and makes request processing slower, its always advised to use DB
connection libraries. Some of the popular ones are Commons Pool and DBCP.
In a web application, it’s web server which generally provides these functionalities but
in core Java application you need to include these connection pool libraries into your
classpath to use database connection pool. If you want to learn more about JDBC and
connection pool in a web application, I suggest you take a look at JSP, Servlet, and
JDBC for Beginnerscourse in Udemy.
10. Messaging libraries
Similar to logging and database connection, messaging is also a common feature of
many real-world Java application. Java provides JMS, Java Messaging Service but that’s
not part of JDK and you need to include separate [Link]. Similarly, if you are using
third-party messaging protocol e.g. Tibco RV then you need to use a third-party JAR
like [Link] in your application classpath.
11. PDF Libraries
Similar to Microsoft Excel and World, PDF is another ubiquitous format. If you need to
support PDF functionality in your application e.g. exporting data in PDF files then you
can use the iText and Apache FOP libraries. Both provide useful PDF related
functionality but iText is richer and better and I always preferred that one. See here to
learn more about iText.

12. Date and Time libraries


Before Java 8, JDK’s data and time libraries have so many flaws e.g they were not
thread-safe, immutable, and error-prone and many Java developer relied on JodaTime
for implementing their date and time requirement. From JDK 8, there is no reason to
use Joda because you get all that functionality in the JDK 8’s new Date and Time
API itself but if you are working in older Java version then JodaTime is a worth learning
library.
If you want to learn more about new Date and Time API, I suggest you to please check
the What’s new in Java 8 course from Pluralsight. It provides a nice overview of all
important features of Java 8, including Date and Time API.
[Link] libraries
Even though JDK has a rich collection libraries, there are are some 3rd party libraries
which provide more options e.g. Apache Commons Collections, Goldman Sachs
collections, Google Collections, and Trove. The Trove library is particularly useful
because it provides high speed regular and primitive collections for Java.

FastUtil is another similar API, it extends the Java Collections Framework by providing
type-specific maps, sets, lists and priority queues with a small memory footprint and
fast access and insertion; provides also big (64-bit) arrays, sets, and lists, and fast,
practical I/O classes for binary and text files.
14. Email APIs
The [Link] and Apache Commons Email – provide an API for sending an email. It is
built on top of the JavaMail API, which it aims to simplify.

15. HTML Parsing libraries


Similar to JSON and XML, HMTL is another common format many of us have to deal
with. Thankfully, we have jsoup which greatly simplify working with HTML in Java
application. You can use JSoup to not only parse HTML but also to create HTML
documents
It provides a very convenient API for extracting and manipulating data, using the best
of DOM, CSS, and jquery-like methods. jsoup implements the WHATWG HTML5
specification and parses HTML to the same DOM as modern browsers do.
[Link] library
The Apache Commons Codec package contains simple encoder and decoders for
various formats such as Base64 and Hexadecimal. In addition to these widely used
encoders and decoders, the codec package also maintains a collection of phonetic
encoding utilities.

17. Embedded SQL database library


I really love in-memory database like H2, which you can embed in your Java
application. They are great for testing your SQL scripts and running Unit tests which
need a database. Btw, H2 is not the only DB, you also have Apache Derby and HSQL to
choose from.
18. JDBC Troubleshooting libraries
There are some good JDBC Extension libraries exists which makes debugging easier
e.g. P6spy. It is a library which enables database data to be seamlessly intercepted and
logged with no code changes to the application. You can use these to log SQL queries
and their timings. For example, if you are
using PreparedStatment and CallableStatement in your code then these libraries can log
an exact call with parameters and how much time it took to execute.

19. Serialization libraries


Google Protocol Buffer Protocol Buffers are a way of encoding structured data in an
efficient yet extensible format. It’s richer and better alternative to Java serialization and
I strongly recommend experienced Java developer to learn Google Protobuf. You can
see this article to learn more about Google Protocol Buffer.
20. Networking libraries
Some of the useful networking libraries are Netty and Apache MINA. If you are writing
an application where you need to do low-level networking task, consider using these
libraries.

That’s all about some of the useful libraries every Java developer should be
familiar with. Java Ecosystem is very vast and you will find tons of libraries for doing
different things. You think about something and you will find there is a library exists to
do just that. As always, Google is your best friend to find useful Java libraries but you
can also take a look at Maven central repository to find some of the useful libraries for
your task at hand.
If you like this article, you may find my other articles useful too:
• 10 Things Java Developer Should Learn in 2018
• 10 Programming Languages to explore in 2018
• 10 Frameworks Java and Web Developers should learn in 2018
• 20 Java Books You Can Read in 2018
• 10 Ways to Learn a New Technology in 2018
• 10 PluralSight Courses for Java and Web Developers
• 10 Tutorials to Learn Java 8 Better
Thanks for reading this article so far. If you like this article then please share with your
friends and colleagues too. If you have any feedback or questions then please drop a
note.
P.S. – If you want to start 2018 in good note then I suggest you to read
Effective Java 3rd Edition, one the must read book for every developer. It’s not updated
for Java 7, 8, and 9 and most of the items are updated keeping new changes in mind.

You might also like