Java Titbits
Java Titbits
Reusability of code.
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
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.
byte
short
int
long
float
double
boolean
char
Autoboxing
primitive types and their corresponding object wrapper classes. For example,
the compiler converts an int to an Integer, a double to a Double, and so on. If the
conversion goes the other way, this operation is called unboxing .
6. What is Function Overriding and Overloading in Java ? Method
overloading in Java occurs when two or more methods in the same class have
the exact same name, but different parameters. On the other hand, method
overriding is defined as the case when a child class redefines the same method
as a parent class. Overridden methods must have the same name, argument
list, and return type. The overriding method may not limit the access of the
method it overrides.
7. What is a Constructor, Constructor Overloading in Java and CopyConstructor ? A constructor gets invoked when a new object is created. Every
class has a constructor. In case the programmer does not provide a constructor
for a class, the Java compiler (Javac) creates a default constructor for that class.
The constructor overloading is similar to method overloading in Java. Different
constructors can be created for a single class. Each constructor must have its
own unique parameter list. Finally, Java does support copy constructors like C+
+, but the difference lies in the fact that Java doesnt create a default copy
constructor if you dont write your own.
8. Does Java support multiple inheritance ? No, Java does not support
multiple inheritance. Each class is able to extend only on one class, but is able
to implement more than one interfaces.
9. What is the difference between an Interface and an Abstract
class ? Java provides and supports the creation both of abstract classes and
interfaces. Both implementations share some common characteristics, but they
differ in the following features:
A class may implement a number of Interfaces, but can extend only one
abstract class.
Also check out the Abstract class and Interface differences for JDK 8.
10. What are pass by reference and pass by value ? When an object is
passed by value, this means that a copy of the object is passed. Thus, even if
changes are made to that object, it doesnt affect the original value. When an
object is passed by reference, this means that the actual object is not passed,
rather a reference of the object is passed. Thus, any changes made by the
external method, are also reflected in all places.
Java Threads
11. What is the difference between processes and threads ? A process is
an execution of a program, while a Threadis 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:
Executor
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 threads
code.
BLOCKED:
TIMED_WAITING:
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:
Map, which is an object that maps keys to values and cannot contain
duplicate keys.
19. Why Collection doesnt 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 dont. 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 anyCollection. Each Java Collection contains
the iterator method that returns an Iterator instance. Iterators arecapable 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
the
ListIterator
ListIterator
Hashtable
HashMap
is preferred
26. What is difference between Array and ArrayList ? When will you use
Array over ArrayList ? The Array andArrayList classes differ on the following
features:
Arrays can contain primitive or objects, while an ArrayList can contain only
objects.
as
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.
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 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 doesnt allow null values,
those objects that doesnt provide natural ordering, or those objects that dont
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 BigO 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 applications
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.
hashCode
and equals
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 System.gc() and Runtime.gc() 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 objects 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.
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 constructors 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 constructors 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 users program should
catch. TheError 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:
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 start any program on the host thats 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 clients 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 applets classes are placed in a
private namespace associated with the applets origin. Then, those classes
loaded by the class loader are passed through the verifier.The 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
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. AList 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 aContainer. 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 threadsafe 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
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 vendorspecific implementations of the abstract classes provided by the JDBC API. Each
driver must provide implementations for the following classes of the java.sql
package:Connection, Statement, PreparedStatement, CallableStatement, ResultSet and Driver.
74. What is the purpose Class.forName 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. ACallableStatement 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 modularity.The method that prepares a CallableStatement is the following:
1 CallableStament.prepareCall();
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.
Stub and Skeleton layer: This layer lies just beneath the view of the developer.
This layer is responsible for intercepting method calls made by the client to
the interface and redirect these calls to a remote RMI Service.
Remote Reference Layer: The second layer of the RMI architecture deals with
the interpretation of references made from the client to the servers remote
objects. This layer interprets and manages references made from clients to
the remote service objects. The connection is a one-to-one (unicast) link.
Transport layer: This layer is responsible for connecting the two JVM
participating in the service. This layer is based on TCP/IP connections between
machines in a network. It provides basic connectivity, as well as some firewall
penetration strategies.
81. What is the role of Remote Interface in RMI ? The Remote interface
serves to identify interfaces whose methods may be invoked from a non-local
virtual machine. Any object that is a remote object must directly or indirectly
implement this interface. A class that implements a remote interface should
declare the remote interfaces being implemented, define the constructor for
each remote object and provide an implementation for each remote method in
all remote interfaces.
82. What is the role of the java.rmi.Naming Class ? The java.rmi.Naming
class provides methods for storing and obtaining references to remote objects in
the remote object registry. Each method of the Naming class takes as one of its
arguments a name that is a String in URL format.
83. What is meant by binding in RMI ? Binding is the process of associating
or registering a name for a remote object, which can be used at a later time, in
order to look up that remote object. A remote object can be associated with a
name using the bind or rebind methods of the Naming class.
84. What is the difference between using bind() and rebind() methods
of Naming Class ? The bind method bind is responsible for binding the
specified name to a remote object, while the rebind method is responsible for
rebinding the specified name to a new remote object. In case a binding exists for
that name, the binding is replaced.
85. What are the steps involved to make work a RMI program ? The
following steps must be involved in order for a RMI program to work properly:
86. What is the role of stub in RMI ? A stub for a remote object acts as a
clients local representative or proxy for the remote object. The caller invokes a
method on the local stub, which is responsible for executing the method on the
remote object. When a stubs method is invoked, it undergoes the following
steps:
It unmarshals the return value or an exception if the method has not been
successfully executed.
87. What is DGC ? And how does it work ? DGC stands for Distributed
Garbage Collection. Remote Method Invocation (RMI) uses DGC for automatic
garbage collection. Since RMI involves remote object references across JVMs,
garbage collection can be quite difficult. DGC uses a reference counting
algorithm to provide automatic memory management for remote objects.
88. What is the purpose of using RMISecurityManager in
RMI ? RMISecurityManager provides a security manager that can be used by
RMI applications, which use downloaded code. The class loader of RMI will not
download any classes from remote locations, if the security manager has not
been set.
89. Explain Marshalling and demarshalling. When an application wants to
pass its memory objects across a network to another host or persist it to
storage, the in-memory representation must be converted to a suitable format.
This process is called marshalling and the revert operation is called
demarshalling.
90. Explain Serialization and Deserialization. Java provides a mechanism,
called object serialization where an object can be represented as a sequence of
bytes and includes the objects data, as well as information about the objects
type, and the types of data stored in the object. Thus, serialization can be seen
as a way of flattening objects, in order to be stored on disk, and later, read back
and reconstituted. Deserialisation is the reverse process of converting an object
from its flattened state to a live object.
Servlets
91. What is a Servlet ? The servlet is a Java programming language class
used to process client requests and generate dynamic web content. Servlets are
mostly used to process or store data submitted by an HTML form, provide
dynamic content and manage state information that does not exist in the
stateless HTTP protocol.
92. Explain the architechure of a Servlet. The core abstraction that must be
implemented by all servlets is the javax.servlet.Servlet interface. Each servlet
must implement it either directly or indirectly, either by extending
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:
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. Seehow 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 server.The 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.
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 changed.The generated servlet class is invoked,
in order to handle the browsers 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.
Developers can offer customized JSP tag libraries that page authors
access using an XML-like syntax.
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 pagelevel 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
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 plugin.Some of the available actions are listed below:
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:forward
jsp:plugin
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 variables.The
following objects are considered implicit in a JSP page:
application
page
request
response
session
exception
out
config
pageContext