Java Interview Questions
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
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.
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.
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
Answer:
The program compiles properly but at runtime it will give “Main method not public.”
message.
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()
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.
Or
Or
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”;
[Link](”== comparison : ” + s3
13
== s4);
15 }
16 }
Output
1 == comparison : true
2 == comparison : true
4 false
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”.
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
Or
Or
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.
Answer:
The GregorianCalendar provides support for traditional Western calendars.
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.
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.
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();
Answer:
The SimpleTimeZone class provides support for a Gregorian calendar.
Answer:
The Locale class is used to tailor a program output to the conventions of a particular
geographic, political, or cultural region.
Answer:
There are three main principals of oops which are called Polymorphism, Inheritance and
Encapsulation.
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
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;
Answer:
The sizeof is not a keyword.
Answer:
A native method is a method that is implemented in a language other than Java.
Answer:
System is a predefined final class, out is a PrintStream object and println is a built-in
overloaded method in the out object.
Or
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
Answer:
Explicit casting in the process in which the complier are specifically informed to about
transforming the object.
Example
1 long i = 700.20;
Answer:
The Java Virtual Machine is software that can be ported onto various hardware-based
platforms
Answer:
The process of Downcasting refers to the casting from a general to a more specific type,
i.e. casting down the hierarchy
Or
39. Q. What is the difference between public, private, protected and default Access
Specifiers?
Or
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
Answer:
Object.
Or
Or
Or
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.
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.
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.
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.
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].
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.
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.
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;
2 a = a ^ b;
3 b = a ^ b;
4 a = a ^ b;
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.
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.
Answer:
Phantom memory is false memory. Memory that does not exist in reality.
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}
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
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
06
07 system)
08
09
10
11 volatile
12
14
16
18
19
20
22
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.
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 () {
5}
2 synchronized (this) {
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.
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.
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.
//add at last
[Link](0, "0");
[Link](1, "1");
//replace
[Link](1, "2");
//remove
[Link]("1");
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 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.
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.
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.
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.
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.
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.
• Avoid ConcurrentModificationException
• CopyOnWriteArrayList Example
• HashMap vs ConcurrentHashMap
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
HashSet No No No No Yes No
TreeSet Yes No No No No No
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.
4 long id = [Link]().getId();
5 String name = [Link]().getName();
6 ...
7 }
8}
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.
02
04 super(name);
05 }
06
07 @Override
[Link]("Executing thread
09
"+[Link]().getName());
10 }
11
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
[Link]("Executing thread
04
"+[Link]().getName());
05 }
06
07 public static void main(String[] args) throws InterruptedException {
09 [Link]();
10 }
11 }
03
06 [Link]();
07 }
08
10 stopIndicator = null;
11 }
12
13 @Override
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() ?
02
04
06 super(name);
07 }
08
09 @Override
11 [Link]([Link]().getName());
12 }
13 }
14
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.
02
04
05 public MyDaemonThread() {
06 setDaemon(true);
07 }
08
09 @Override
12 try {
13 [Link](1);
14 } catch (InterruptedException e) {
15 [Link]();
16 }
17 }
18 }
19 }
20
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 .
07 currentTimeMillis = [Link]();
08 }
09 }
10 });
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
04 try {
05 [Link](Long.MAX_VALUE);
06 } catch (InterruptedException e) {
[Link]("["+[Link]().getName()+"]
07
Interrupted by exception!");
08 }
09 }
10
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 }
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
5 }
6 });
7 [Link]();
8 [Link]();
02
04
05 public MyDaemonThread() {
06 setDaemon(true);
07 }
08
09 @Override
11 try {
12 [Link](1000);
13 } catch (InterruptedException e) {
14 }
15 }
16 }
17
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
5 }
6 });
2 counter++;
3}
2 synchronized(this) {
3 ...
4 }
5}
03
05 if(instance == null) {
06 synchronized ([Link]) {
07 if(instance == null) {
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.
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.
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.
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() {
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");
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.
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.
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.
132. Which technique to reduce lock contention can be applied to the following
code?
1 synchronized (map) {
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]();
4 synchronized (map) {
5 [Link](key, value);
6}
03
04 public void increment() {
05 [Link]();
06 }
07
09 return [Link]();
10 }
11 }
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 .
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 {
06 }
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.
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.
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.
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.
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.
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.
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?
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.
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.
04 [Link](obj);
05 }
06 //using iterator
07 Iterator<String> it = [Link]();
08 while([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 .
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.
03 [Link](key, 'Value');
04
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,
12 [Link](new MyKey('Pankaj'));
9. This is the reason why String and Integer are mostly used as HashMap keys.
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<>>
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 .
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!
4.1. Optional
4.2. Streams
4.5. Base64
4.6. Parallel Arrays
4.7. Concurrency
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)
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:
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:
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:
And:
1 final String 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:
And:
1 [Link]( "a", "b", "d" ).sort( ( e1, e2 ) -> {
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
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
3 void method();
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.
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.
06 }
07 }
08
10 }
11
13 @Override
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 {
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 ) {
3 [Link]( [Link]() );
6 [Link]( [Link]() );
7}
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.
03 return [Link]();
04 }
05
08 }
09
12 }
13
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.
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.
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.
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
10 @Target( [Link] )
11 @Retention( [Link] )
13 Filter[] value();
14 }
15
16 @Target( [Link] )
17 @Retention( [Link] )
18 @Repeatable( [Link] )
20 String value();
21 };
22
23 @Filter( "filter1" )
24 @Filter( "filter2" )
26 }
27
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).
2 filter2
01 package [Link];
02
05 return null;
06 }
07
10 }
11 }
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().
01 package [Link];
02
03 import [Link];
04 import [Link];
05 import [Link];
06 import [Link];
07 import [Link];
08 import [Link];
09
11 @Retention( [Link] )
12 @Target( { ElementType.TYPE_USE, ElementType.TYPE_PARAMETER } )
14 }
15
18 }
19 }
20
21 @SuppressWarnings( "unused" )
25 }
26 }
02
03 import [Link];
04 import [Link];
05
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.
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.
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:
3 Hey Stranger!
5 [Link]();
3 Hey Tom!
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.
03 OPEN, CLOSED
04 };
05
09
11 [Link] = status;
12 [Link] = points;
13 }
14
16 return points;
17 }
18
20 return status;
21 }
22
23 @Override
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.
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.
3 .stream()
5 .mapToInt( Task::getPoints )
6 .sum();
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.
3 .stream()
4 .parallel()
6 .reduce( 0, Integer::sum );
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:
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.
3 .stream()
5 [Link]( map );
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.
05 .asLongStream() // LongStream
11
12 [Link]( result );
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.
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]().
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.
04
05 [Link]( date );
06 [Link]( dateFromClock );
07
11
12 [Link]( time );
13 [Link]( timeFromClock );
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.
5 [Link]( datetime );
6 [Link]( datetimeFromClock );
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.
6 [Link]( zonedDatetime );
7 [Link]( zonedDatetimeFromClock );
8 [Link]( zonedDatetimeFromZone );
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.
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
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 [Link]( [Link]().getName() );
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
09
11 .getEncoder()
13 [Link]( encoded );
14
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]()).
01 package [Link];
02
03 import [Link];
04 import [Link];
05
09
10 [Link]( arrayOfLong,
14 [Link]();
15
16 [Link]( arrayOfLong );
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).
• DoubleAccumulator
• DoubleAdder
• LongAccumulator
• LongAdder
1 function f() {
2 return 1;
3 };
5 print( f() + 1 );
1 jjs [Link]
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.
02 [Link] ([Link])
03 -> [Link]
04 -> [Link]
05 -> [Link]
06 -> [Link]
07 -> [Link]
08 -> [Link]
09 -> [Link]
[Link] ([Link]-
13
[Link])
14 -> [Link]
15 -> [Link]
16 -> [Link]
17 -> [Link]
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:
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.
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.
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.
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.