Java Interview Questions have been designed especially to get you acquainted with the
nature of questions you may encounter during your interview for the subject of Java Programming Language. As per my experience, good interviewers hardly
planned to ask any particular question during your interview, normally
questions start with some basic concept of the subject and later they continue
based on further discussion and what you answer:
Q: What do you know
about Java?
A: Java is a high-level
programming language originally developed by Sun Microsystems and released in
1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX.
Q: What are the
supported platforms by Java Programming Language?
A: Java runs on a variety of
platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like
HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.
Q: List any five
features of Java?
A: Some features include
Object Oriented, Platform Independent, Robust, Interpreted, Multi-threaded
Q: Why is Java
Architectural Neutral?
A: It’s compiler generates
an architecture-neutral object file format, which makes the compiled code to be
executable on many processors, with the presence of Java runtime system.
Q: How Java enabled High
Performance?
A: Java uses Just-In-Time
compiler to enable high performance. Just-In-Time compiler is a program that
turns Java bytecode, which is a program that contains instructions that must be
interpreted into instructions that can be sent directly to the processor.
Q: Why Java is
considered dynamic?
A: It is designed to adapt
to an evolving environment. Java programs can carry extensive amount of
run-time information that can be used to verify and resolve accesses to objects
on run-time.
Q: What is Java Virtual
Machine and how it is considered in context of Java’s platform independent
feature?
A: When Java is compiled,
it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and
interpreted by virtual Machine (JVM) on whichever platform it is being run.
Q: List two Java IDE’s?
A: Netbeans, Eclipse, etc.
Q: List some Java
keywords(unlike C, C++ keywords)?
A: Some Java keywords are
import, super, finally, etc.
Q: What do you mean by
Object?
A: Object is a runtime
entity and it’s state is stored in fields and behavior is shown via methods.
Methods operate on an object's internal state and serve as the primary
mechanism for object-to-object communication.
Q: Define class?
A: A class is a blue print
from which individual objects are created. A class can contain fields and
methods to describe the behavior of an object.
Q: What kind of
variables a class can consist of?
A: A class consist of Local
variable, instance variables and class variables.
Q: What is a Local
Variable
A: Variables defined inside
methods, constructors or blocks are called local variables. The variable will
be declared and initialized within the method and it will be destroyed when the
method has completed.
Q: What is a Instance
Variable
A: Instance variables are
variables within a class but outside any method. These variables are
instantiated when the class is loaded.
Q: What is a Class
Variable
A: These are variables
declared with in a class, outside any method, with the static keyword.
Q: What is Singleton
class?
A: Singleton class control
object creation, limiting the number to one but allowing the flexibility to
create more objects if the situation changes.
Q: What do you mean by
Constructor?
A: Constructor gets invoked
when a new object is created. Every class has a constructor. If we do not
explicitly write a constructor for a class the java compiler builds a default
constructor for that class.
Q: List the three steps
for creating an Object for a class?
A: An Object is first
declared, then instantiated and then it is initialized.
Q: What is the default
value of byte datatype in Java?
A: Default value of byte
datatype is 0.
Q: What is the default
value of float and double datatype in Java?
A: Default value of float
and double datatype in different as compared to C/C++. For float its 0.0f and
for double it’s 0.0d
Q: When a byte datatype
is used?
A: This data type is used
to save space in large arrays, mainly in place of integers, since a byte is
four times smaller than an int.
Q: What is a static
variable?
A: Class variables also
known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.
Q: What do you mean by
Access Modifier?
A: Java provides access
modifiers to set access levels for classes, variables, methods and
constructors. A member has package or default accessibility when no
accessibility modifier is specified.
Q: What is protected
access modifier?
A: Variables, methods and
constructors which are declared protected in a superclass can be accessed only
by the subclasses in other package or any class within the package of the
protected members' class.
Q: What do you mean by
synchronized Non Access Modifier?
A: Java provides these
modifiers for providing functionalities other than Access Modifiers,
synchronized used to indicate that a method can be accessed by only one thread
at a time.
Q: According to Java
Operator precedence, which operator is considered to be with highest
precedence?
A: Postfix operators i.e ()
[] . is at the highest precedence.
Q: Variables used in a
switch statement can be used with which datatypes?
A: Variables used in a
switch statement can only be a byte, short, int, or char.
Q: When parseInt() method
can be used?
A: This method is used to
get the primitive data type of a certain String.
Q: Why is String class
considered immutable?
A: The String class is
immutable, so that once it is created a String object cannot be changed. Since
String is immutable it can safely be shared between many threads ,which is
considered very important for multithreaded programming.
Q: Why is StringBuffer
called mutable?
A: The String class is
considered as immutable, so that once it is created a String object cannot be changed.
If there is a necessity to make alot of modifications to Strings of characters
then StringBuffer should be used.
Q: What is the
difference between StringBuffer and StringBuilder class?
A: Use StringBuilder
whenever possible because it is faster than StringBuffer. But, if thread safety
is necessary then use StringBuffer objects.
Q: Which package is used
for pattern matching with regular expressions?
A: java.util.regex package
is used for this purpose.
Q: java.util.regex
consists of which classes?
A: java.util.regex consists
of three classes: Pattern class, Matcher class and PatternSyntaxException
class.
Q: What is finalize()
method?
A: It is possible to define
a method that will be called just before an object's final destruction by the
garbage collector. This method is called finalize( ), and it can be used to
ensure that an object terminates cleanly.
Q: What is an Exception?
A: An exception is a
problem that arises during the execution of a program. Exceptions are caught by
handlers positioned along the thread's method invocation stack.
Q: What do you mean by
Checked Exceptions?
A: It is an exception that
is typically a user error or a problem that cannot be foreseen by the
programmer. For example, if a file is to be opened, but the file cannot be
found, an exception occurs. These exceptions cannot simply be ignored at the
time of compilation.
Q: Explain Runtime
Exceptions?
A: It is an exception that
occurs that probably could have been avoided by the programmer. As opposed to
checked exceptions, runtime exceptions are ignored at the time of compliation.
Q: Which are the two
subclasses under Exception class?
A: The Exception class has
two main subclasses : IOException class and RuntimeException Class.
Q: When throws keyword
is used?
A: If a method does not
handle a checked exception, the method must declare it using the throwskeyword.
The throws keyword appears at the end of a method's signature.
Q: When throw keyword is
used?
A: An exception can be
thrown, either a newly instantiated one or an exception that you just caught,
by using throw keyword.
Q: How finally used
under Exception Handling?
A: The finally keyword is
used to create a block of code that follows a try block. A finally block of
code always executes, whether or not an exception has occurred.
Q: What things should be
kept in mind while creating your own exceptions in Java?
A: While creating your own
exception:
·
All exceptions must be a
child of Throwable.
·
If you want to write a
checked exception that is automatically enforced by the Handle or Declare Rule,
you need to extend the Exception class.
·
You want to write a
runtime exception, you need to extend the RuntimeException class.
Q: Define Inheritance?
A: It is the process where
one object acquires the properties of another. With the use of inheritance the
information is made manageable in a hierarchical order.
Q: When super keyword is
used?
A: If the method overrides
one of its superclass's methods, overridden method can be invoked through the
use of the keyword super. It can be also used to refer to a hidden field
Q: What is Polymorphism?
A: Polymorphism is the
ability of an object to take on many forms. The most common use of polymorphism
in OOP occurs when a parent class reference is used to refer to a child class
object.
Q: What is Abstraction?
A: It refers to the ability
to make a class abstract in OOP. It helps to reduce the complexity and also
improves the maintainability of the system.
Q: What is Abstract
class
A: These classes cannot be
instantiated and are either partially implemented or not at all implemented.
This class contains one or more abstract methods which are simply method
declarations without a body.
Q: When Abstract methods
are used?
A: If you want a class to
contain a particular method but you want the actual implementation of that
method to be determined by child classes, you can declare the method in the
parent class as abstract.
Q: What is
Encapsulation?
A: It is the technique of
making the fields in a class private and providing access to the fields via
public methods. If a field is declared private, it cannot be accessed by anyone
outside the class, thereby hiding the fields within the class. Therefore
encapsulation is also referred to as data hiding.
Q: What is the primary
benefit of Encapsulation?
A: The main benefit of
encapsulation is the ability to modify our implemented code without breaking
the code of others who use our code. With this Encapsulation gives
maintainability, flexibility and extensibility to our code.
Q: What is an Interface?
A: An interface is a
collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface.
Q: Give some features of
Interface?
A: It includes:
·
Interface cannot be
instantiated
·
An interface does not
contain any constructors.
·
All of the methods in an
interface are abstract.
Q: Define Packages in
Java?
A: A Package can be defined
as a grouping of related types(classes, interfaces, enumerations and
annotations ) providing access protection and name space management.
Q: Why Packages are
used?
A: Packages are used in
Java in-order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and
annotations, etc., easier.
Q: What do you mean by
Multithreaded program?
A: A multithreaded program
contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of
execution.
Q: What are the two ways
in which Thread can be created?
A: Thread can be created
by: implementing Runnable interface, extending the Thread class.
Q: What is an applet?
A: An applet is a Java
program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
Q: An applet extend
which class?
A: An applet extends
java.applet.Applet class.
Q: Explain garbage
collection in Java?
A: It uses garbage
collection to free the memory. By cleaning those objects that is no longer
reference by any of the program.
Q: Define immutable
object?
A: An immutable object
can’t be changed once it is created.
Q: Explain the usage of
this() with constructors?
A: It is used with
variables or methods and used to call constructer of same class.
Q: Explain Set Interface?
A: It is a collection of
element which cannot contain duplicate elements. The Set interface contains
only methods inherited from Collection and adds the restriction that duplicate
elements are prohibited.
Q: Explain TreeSet?
A: It is a Set implemented
when we want elements in a sorted order.
Q: What is Comparable
Interface?
A: It is used to sort
collections and arrays of objects using the collections.sort() and java.utils.
The objects of the class implementing the Comparable interface can be ordered.
Q: Difference between
throw and throws?
A: It includes:
·
Throw is used to trigger
an exception where as throws is used in declaration of exception.
·
Without throws, Checked
exception cannot be handled where as checked exception can be propagated with
throws.
Q: Explain the following
line used under Java Program:
public static void main (String args[ ])
A: The following shows the
explanation individually:
·
public: it is the access specifier.
·
static: it allows main() to be called without
instantiating a particular instance of a class.
·
void: it affirns the compiler that no value is
returned by main().
·
main(): this method is called at the beginning of a Java program.
·
String args[ ]: args parameter is an instance array of class
String
Q: Define JRE i.e. Java
Runtime Environment?
A: Java Runtime Environment
is an implementation of the Java Virtual Machine which executes Java programs.
It provides the minimum requirements for executing a Java application;
Q: What is JAR file?
A: JAR files is Java
Archive fles and it aggregates many files into one. It holds Java classes in a
library. JAR files are built on ZIP file format and have .jar file extension.
Q: What is a WAR file?
A: This is Web Archive File
and used to store XML, java classes, and JavaServer pages. which is used to
distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML
files, static Web pages etc.
Q: Define JIT compiler?
A: It improves the runtime
performance of computer programs based on bytecode.
Q: What is the
difference between object oriented programming language and object based
programming language?
A: Object based programming
languages follow all the features of OOPs except Inheritance. JavaScript is an
example of object based programming languages
Q: What is the purpose of
default constructor?
A: The java compiler
creates a default constructor only if there is no constructor in the class.
Q: Can a constructor be
made final?
A: No, this is not
possible.
Q: What is static block?
A: It is used to initialize
the static data member, It is excuted before main method at the time of
classloading.
Q: Define composition?
A: Holding the reference of
the other class within some other class is known as composition.
Q: What is function
overloading?
A: If a class has multiple
functions by same name but different parameters, it is known as Method
Overloading.
Q: What is function
overriding?
A: If a subclass provides a
specific implementation of a method that is already provided by its parent
class, it is known as Method Overriding.
Q: Difference between
Overloading and Overriding?
A: Method overloading
increases the readability of the program. Method overriding provides the
specific implementation of the method that is already provided by its super
class parameter must be different in case of overloading, parameter must be
same in case of overriding.
Q: What is final class?
A: Final classes are
created so the methods implemented by that class cannot be overridden. It can’t
be inherited.
Q: What is
NullPointerException?
A: A NullPointerException
is thrown when calling the instance method of a null object, accessing or
modifying the field of a null object etc.
Q: What are the ways in
which a thread can enter the waiting state?
A: A thread can enter the
waiting state by invoking its sleep() method, by blocking on IO, by
unsuccessfully attempting to acquire an object's lock, or by invoking an
object's wait() method. It can also enter the waiting state by invoking its
(deprecated) suspend() method.
Q: How does
multi-threading take place on a computer with a single CPU?
A: The operating system's
task scheduler allocates execution time to multiple tasks. By quickly switching
between executing tasks, it creates the impression that tasks execute
sequentially.
Q: What invokes a
thread's run() method?
A: After a thread is
started, via its start() method of the Thread class, the JVM invokes the
thread's run() method when the thread is initially executed.
Q: Does it matter in
what order catch statements for FileNotFoundException and IOException are
written?
A: Yes, it does. The
FileNoFoundException is inherited from the IOException. Exception's subclasses
have to be caught first.
Q: What is the
difference between yielding and sleeping?
A: When a task invokes its
yield() method, it returns to the ready state. When a task invokes its sleep()
method, it returns to the waiting state.
Q: Why Vector class is
used?
A: The Vector class
provides the capability to implement a growable array of objects. Vector proves
to be very useful if you don't know the size of the array in advance, or you
just need one that can change sizes over the lifetime of a program.
Q: How many bits are
used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
A: Unicode requires 16 bits
and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it
is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and
18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
Q: What are Wrapper
classes?
A: These are classes that
allow primitive types to be accessed as objects. Example: Integer, Character,
Double, Boolean etc.
Q: What is the
difference between a Window and a Frame?
A: The Frame class extends
Window to define a main application window that can have a menu bar.
Q: Which package has light
weight components?
A: javax.Swing package. All
components in Swing, except JApplet, JDialog, JFrame and JWindow are
lightweight components.
Q: What is the
difference between the paint() and repaint() methods?
A: The paint() method
supports painting via a Graphics object. The repaint() method is used to cause
paint() to be invoked by the AWT painting thread.
Q: What is the purpose
of File class?
A: It is used to create
objects that provide access to the files and directories of a local file
system.
Q: What is the
difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?
A: The Reader/Writer class
hierarchy is character-oriented, and the InputStream/OutputStream class
hierarchy is byte-oriented.
Q: Which class should
you use to obtain design information about an object?
A: The Class class is used
to obtain information about an object's design and java.lang.Class class
instance represent classes, interfaces in a running Java application.
Q: What is the difference
between static and non-static variables?
A: A static variable is
associated with the class as a whole rather than with specific instances of a
class. Non-static variables take on unique values with each object instance.
Q: What is Serialization
and deserialization?
A: Serialization is the
process of writing the state of an object to a byte stream. Deserialization is
the process of restoring these objects.
Q: What are use cases?
A: It is part of the
analysis of a program and describes a situation that a program might encounter
and what behavior the program should exhibit in that circumstance.
Q: Explain the use of
sublass in a Java program?
A: Sub class inherits all
the public and protected methods and the implementation. It also inherits all
the default modifier methods and their implementation.
Q: How to add
menushortcut to menu item?
A: If there is a button
instance called b1, you may add menu short cut by calling b1.setMnemonic('F'),
so the user may be able to use Alt+F to click the button.
Q: Can you write a Java
class that could be used both as an applet as well as an application?
A: Yes, just add a main()
method to the applet.
Q: What is the
difference between Swing and AWT components?
A: AWT components are
heavy-weight, whereas Swing components are lightweight. Heavy weight components
depend on the local windowing toolkit. For example, java.awt.Button is a heavy
weight component, when it is running on the Java platform for Unix platform, it
maps to a real Motif button.
Q: What's the difference
between constructors and other methods?
A: Constructors must have
the same name as the class and can not return a value. They are only called
once while regular methods could be called many times.
Q: Is there any
limitation of using Inheritance?
A: Yes, since inheritance
inherits everything from the super class and interface, it may make the
subclass too clustering and sometimes error-prone when dynamic overriding or
dynamic overloading in some situation.
Q: When is the
ArrayStoreException thrown?
A: When copying elements
between different arrays, if the source or destination arguments are not arrays
or their types are not compatible, an ArrayStoreException will be thrown.
Q: Can you call one
constructor from another if a class has multiple constructors?
A: Yes, use this() syntax.
Q: What's the difference
between the methods sleep() and wait()?
A: The code sleep(2000);
puts thread aside for exactly two seconds. The code wait(2000), causes a wait
of up to two second. A thread could stop waiting earlier if it receives the
notify() or notifyAll() call. The method wait() is defined in the class Object
and the method sleep() is defined in the class Thread.
Q: When
ArithmeticException is thrown?
A: The ArithmeticException
is thrown when integer is divided by zero or taking the remainder of a number
by zero. It is never thrown in floating-point operations.
Q: What is a transient
variable?
A: A transient variable is
a variable that may not be serialized during Serialization and which is
initialized by its default value during de-serialization,
Q: What is
synchronization?
A: Synchronization is the
capability to control the access of multiple threads to shared resources.
synchronized keyword in java provides locking which ensures mutual exclusive
access of shared resource and prevent data race.
Q: What is the
Collections API?
A: The Collections API is a
set of classes and interfaces that support operations on collections of
objects.
Q: Does garbage
collection guarantee that a program will not run out of memory?
A: Garbage collection does
not guarantee that a program will not run out of memory. It is possible for
programs to use up memory resources faster than they are garbage collected. It
is also possible for programs to create objects that are not subject to garbage
collection.
Q: The immediate
superclass of the Applet class?
A: Panel is the immediate
superclass. A panel provides space in which an application can attach any other
component, including other panels.
Q: Which Java operator
is right associative?
A: The = operator is right
associative.
Q: What is the
difference between a break statement and a continue statement?
A: A break statement
results in the termination of the statement to which it applies (switch, for,
do, or while). A continue statement is used to end the current loop iteration
and return control to the loop statement.
Q: If a variable is
declared as private, where may the variable be accessed?
A: A private variable may
only be accessed within the class in which it is declared.
Q: What is the purpose
of the System class?
A: The purpose of the
System class is to provide access to system resources.
Q: List primitive Java
types?
A: The eight primitive
types are byte, char, short, int, long, float, double, and boolean.
Q: What is the relationship
between clipping and repainting under AWT?
A: When a window is
repainted by the AWT painting thread, it sets the clipping regions to the area
of the window that requires repainting.
Q: Which class is the
immediate superclass of the Container class?
A: Component class is the
immediate super class.
Q: What class of
exceptions are generated by the Java run-time system?
A: The Java runtime system
generates RuntimeException and Error exceptions.
Q: Under what conditions
is an object's finalize() method invoked by the garbage collector?
A: The garbage collector
invokes an object's finalize() method when it detects that the object has
become unreachable.
Q: How can a dead thread
be restarted?
A: A dead thread cannot be
restarted.
Q: Which arithmetic operations
can result in the throwing of an ArithmeticException?
A: Integer / and % can
result in the throwing of an ArithmeticException.
Q: Variable of the
boolean type is automatically initialized as?
A: The default value of the
boolean type is false.
Q: Can try statements be
nested?
A: Yes
Q: What are
ClassLoaders?
A: A class loader is an
object that is responsible for loading classes. The class ClassLoader is an
abstract class.
Q: What is the
difference between an Interface and an Abstract class?
A: An abstract class can
have instance methods that implement a default behavior. An Interface can only
declare constants and instance methods, but cannot implement default behavior
and all methods are implicitly abstract. An interface has all public members and
no implementation.
Q: What will happen if
static modifier is removed from the signature of the main method?
A: Program throws
"NoSuchMethodError" error at runtime .
Q: What is the default
value of an object reference declared as an instance variable?
A: Null, unless it is
defined explicitly.
Q: Can a top level class
be private or protected?
A: No, a top level class
can not be private or protected. It can have either "public" or no
modifier.
Q: Why do we need
wrapper classes?
A: We can pass them around
as method parameters where a method expects an object. It also provides utility
methods.
Q: What is the
difference between error and an exception?
A: An error is an
irrecoverable condition occurring at runtime. Such as OutOfMemory error.
Exceptions are conditions that occur because of bad input etc. e.g.
FileNotFoundException will be thrown if the specified file does not exist.
Q: Is it necessary that
each try block must be followed by a catch block?
A: It is not necessary that
each try block must be followed by a catch block. It should be followed by
either a catch block or a finally block.
Q: When a thread is
created and started, what is its initial state?
A: A thread is in the ready
state as initial state after it has been created and started.
Q: What is the Locale
class?
A: The Locale class is used
to tailor program output to the conventions of a particular geographic,
political, or cultural region.
Q: What are synchronized
methods and synchronized statements?
A: Synchronized methods are
methods that are used to control access to an object. A synchronized statement
can only be executed after a thread has acquired the lock for the object or
class referenced in the synchronized statement.
Q: What is runtime
polymorphism or dynamic method dispatch?
A: Runtime polymorphism or
dynamic method dispatch is a process in which a call to an overridden method is
resolved at runtime rather than at compile-time. In this process, an overridden
method is called through the reference variable of a superclass.
Q: What is Dynamic Binding(late
binding)?
A: Binding refers to the
linking of a procedure call to the code to be executed in response to the call.
Dynamic binding means that the code associated with a given procedure call is
not known until the time of the call at run-time.
Q: Can constructor be
inherited?
A: No, constructor cannot
be inherited.
Q: What are the
advantages of ArrayList over arrays?
A: ArrayList can grow
dynamically and provides more powerful insertion and search mechanisms than
arrays.
Q: Why deletion in LinkedList
is fast than ArrayList?
A: Deletion in linked list
is fast because it involves only updating the next pointer in the node before
the deleted node and updating the previous pointer in the node after the
deleted node.
Q: How do you decide
when to use ArrayList and LinkedList?
A: If you need to
frequently add and remove elements from the middle of the list and only access
the list elements sequentially, then LinkedList should be used. If you need to
support random access, without inserting or removing elements from any place
other than the end, then ArrayList should be used.
Q: What is a Values
Collection View ?
A: It is a collection
returned by the values() method of the Map Interface, It contains all the
objects present as values in the map.
Q: What is dot operator?
A: The dot operator(.) is
used to access the instance variables and methods of class objects.It is also
used to access classes and sub-packages from a package.
Q: Where and how can you
use a private constructor?
A: Private constructor is
used if you do not want other classes to instantiate the object and to prevent
subclassing.T
Q: What is type casting?
A: Type casting means
treating a variable of one type as though it is another type.
Q: Describe life cycle
of thread?
A: A thread is a execution
in a program. The life cycle of a thread include:
·
Newborn state
·
Runnable state
·
Running state
·
Blocked state
·
Dead state
Q: What is the
difference between the >> and >>> operators?
A: The >> operator
carries the sign bit when shifting right. The >>> zero-fills bits that
have been shifted out.
Q: Which method of the
Component class is used to set the position and size of a component?
A: setBounds() method is
used for this purpose.
Q: What is the range of
the short type?
A: The range of the short
type is -(2^15) to 2^15 - 1.
Q: What is the immediate
superclass of Menu?
A: MenuItem class
Q: Does Java allow
Default Arguments?
A: No, Java does not allow
Default Arguments.
Q: Which number is
denoted by leading zero in java?
A: Octal Numbers are
denoted by leading zero in java, example: 06
Q: Which number is
denoted by leading 0x or 0X in java?
A: Hexadecimal Numbers are
denoted by leading 0x or 0X in java, example: 0XF
Q: Break statement can
be used as labels in Java?
A: Yes, an example can be break one;
Q: Where import
statement is used in a Java program?
A: Import statement is
allowed at the beginning of the program file after package statement.
Q: Explain suspend()
method under Thread class>
A: It is used to pause or
temporarily stop the execution of the thread.
Q: Explain isAlive()
method under Thread class?
A: It is used to find out
whether a thread is still running or not.
Q: What is
currentThread()?
A: It is a public static
method used to obtain a reference to the current thread.
Q: Explain main thread
under Thread class execution?
A: The main thread is
created automatically and it begins to execute immediately when a program
starts. It ia thread from which all other child threads originate.
Q: Life cycle of an
applet includes which steps?
A: Life cycle involves the
following steps:
·
Initialization
·
Starting
·
Stopping
·
Destroying
·
Painting
Q: Why is the role of
init() method under applets?
A: It initializes the
applet and is the first method to be called.
Q: Which method is
called by Applet class to load an image?
A: getImage(URL object,
filename) is used for this purpose.
Q: Define code as an
attribute of Applet?
A: It is used to specify
the name of the applet class.
Q: Define canvas?
A: It is a simple drawing
surface which are used for painting images or to perform other graphical
operations.
Q: Define Network
Programming?
A: It refers to writing
programs that execute across multiple devices (computers), in which the devices
are all connected to each other using a network.
Q: What is a Socket?
A: Sockets provide the communication
mechanism between two computers using TCP. A client program creates a socket on
its end of the communication and attempts to connect that socket to a server.
Q: Advantages of Java
Sockets?
A: Sockets are flexible and
sufficient. Efficient socket based programming can be easily implemented for
general communications. It cause low network traffic.
Q: Disadvantages of Java
Sockets?
A: Socket based
communications allows only to send packets of raw data between applications.
Both the client-side and server-side have to provide mechanisms to make the
data useful in any way.
Q: Which class is used
by server applications to obtain a port and listen for client requests?
A: java.net.ServerSocket
class is used by server applications to obtain a port and listen for client
requests
Q: Which class
represents the socket that both the client and server use to communicate with
each other?
A: java.net.Socket class
represents the socket that both the client and server use to communicate with
each other.
Q: Why Generics are used
in Java?
A: Generics provide
compile-time type safety that allows programmers to catch invalid types at
compile time. Java Generic methods and generic classes enable programmers to
specify, with a single method declaration, a set of related methods or, with a
single class declaration, a set of related types.
Q: What environment
variables do I need to set on my machine in order to be able to run Java
programs?
A: CLASSPATH and PATH are
the two variables.
Q: Is there any need to
import java.lang package?
A: No, there is no need to
import this package. It is by default loaded internally by the JVM.
Q: What is Nested
top-level class?
A: If a class is declared
within a class and specify the static modifier, the compiler treats the class
just like any other top-level class. Nested top-level class is an Inner class.
Q: What is
Externalizable interface?
A: Externalizable is an
interface which contains two methods readExternal and writeExternal. These
methods give you a control over the serialization mechanism.
Q: If System.exit (0);
is written at the end of the try block, will the finally block still execute?
A: No in this case the
finally block will not execute because when you say System.exit (0); the
control immediately goes out of the program, and thus finally never executes.
Q: What is daemon
thread?
A: Daemon thread is a low
priority thread, which runs intermittently in the back ground doing the garbage
collection operation for the java runtime system.
Q: Which method is used
to create the daemon thread?
A: setDaemon method is used
to create a daemon thread.
Q: Which method must be
implemented by all threads?
A: All tasks must implement
the run() method
Q: What is the
GregorianCalendar class?
A: The GregorianCalendar
provides support for traditional Western calendars
Q: What is the
SimpleTimeZone class?
A: The SimpleTimeZone class
provides support for a Gregorian calendar .
Q: What is the
difference between the size and capacity of a Vector?
A: The size is the number
of elements actually stored in the vector, while capacity is the maximum number
of elements it can store at a given instance of time.
Q: Can a vector contain
heterogenous objects?
A: Yes a Vector can contain
heterogenous objects. Because a Vector stores everything in terms of Object.
Q: What is an
enumeration?
A: An enumeration is an
interface containing methods for accessing the underlying data structure from
which the enumeration is obtained. It allows sequential access to all the
elements stored in the collection.
Q: What is difference between
Path and Classpath?
A: Path and Classpath are
operating system level environment variales. Path is defines where the system
can find the executables(.exe) files and classpath is used to specify the
location of .class files.
Q: Can a class declared as
private be accessed outside it's package?
A: No, it's not possible to
accessed outside it's package.
Q: What are the
restriction imposed on a static method or a static block of code?
A: A static method should
not refer to instance variables without creating an instance and cannot use
"this" operator to refer the instance.
Q: Can an Interface
extend another Interface?
A: Yes an Interface can
inherit another Interface, for that matter an Interface can extend more than
one Interface.
Q: Which object oriented
Concept is achieved by using overloading and overriding?
A: Polymorphism
Q: What is an object's
lock and which object's have locks?
A: An object's lock is a
mechanism that is used by multiple threads to obtain synchronized access to the
object. A thread may execute a synchronized method of an object only after it
has acquired the object's lock.
Q: What is Downcasting?
A: It is the casting from a
general to a more specific type, i.e. casting down the hierarchy.
Q: What are order of
precedence and associativity and how are they used?
A: Order of precedence
determines the order in which operators are evaluated in expressions.
Associatity determines whether an expression is evaluated left-to-right or
right-to-left.
Q: If a method is
declared as protected, where may the method be accessed?
A: A protected method may
only be accessed by classes or interfaces of the same package or by subclasses
of the class in which it is declared.
Q: What is the
difference between inner class and nested class?
A: When a class is defined
within a scope of another class, then it becomes inner class. If the access
modifier of the inner class is static, then it becomes nested class.
Q: What restrictions are
placed on method overriding?
A: 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.
Q: What is constructor
chaining and how is it achieved in Java?
A: A child object
constructor always first needs to construct its parent. In Java it is done via
an implicit call to the no-args constructor as the first statement.
Q: Can a double value be
cast to a byte?
A: Yes, a double value can
be cast to a byte.
Q: How does a try
statement determine which catch clause should be used to handle an exception?
A: When an exception is
thrown within the body of a try statement, the catch clauses of the try
statement are examined in the order in which they appear. The first catch
clause that is capable of handling the exception is executed. The remaining
catch clauses are ignored.
Q: What will be the
default values of all the elements of an array defined as an instance variable?
A: If the array is an array
of primitive types, then all the elements of the array will be initialized to
the default value corresponding to that primitive type.
Q. What if the main method is
declared as private?
A: The program compiles properly but at runtime it will give “Main
method not public.” message.
Q. What is meant by pass by
reference and pass by value in Java?
A:Pass
by reference means, passing the address itself rather than passing the value.
Pass by value means passing a copy of the value.
Q. If you’re overriding the
method equals() of an object, which other method you might also
consider?
A: hashCode()
Q. What is Byte Code?
Or
Q. What gives java it’s
“write once and run anywhere” nature?
A: 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.
Q. Expain the reason for each
keyword of public static void main(String args[])?
A: 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.
Q. What are the differences
between == and .equals()?
Or
Q. what is difference between
== and equals?
Or
Q. Difference between == and
equals method
Or
Q. What would you use to
compare two String variables – the operator == or the
method equals()?
Or
Q. How is it possible for two
String objects with identical values not to be equal under
the == operator?
A: 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.
public class EqualsTest {
public
static void main(String[]
args) {
String s1 = “abc”;
String s2 = s1;
String s5 = “abc”;
String s3 = new String(”abc”);
String s4 = new String(”abc”);
System.out.println(”== comparison : ” + (s1 == s5));
System.out.println(”== comparison : ” +(s1 == s2));
System.out.println(”Using equals method : ” +
s1.equals(s2));
System.out.println(”== comparison : ” + s3 == s4);
System.out.println(”Using equals method : ” +
s3.equals(s4));
}
}
Output
== comparison : true
== comparison : true
Using equals method : true
== comparison : false
Using equals method : true
Q. What if the static
modifier is removed from the signature of the main method?
Or
Q. What if I do not provide
the String array as the argument to the method?
A: Program compiles. But at runtime throws an error
“NoSuchMethodError”.
Q. Why oracle Type 4 driver
is named as oracle thin driver?
A: 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.
Q. What is the difference
between final, finally and finalize? What do you understand
by the java final keyword?
Or
Q. What is final,
finalize() and finally?
Or
Q. What is
finalize() method?
Or
Q. What does it mean that a
class or member is final?
A:
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 sub-classed. 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.
Q. What is the Java API?
A: The Java API is a large collection of ready-made software
components that provide many useful capabilities, such as graphical user
interface (GUI) widgets.
Q. What is the
GregorianCalendar class?
A: The GregorianCalendar provides support for traditional Western calendars.
Q. What is the ResourceBundle
class?
A: 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.
Q. Why there are no global
variables in Java?
A: 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.
Q. How to convert String to
Number in java program?
A: The
valueOf() function of Integer class is is used to convert string to Number.
Here is the code example:
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();
Q. What is the SimpleTimeZone
class?
A: The SimpleTimeZone class provides support for a Gregorian
calendar.
Q. What is the difference
between a while statement and a do statement?
A: A while statement (pre test) checks at the beginning of a loop to
see whether the next loop iteration should occur. A do while statement(post
test) checks at the end of a loop to see whether the next iteration of a loop
should occur. The do statement will always execute the loop body at least once.
Q. What is the Locale class?
A: The Locale class is used to tailor a program output to the
conventions of a particular geographic, political, or cultural region.
Q. Describe the principles of
OOPS.
A: There are three main principals of oops which are called
Polymorphism, Inheritance and Encapsulation.
Q. Explain the Inheritance
principle.
A: 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
Q. What is implicit casting?
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
int i = 1000;
long j = i; //Implicit casting
Q. Is sizeof a keyword in
java?
A: The sizeof is not a keyword.
Q. What is a native method?
A: A native method is a method that is implemented in a language
other than Java.
Q. In System.out.println(),
what is System, out and println?
A: System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the
out object.
Q. What are Encapsulation,
Inheritance and Polymorphism
Or
Q. Explain the Polymorphism
principle. Explain the different forms of Polymorphism.
A: 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 (Static
Polimorphism)
Method overriding (Dynamic or
Runtime Polimorphism) through inheritance
Method overriding (Dynamic or
Runtime Polimorphism) through the Java interface
Q. What is explicit casting?
A: Explicit casting in the process in which the complier are
specifically informed to about transforming the object.
Example
long i = 700.20;
int j = (int) i; //Explicit casting
Q. What is the Java Virtual
Machine (JVM)?
A: The Java Virtual Machine is software that can be ported onto
various hardware-based platforms
Q. What do you understand by
downcasting?
A: The process of Downcasting refers to the casting from a general to
a more specific type, i.e. casting down the hierarchy
Q. What are Java Access
Specifiers?
Or
Q. What is the difference
between public, private, protected and default Access Specifiers?
Or
Q. What are different types
of access modifiers?
A: 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
Q. Which class is the
superclass of every class?
A: Object.
Q. Name primitive Java types.
A: The 8 primitive types are byte, char, short, int, long, float,
double, and boolean. Additional is String.
Q. What is the difference
between static and non-static variables?
Or
Q. What are “class
variables”?
Or
Q. What is static in java?
Or
Q. What is a static method?
A: 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.
Q. What is the difference between the boolean & operator and the && operator?
A: 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.
Q. How does Java handle
integer overflows and underflows?
A: It
uses those low order bytes of the result that can fit into the size of the type
allowed by the operation.
Q. What if I write static
public void instead of public static void?
A: Program
compiles and runs properly.
Q. What is the difference between declaring a variable and defining a variable?
A: 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.
Q. What type of parameter
passing does Java support?
A: 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.
Q. Explain the Encapsulation principle.
A: 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.
Q. What do you understand by
a variable?
A: Variable is a named memory location that can be easily referred in
the program. The variable is used to hold the data and it can be changed during
the course of the execution of the program.
Q. What do you understand by
numeric promotion?
A: 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.
Q. What do you understand by
casting in java language? What are the types of casting?
A: 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.
Q. What is the first argument
of the String array in main method?
A: 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.
Q. How can one prove that the
array is not null but empty?
A: Print array.length. 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
array.length.
Q. Can an application have
multiple classes having main method?
A: 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.
Q. When is static variable
loaded? Is it at compile time or runtime? When exactly a static block
is loaded in Java?
A: 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.
Q. Can I have multiple main
methods in the same class?
A: We can have multiple overloaded main methods but there can be only
one main method with the following signature :
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.
Q. Explain working of Java
Virtual Machine (JVM)?
A: 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.
Q. How can I swap two
variables without using a third variable?
A: 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:
int a=5, b=10;
a=a+b;
b=a-b;
a=a-b;
You use an XOR swap (BBEST
APPROACH), as in case of using above approach it may goes over/under flow. For
example:
int a = 5;
int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
Q. What is data
encapsulation?
A: 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.
Q. What is reflection API?
How are they implemented?
A: 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.
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?
A: Yes, the JVM maintains a cache by itself. It creates the Objects
on the HEAP, but references to those objects are on the STACK.
Q. What is phantom memory?
A: Phantom memory is false memory. Memory that does not exist in
reality.
Q. Can a method be static and
synchronized?
A: A
static method can be synchronized. If you do so, the JVM will obtain a lock on
the java.lang.Class instance associated with the object. It is similar to
saying:
synchronized(XYZ.class) {}
Q. What is difference between
String and StringTokenizer?
A: A StringTokenizer is utility class used to break up string.
Example:
StringTokenizer st = new StringTokenizer(”Hello World”);
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Output:
Hello
World
Q: What is transient
variable?
A: 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:
transient identifies
a variable not to be written out when an instance is serialized (It
can't be copied to remove system)
volatile indicates
that the field is used by synchronized threads and that the compiler
should not attempt to perform optimizations with it.
When more than one thread
share a (volatile) data it is checked every time. Every thread keeps the
latest value of volatile variable.
Q: Name the containers which
uses Border Layout as their default layout?
A: Containers which uses Border Layout as their default are: window,
Frame and Dialog classes.
Q: What do you understand by
Synchronization?
A: 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:
public synchronized void Method1() {
//Appropriate
method-related code.
}
E.g. Synchronizing a block of
code inside a function:
public myFunction() {
synchronized(this) {
//Synchronized
code here.
}
}
Java Interview Questions.
OOPS
Q. What is
meant by Object Oriented Programming?
A. OOP is a method of programming in which programs
are organised as cooperative collections of objects. Each object is an instance
of a class and each class belong to a hierarchy.
Q. What is a Class?
A. Class is a template for a set of objects that
share a common structure and a common behaviour.
Q. What is an Object?
A. Object is an instance of a class. It has
state,behaviour and identity. It is also called as an instance of a class.
Q. What is an Instance?
A. An instance has state, behaviour and identity.
The structure and behaviour of similar classes are defined in their common
class. An instance is also called as an object.
Q. What are the core OOP's concepts?
A. Abstraction, Encapsulation,Inheritance and
Polymorphism are the core OOP's concepts.
Q. What is meant by abstraction?
A. Abstraction defines the essential
characteristics of an object that distinguish it from all other kinds of
objects. Abstraction provides crisply-defined conceptual boundaries relative to
the perspective of the viewer. Its the process of focussing on the essential
characteristics of an object. Abstraction is one of the fundamental elements of
the object model.
Q. What is meant by Encapsulation?
A. Encapsulation is the process of
compartmentalising the elements of an abtraction that defines the structure and
behaviour. Encapsulation helps to separate the contractual interface of an
abstraction and implementation.
Q. What is meant by Inheritance?
A. Inheritance is a relationship among classes,
wherein one class shares the structure or behaviour defined in another class.
This is called Single Inheritance. If a class shares the structure or behaviour
from multiple classes, then it is called Multiple Inheritance. Inheritance
defines "is-a" hierarchy among classes in which one subclass inherits
from one or more generalised superclasses.
Q. What is meant by Polymorphism?
A. Polymorphism literally means taking more than
one form. Polymorphism is a characteristic of being able to assign a different
behavior or value in a subclass, to something that was declared in a parent
class.
Q. What is an Abstract Class?
A. Abstract class is a class that has no instances.
An abstract class is written with the expectation that its concrete subclasses
will add to its structure and behaviour, typically by implementing its abstract
operations.
Q. What is an Interface?
A. Interface is an outside view of a class or
object which emphaizes its abstraction while hiding its structure and secrets
of its behaviour.
Q. What is a base class?
A. Base class is the most generalised class in a
class structure. Most applications have such root classes. In Java, Object is
the base class for all classes.
Q. What is a subclass?
A. Subclass is a class that inherits from one or
more classes.
Q. What is a superclass?
A. Superclass is a class from which another class
inherits.
Q. What is a constructor?
A. Constructor is an operation that creates an
object and/or initialises its state.
Q. What is a destructor?
A. Destructor is an operation that frees the state
of an object and/or destroys the object itself. In Java, there is no concept of
destructors. Its taken care by the JVM.
Q. What is meant by Binding?
A. Binding denotes association of a name with a
class
Q. What is meant by static binding?
A. Static binding is a binding in which the class
association is made during compile time. This is also called as Early binding.
Q. What is meant by Dynamic binding?
A. Dynamic binding is a binding in which the class
association is not made until the object is created at execution time. It is
also called as Late binding.
Q. Define Modularity?
A. Modularity is the property of a system that has
been decomposed into a set of cohesive and loosely coupled modules.
Q. What is meant by Persistence?
A. Persistence is the property of an object by
which its existence transcends space and time.
Q. What is colloboration?
A. Colloboration is a process whereby several
objects cooperate to provide some higher level behaviour.
Q. In Java, How to make an object completely encapsulated?
A. All the instance variables should be declared as
private and public getter and setter methods should be provided for accessing
the instance variables.
Q. How is polymorphism acheived in java?
A. Inheritance,
Overloading and Overriding are used to acheive Polymorphism in java.
Core Java Interview Questions
Q. What are the most important features of Java?
A. Java is object oriented,
platform independent, secure, robust, simple, etc
Q. Which one of them do you consider the best feature of Java?
A. Platform independence.
Q. What do you mean by platform independence?
A. Platform independence
means that we can write and compile the java code in one platform (eg Windows)
and can execute the class in any other supported platform eg
(Linux,Solaris,etc).
Q. What is byte code?
A. Byte code is a set of
instructions generated by the compiler. JVM executes the byte code.
Q. How does Java acheive platform independence?
A. A Java source file on
compilation produces an intermediary . Class rather than a executable file.
This . Class file is interpreted by the JVM. Since JVM acts as an intermediary
layer.
Q. What is a JVM?
A. JVM is Java Virtual
Machine which is a run time environment for the compiled java class files.
Q. Are JVM's platform independent?
A. JVM's are not platform
independent. JVM's are platform specific run time implementation provided by
the vendor. A Windows JVM cannot be installed in Linux.
Q. Who provides the JVM?
A. Any software vendor can
provide a JVM but it should comply to the Java langauge specification.
Q. What is the difference between a JDK and a JVM?
A. JDK is Java Development
Kit which is for development purpose and it includes execution environment
also. But JVM is purely a run time environment and hence you will not be able
to compile your source files using a JVM.
Q. What is a pointer and does Java support pointers?
A. Pointer is a reference
handle to a memory location. Improper handling of pointers leads to memory
leaks and reliability issues hence Java doesn't support the usage of pointers.
Q. How is an object reference different from a pointer?
A. Both object reference
and pointer point to the memory location of the object. You can manipulate
pointers but not object references.
Q. Does Java support multiple inheritance?
A. Java doesn't support
multiple inheritance.
Q. Why Java doesn't support multiple inheritance?
A. When a class inherits
from more than class, it will lead to the diamond problem - say A is the super
class of B and C & D is a subclass of both B and C. D inherits properties
of A from two different inheritance paths ie via both B & C. This leads to
ambiguity and related problems, so multiple inheritance is not allowed in Java.
Q. Is Java a pure object oriented language?
A. Java is a pure object
oriented language. Except for the primitives everything else are objects in
Java.
Q. What is the difference between Path and Classpath?
A. Path and Classpath are
operating system level environment variales. Path is used define where the
system can find the executables(. Exe) files and classpath is used to specify
the location . Class files.
Q. Why does Java not support operator overloading?
A. Operator overloading
makes the code very difficult to read and maintain. To maintain code
simplicity, Java doesn't support operator overloading.
Q. What are keywords?
Keywords cannot be used as identifiers.
Q. What are reserved keywords? And can you name few reserved keywords?
A. Few of the words are
reserved as keywords for future usage. Compiler forces the developer not to use
a reserved keyword. const and
Q. What is the overhead of introducing a new keyword?
A. When a new keyword is
used in a new version of the JDK, there is high chances that has been used by
developers as identifiers. This make tougher for the code base to migrate to
new version since it requires code change, recompilation,testing and release
cycle.
Q. Have you come across difficulties due to introduction of a new keyword?
A. Yes. enum keyword was
used extensively as identifier in one of our project - we had to change the
code in a lot of places to migrate it to newer v ersion.
Q. What are identifiers?
A. Identifiers are names
given to a variable, method, class and interface. Identifiers must conform to
the following rules:a. The identifiers can contain a to z, A to Z,0 to 9,_ and
$.b. Special characters other than _ and $ cannot be used in identifiers. C.
Identifiers cannot start with numbers. d. keywords cannot be used as
identifiers.
Q. What is meant by naming conventions? And what are the naming conventions followed in Java?
A. Naming conventions are
part of coding standards which are prescribed for better readability and
maintenance. The following are simple conventions followed in Java:1. Instance
and local Variables should start with a lowercase and subsequent word should
start with a capital letter. Examples: int quantity; double unitPrice; 2. Class
level variables ie constants should be in capital letters and _ is used word
seprator final static double PI = 3.14; final static int MAX_PRIORITY = 10;3.
Method names should start with small case and subsequent word should be capital
letter. public double getAvailableBalance(String accountNo) throws
InvalidAccountException{}4. Classes and Interfaces should start with a capital
letter and subsequent words should also be capital letters. public class
HelloWorld{}
Q. If you dont follow coding standards, will it result in compilation error?
A. No. These are standards.
Each company or fot that matter each software unit might have its own coding
standards. These are not enforced by the compiler.
Q. How to make sure that all programmers are following the coding standards?
A. The best and simple way
is to do peer reviews and code walkthroughs. You can use external plugins to
your IDE (integrated development environment) to enforce during coding itself.
Q. What are literals?
A. Literals are source code
representation of primitive data types.
Q. Name the eight data types which are available in Java?
A. boolean, byte, short,
int, long, float, double and char.
Q. Are primitive data types objects in Java?
A. Primitive data types are
not objects.
Q. What are all the number data types? And are they signed or unsigned?
A. Excpet boolean and char,
others are number data types and they are all signed which means that they can
hold both positive and negative values.
Q. What are the possible values that a boolean data type can hold?
A. The boolean is the
simplest data type which can hold true or false.
Q. What are default values?
A. Values which are
defaulted during object initialisation are called default values. Each data
type has a default value.
Q. What are the default values of primitive data types?
A. For boolean data type,
it is false. For byte,short,int and long, it is 0. For float and double, it is
0.0. For char, the default value is 'u000'.
Q. Are object references defaulted?
A. Yes. Object references
are defaulted to null.
Q. Are arrays defaulted?
A. If arrays is just
declared but not initialised then the array reference will be defaulted to
null. This is because arrays are objects in Java. Int arr[]; // Here the arr
reference is defaulted to null. If array values are not assigned, then will be
defaulted to their respective default values.double priceRange[] = new
double[3]; // Here all the elements in the array will be defaulted to 0.0 - the
default value of double. String str[] = new String[3]; // Here all the elements
will be defaulted to null - the default value for object references.
Q. Can you explain keyword , identifier and literal with an example?
A. Consider the below
statement:int i = 10;Here int is the keyword which has special meaning attached
Java programming langauge ie whatever is declared is an integer value. I is the
identifier or the variable name.10 is the literal or the actual value.
Q. What are the 3 ways to represent an integer value?
A. The following are the 3
different ways to represent an integer value:int i = 123 // this is the usual
decimal representation. Int i = 0123 // this is octal representation. Octal
values start with a zero. Int i = 0XCAAD // this is hexadecimal representation.
Hexadecimal values start with 0X.
Q. In how many ways a char value be represented?
A. Char value can be
represented in 3 ways. They are as follows:char ch = 'A'; // represented using
single quotes. Char ch = 'u0041'; // represented using unicode representation.
Char ch = 41; // represented using integer value.
Q. How is it possible to represent char using a integer value?
A. char is internally
represented as a unsigned 16 bit integer value ie it will accept integer values
from 0 to 65536.
Q. Can char be used when an integer value is expected?
A. Yes. A fine example is
switch statement will accept char value for multiway condition checking.
Q. Can char be manipulated like integers?
A. Yes possible. The below
is an example. Char ch = 'A';System.out.println(ch++); The above statement will
print B. ++ is a numeral operand and since char is internally represented as
integer, ++ operand can be applied on char value.
Q. What is Unicode?
A. A universal, 16-bit,
standard coded character set for the representation of all human scripts.
Q. What should i have to do if i have to print my name in Spanish?
A. Provide code...
Q. How will the below literal value be internally represented?
float f = 21.22;
A. It will be represented
as a double value. Floating point literals are always double by default. If you
want a float, you must append an F or f to the literal.
Q. Give your observation on the below statement.
A. int i = 10/0;
The statement will result in RuntimeException
(DivideByZeroException). Integer values cannot be divided by zero.
Q. Give your observation on the below statement.
A. double d = 10.12/0;
This will compile and execute fine. The result will be Infinity
Q. What is a Variable?
A. a variable is a facility
for storing data. The current value of the variable is the data actually stored
in the variable.
Q. What are the 3 types of variables?
A. There are 3 types of
variables in Java. They are :1. Local variables.2. Instance variables.3. Class
variables.
Q. What are Local variables?
A. Local varaiables are
those which are declared within a block of code like methods, loops, exception
blocks, etc. Local variables should be initialised before accessing them. Local
variables are stored on the stack, hence they are sometimes called stack
variables. They are also called as method variables or block variables.
Q. When are local variables eligible for garbage collection?
A. As soon as the block is
completed the variables are eligible for GC. Block could be a condition, a
loop, a exception block or a methodConsider the below class:public class Test {
public static void main (String str[]){ String name = str[0]; for (int i=0;
i<=10; i++){ System.out.println(name + i); } }}In the above the class, the
variable i is eligible for garbage collection immediately after the completion
of for loop.name string variable and str[] argument are eligible for GC after
the completion of main method.
Q. What are Instance variables?
A. Instance variables are
those which are defined at the class level. As we know, object have identity
and behaviour - the identity is provided by the instance variables. These are
also called as object variables. Instance variables need not be initialized
before using them. Instance variables will be initialized to their default
values automatically when not initialized.
Q. Are arrays primitive data types?
A. No. Arrays are not
primitives - they are objects.
Q. What are different ways to declare an array?
A. Object obj[]; // most
frequently used form of array declaration.Object []obj; // nothing wrong with
this. Object[] obj; // nothing wrong with this. int i[][]; // most frequently
form multi-dimensional arrayint[] i[]; // nothing wrong with this. int[] i[],j;
// nothing wrong with this. Important : i is double dimensional whereas j is
single dimensional.
Q. What are the 3 steps in defining arrays?
A. declaration,initialization
and assignmentint i[]; // array declaration. I[] = new int[2]; // array
initialization. I[0] = 10; i[1] = 7; i[2] = 9; // element value assignment.
What is the simplest way to defining an primitive array? The below statement
merges declaration,initialization and assignment into a single step:int i [] =
{10, 20, 30 40}; What is wrong with the below code segment?int i[] = new
int[5]System.out.println(i.length()) length is an instance variable of array
object - here it is given a method.
Q. What is wrong with the below code segment?
A. int i[5] = new int[]System.out.println(i.length)
length of an array should be given when it is initialized. Here it
is given during declaration. It will result in compilation error.
Q. What will be the output of the below code segment?
A. int i[] = new int[5]System.out.println(i.length)
It will print 6. Remember array indexes start with 0.
Q. What are the frequent RuntimeException's encountered because of improper coding with respect to arrays?
A. ArrayIndexOutOfBoundsException
and NullPointerException.
56. Should a main method be compulsorily declared in all java classes?
A. No not required. main
method should be defined only if the source class is a java application.
Q. What is the return type of the main method?
A. Main method doesn't
return anything hence declared void.
Q. Why is the main method declared static?
A. main method is the entry
point for a Java application and main method is called by the JVM even before
the instantiation of the class hence it is declared as static. static methods
can be called even before the creation of objects.
Q. What is the argument of main method?
A. main method accepts an
array of String objects as argument.
Q. How to pass an argument to main method?
A. You should pass the
argument as a command line argument. Command line arguments are seprated by a
space. The following is an example:java Hello Tom JerryIn the above command
line Hello is the class, Tom is the first argument and Jerry is the second
argument.
Q. What will happen if no argument is passed to the main method?
A. If you dont access the
argument, the main method will execute without any problem. If try to access
the argument, NullPointerException will be thrown.
Q. Can a main method be overloaded?
A. Yes. You can have any
number of main methods with different method signature and implementation in
the class.
Q. Can a main method be declared final?
A. Yes. Any inheriting
class will not be able to have it's own default main method.
Q.Does the order of public and static declaration matter in main method?
A. No it doesn't matter but
void should always come before main().
Q. Can a source file contain more than one Class declaration?
A. Yes. A single source
file can contain any number of Class declarations but only one of the class can
be declared as public.
Q. If a source file has 2 class declaration in it, on compilation how many class files will be created?
A. 2 class files will be
generated by the compiler.
Q. Can the first line of the source code be a comment?
A. Yes. Comments can appear
anywhere in the code. It is just a "skip this line" instruction to
the conpiler.
Q. Can the source file name and the class name in the file be different?
A. If the class in the
source is not of public access, then the name can be anything but should
confirm to identifier rules.
Q. Explain Inheritance?
A. Inheritance is a concept
where the properties and behaviour of a class is reused in another class. The
class which is being reused or inherited is called the super class or the
parent class. The class which is inheriting is called the subclass or the child
class of the inherited class.
Q. Does Java support multiple inheritance?
A. No. Java Supports only
single inheritance.
Q. Why Java doesn’t support muliple inheritance?
A. When a class inherits
from more than class, it will lead to inheritance path amibiguity (this is
normally calledthe diamond problem). Say A is the super class of B and C &
D is a subclass of both B and C. D inherits properties of A from two different
inheritance paths ie via both B & C. This leads to ambiguity and related
problems, so multiple inheritance is not allowed in Java.
Q. Which keyword is used for inheriting from another class?
A. extends keyword is used
for inheritance.
Q. Can a subclass be referenced for a super class object?
No. If Vehicle is super class and Car is the subclass then the
following reference would be wrong – Car c = new Vehicle();
Q. Can a parent class be referenced for a subclass object?
A. Yes. The below is an
example :Vehicle v = new Car();
Q. Can an interface be referenced for any object?
A. Yes. We can create a
object reference for an interface. The object should have provided the
implementation for the object.Runnable r = new Test(); Test class should have
implemented the runnable interface and overridded the run method.
Q. What are constructors?
A. Constructors are used to
initialise an object. Constructors are invoked when the new operator on the
class are called.
Q. What are the decalaration of a constructor?
A. Constructor name should
be the same as class name. Constructors doesn’t return anything – not even
void.
Q.Does constructors throw exceptions?
A. Yes. Like methods
constructors can also throw exceptions.
Q. Can constructors be overloaded?
A. Yes. Constructors can be
overloaded.
80. Is it compulsory to define a constructor for a class?
A. No. If you don’t define
a constructor, the compiler will provide a default constructor.
Q. What is a default constructor?
A. Default constructor is a
no argument constructor which initialises the instance variables to their
default values. This will be provided by the compiler at the time of
compilation. Default constructor will be provided only when you don’t have any
constructor defined.
Q. Explain about “this” operator?
A. “this” is used to refer
the currently executing object and it’s state. “this” is also used for chaining
constructors and methods.
Q. Explain about “super” operator?
A. “super” is used to refer
to the parent object of the currently running object. “super” is also to invoke
super class methods and classes.
Q. What is the sequence of constructor invocation?
A. When you instantiate a
subclass, the object will begin with an invocation of the constructor in the
base class and initialize downwards through constructors in each subclass till
it reaches the final subclass constructor. Note: This top down imagery for
class inheritance, rather than a upward tree-like approach, is standard in OOP
but is sometimes confusing to newcomers.
Q. Can a constructor be defined for an interface?
A. No
Q. Explain Polymorphism?
A. The dictionary
definition of polymorphism refers to a principle in biology in which an
organism or species can have many different forms or stages. This principle can
also be applied to object-oriented programming and languages like the Java
language. Subclasses of a class can define their own unique behaviors and yet
share some of the same functionality of the parent class. Polymorphism is the
capability of an action or method to do different things based on the object
that it is acting upon. Overloading and overriding are two types of
polymorphism.
Q. What is Overloading?
A. In a class, if two
methods have the same name and a different signature,it is known as overloading
in Object oriented concepts.
Q. When to use overloading?
A. Overloading is a powerful
feature, but you should use it only as needed. Use it when you actually do need
multiple methods with different parameters, but the methods do the same thing.
That is, don't use overloading if the multiple methods perform different tasks.
This approach will only confuse other developers who get a peek at your code.
Q. Explain Overriding?
A. Overriding means, to
give a specific definition by the derived class for a method implemented in the
base class.
Q. What is a package?
A. Package is a collection
of related classes and interfaces. package declaration should be first
statement in a java class.
Q. Which package is imported by default?
A. java.lang package is
imported by default even without a package declaration.
Q. Is package statement mandatory in a Java source file?
It's not mandatory.
Q. What will happen if there is no package for Java source file?
A. The classes will
packaged into a no name default package. In practice, we always put classes
into a meaningful package.
Q. What is the impact using a * during importing(for example import java. Io.*;?
A. When a * is used in a
import statement, it indicates that the classes used in the current source can
be available in the imported package. Using slightly increases the compilation
time but has no impact on the execution time.
Q. Can a class declared as private be accessed outside it's package?
A. A class can't be
declared as private. It will result in compile time error.
Q. Can a class be declared as protected?
A. A class can't be
declared as protected. only methods can be declared as protected.
Q. What is the access scope of a protected method?
A. A protected method can
be accessed by the classes within the same package or by the subclasses of the
class in any package.
Q. What is the impact of marking a constructor as private?
A. Nobody can instantiate
the class from outside that class.
Q. What is meant by default access?
A. default access means the
class,method,construtor or the variable can be accessed only within the
package.
Q. Is default a keyword?
A. Yes. default is a
keyword but is associated with switch statement not with access specifiers.
Q.Then how to give default access to a class?
A. If you dont specify any
access, then it means the class is of default access.
Q. Can i give two access specifiers to a method at the same time?
A. No its not possible. It
will result in compile time error.
Q. What is the purpose of declaring a variable as final?
A. A final variable's value
can't be changed. final variables should be initialized before using them.
Q. Can a final variable be declared inside a method?
A. No. Local variables
cannot be declared as final.
Q. What is the impact of declaring a method as final?
A. A method declared as
final can't be overridden. A sub-class doesn't have the independence to provide
different implementation to the method.
Q. I don't want my class to be inherited by any other class. What should i do?
A. You should declared your
class as final. A class declared as final can't be inherited by any other
class.
Q. When will you declare a class as final?
A. When a class is
independent and completely concrete in nature, then the class has to be marked
as final.
Q. Can you give few examples of final classes defined in Java API?
A. java.lang.
String,java.lang.Math are final classes.
Q. How to define a constant variable in Java?
A. The variable should be
declared as static and final. So only one copy of the variable exists for all
instances of the class and the value can't be changed also. Static final int PI
= 3.14; is an example for constant.
Q. Can a class be declared as static?
A. No a class cannot be
defined as static. Only a method,a variable or a block of code can be declared
as static.
Q. When will you define a method as static?
A. When a method needs to
be accessed even before the creation of the object of the class then we should
declare the method as static.
Q. I want to print "Hello" even before main is executed. How will you acheive that?
A. Print the statement
inside a static block of code. Static blocks get executed when the class gets
loaded into the memory and even before the creation of an object. Hence it will
be executed before the main method.
Q. What is the use of a static code block?
A. static code blocks
could be used for one time initialisation activities.
Q. Can’t you use the constructor for initialisation rather than static block?
A. Constructors are used
for object level initialisation whereas the static block are used for class
level initialisation ie to initialise constants.
Q. Will the static block be executed for each object?
A. No. It will be executed
only once for each class ie at the time of loading a class.
Q. What are the restriction imposed on a static method or a static block of code?
A. A static method
should not refer to instance variables without creating an instance. It cannot
use "this" or "super". A static method can acces
only static variables or static methods.
Q. When overriding a static method, can it be converted to a non-static method?
A. No. It should be static only.
Q. What is the importance of static variable?
A. static variables
are class level variables where all objects of the class refer to the same
variable. If one object changes the value then the change gets reflected in all
the objects.
Q. Can we declare a static variable inside a method?
A. Static varaibles are class
level variables and they can't be declared inside a method. If declared, the
class will not compile.
Q. What is an Abstract Class and what is it's purpose?
A. A Class which doesn't
provide complete implementation is defined as an abstract class. Abstract
classes enforce abstraction.
Q. What is the use of a abstract variable?
A. Variables can't be
declared as abstract. only classes and methods can be declared as abstract.
Q. Can a abstract class be declared final?
A. Not possible. An
abstract class without being inherited is of no use and a final class cannot be
inherited. So if a abstract class is declared as final, it will result in
compile time error.
Q. What is an abstract method?
A. An abstract method is a
method whose implementation is deferred to a subclass.
Q. Can a abstract class be defined without any abstract methods?
A. Yes it's possible. This
is basically to avoid instance creation of the class.
Q. What happens if a subclass has inherited a abstract class but has not provided implementation for all the abstract methods of the super class?
A. Then the subclass also
becomes abstract. This will be enforced by the compiler.
Q. What happens if a class has implemented an interface but has not provided implementation for a method in a interface?
A. Its the same as the
earlier answer. The class has to be marked as abstract. This will be enforced
by the compiler.
Q. Can you create an object of an abstract class?
A. Not possible. Abstract
classes are not concrete and hence can't be instantiated. If you try
instantiating, you will get compilation error.
Q. Can I create a reference for a an abstract class?
A. Yes. You can create a
reference for an abstract class only when the object being has provided the
implementation for the abstract class - it means that the object should be of a
concrete subclass of the abstract class. This applies to interfaces also. Below
is an example for interface referencing an object:java. Sql. Connection con =
java. Sql.DriverManager. GetConnection("");
Q. Can a class be marked as native?
A. No. Only methods can be
marked as native.
Q. What is the use of native methods?
A. When a java method
accesses native library written in someother programming language then the
method has to be marked as native.
Q. What is the disadvantage of native methods?
A. By using native methods,
the java program loses platform independence - the accessed platform might be
tightly coupled with a operating system hence java program also loses OS
independence.
Q. What is the purpose of transient modifier?
A. Only variables can be
marked as transient. Variables marked as transient will not be persisted during
object persistence.
Q. What is the purpose of volatile modifier?
A. Only variables can be
marked as volatile. Volatile variables might be modified asynchronously.
Q. What is an Interface?
A. Interfaces say what a
class must do but does not say how a class must do it. Interfaces are 100%
abstract.
Q. Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2. Can i create an object of Class C?
A. No not possible. Class C
should provide implementation for all the methods in the Interface I. Since
Class C didn't provide implementation for m1 method, it has to be declared as
abstract. Abstract classes can't be instantiated.
Q. Can a method inside a Interface be declared as final?
A. No not possible. Doing
so will result in compilation error. public and abstract are the only
applicable modifiers for method declaration in an interface.
Q. Can an Interface implement another Interface?
A. Intefaces doesn't
provide implementation hence a interface cannot implement another interface.
Q. Can an Interface extend another Interface?
A. Yes an Interface can
inherit another Interface, for that matter an Interface can extend more than
one Interface.
Q. Can a Class extend more than one Class?
A. Not possible. A Class
can extend only one class but can implement any number of Interfaces.
Q. Why is an Interface be able to extend more than one Interface but a Class can't extend more than one Class?
A. Basically Java doesn't
allow multiple inheritance, so a Class is restricted to extend only one Class.
But an Interface is a pure abstraction model and doesn't have inheritance
hierarchy like classes(do remember that the base class of all classes is Object).
So an Interface is allowed to extend more than one Interface.
Q. Can an Interface be final?
A. Not possible. Doing so
so will result in compilation error.
Q. Can a class be defined inside an Interface?
A. Yes it's possible.
Q. Can an Interface be defined inside a class?
A. Yes it's possible.
Q. What is a Marker Interface?
A. An Interface which
doesn't have any declaration inside but still enforces a mechanism.
Q. Can we define private and protected modifiers for variables in interfaces?
A. No. Always all variables
declared inside a interface are of public access.
Q. What modifiers are allowed for methods in an Interface?
A. Only public and abstract
modifiers are allowed for methods in interfaces.
Q. When can an object reference be cast to an interface reference?
A. An object reference can
be cast to an interface reference when the object implements the referenced
interface.
Q. What are Inner Classes?
A. Inner classes are
classes which are defined inside another class.
Q. What are Nested Classes?
A. Static Inner classes are
called sometimes referred as nested classes because these classes can exist
without any relationship with the containing class.
Q. What is the super class of all Inner Classes?
A. Inner class is just a
concept and can be applied to any class, hence there is no common super class
for inner classes.
Q. What are the disadvantages of Inner classes?
A. 1. Inner classes are not
reusable hence defeats one of the fundamental feature of Java.2. Highly
confusing and difficult syntax which leads poor code maintainability.
Q.Name the different types of Inner Classes?
A. The following are the
different types of Inner classes:Regular Inner ClassMethod Local Inner
ClassStatic Inner ClassAnonymous Inner Class
Q. What are Regular Inner Classes?
A. A Regular inner class is
declared inside the curly braces of another class outside any method or other
code block. This is the simplest form of inner classes.
Q. Can a regular inner class access a private member of the enclosing class?
A. Yes. Since inner classes
are treated as a member of the outer class they can access private members of
the outer class.
Q. How will you instantiate a regular inner class from outside the enclosing class?
A. Outer out=new Outer();
Outer.Inner in=out.new Inner();
Q. What are Local Inner Classes or Method Local Inner Classes?
A. A method-local inner
class is defined within a method of the enclosing class.
Q. What are the constraints on Method Local Inner Classes?
A. The following are the
restrictions for Method Inner Classes:Method Local Inner classes cannot acccess
local variables but can access final variables.Only abstract and final
modifiers can be applied to Method Local Inner classesMethod Local Inner
classes can be instantiated only within the method in which it is contained
that too after the class definition.
Q. What are Anonymous Inner Classes? Name the various forms of Anonymous Inner Classes.
A. Anonymous Inner Classes
have no name, and their type must be either a subclass of the named type or an
implementer of the named interface. The following are the different forms of
inner classes:Anonymous subclass(i. E. extends a class)Anonymous implementer
(i. E. implements an interface)Argument-Defined Anonymous Inner Classes.
Q. How many classes can an Anonymous Inner classes inherit from?
A. One.
Q. How many Interfaces can an Anonymous Inner classes implement?
A. One. Normal classes and
other inner classes can implement more than one interface whereas anonymous
inner classes can either implement a single interface or extend a single class.
Q. What are Static Inner Classes?
A. Static Inner Classes are
inner classes which marked with a static modifier. These classes need not have
any relationship with the outer class. These can be instantiated even without
the existence of the outer class object.
Q. Can you instantiate the static Inner Class without the existence of the outer class object?
A. If Yes, Write a sample
statement. Yes. It can be instantiated as follows by referencing the Outer
class.Outer. Inner in = new Outer. Inner();
Q. What are the constraints on Static Inner Classes?
A. It cannot access
non-static members of the outer class. It cannot use this reference to the
outer class.
Q. How many class files are produced for source file having one Outer class and one Inner class?
A. Two class files will be
produced as follows:Outer. ClassOuter$Inner. Class
Java Exception Handling Interview Questions
Q. Which package
contains exception handling related classes?
A. java.lang
Q. What are
the two types of Exceptions?
A. Checked Exceptions and Unchecked
Exceptions.
Q. What is the base
class of all exceptions?
A. java.lang.Throwable
Q. What is the
difference between Exception and Error in java?
A. Exception and Error
are the subclasses of the Throwable class. Exception class is used for
exceptional conditions that user program should catch. Error defines exceptions
that are not excepted to be caught by the user program. Example is Stack
Overflow.
Q. What is the
difference between throw and throws?
A. throw is used to explicitly raise a
exception within the program, the statement would be throw new Exception();
throws clause is used to indicate the exceptions that are not handled by the
method. It must specify this behavior so the callers of the method can guard
against the exceptions. throws is specified in the method signature. If
multiple exceptions are not handled, then they are separated by a comma. the
statement would be as follows: public void doSomething() throws IOException,MyException{}
Q. Differentiate
between Checked Exceptions and Unchecked Exceptions?
A. Checked Exceptions are those exceptions
which should be explicitly handled by the calling method. Unhandled checked
exceptions results in compilation error.Unchecked Exceptions are those which
occur at runtime and need not be explicitly handled. RuntimeException and it's
subclasses, Error and it's subclasses fall under unchecked exceptions.
Q. What are User
defined Exceptions?
A. Apart from the exceptions already defined
in Java package libraries, user can define his own exception classes by
extending Exception class.
Q. What is the
importance of finally block in exception handling?
A. Finally block will be executed whether or
not an exception is thrown. If an exception is thrown, the finally block will
execute even if no catch statement match the exception. Any time a method is
about to return to the caller from inside try/catch block, via an uncaught
exception or an explicit return statement, the finally block will be executed.
Finally is used to free up resources like database connections, IO handles,
etc.
Q. Can a catch
block exist without a try block?
A. No. A catch block should always go with a
try block.
Q. Can a
finally block exist with a try block but without a catch?
A. Yes. The following are the combinations
try/catch or try/catch/finally or try/finally.
Q. What will happen
to the Exception object after exception handling?
A. Exception object will be garbage
collected.
Q. The subclass
exception should precede the base class exception when used within the catch
clause. True/False?
A. True.
Q. Exceptions can
be caught or rethrown to a calling method. True/False?
A. True.
Q. The statements
following the throw keyword in a program are not executed. True/False?
A. True.
Q. How does finally
block differ from finalize() method?
A. Finally block will be executed whether or not an
exception is thrown. So it is used to free resoources. finalize() is a
protected method in the Object class which is called by the JVM just before an
object is garbage collected.
Q. What are the
constraints imposed by overriding on exception handling?
A. An overriding method in a subclass may only
throw exceptions declared in the parent class or children of the exceptions
declared in the parent class.
Threading/Multithreading.
Q. What is
synchronization in respect to multi-threading in Java?
A. With respect to
multi-threading, synchronization is the capability to control the access of
multiple threads to shared resources. Without synchronization, it is possible
for one Java thread to modify a shared variable while another thread is in the
process of using or updating same shared variable. This usually leads to
erroneous behavior or program.
Q. Explain
different way of using thread?
A. A Java thread
could be implemented by using Runnable interface or by extending the Thread
class. The Runnable is more advantageous, when you are going for multiple
inheritance.
Q. What is the
difference between Thread.start() & Thread.run() method?
A.Thread.start() method
(native method) of Thread class actually does the job of running the
Thread.run() method in a thread. If we directly call Thread.run() method it
will executed in same thread, so does not solve the purpose of creating a new
thread.
Q. Why do we
need run() & start() method both. Can we achieve it with only run method?
A. We need run()
& start() method both because JVM needs to create a separate thread which
can not be differentiated from a normal method call. So this job is done by
start method native implementation which has to be explicitly called. Another
advantage of having these two methods is we can have any object run as a thread
if it implements Runnable interface. This is to avoid Java’s multiple
inheritance problems which will make it difficult to inherit another class with
Thread.
Q. What is
ThreadLocal class? How can it be used?
A. Below are some
key points about ThreadLocal variables
· A thread-local variable effectively provides a
separate copy of its value for each thread that uses it.
· ThreadLocal instances are typically private
static fields in classes that wish to associate state with a thread
· In case when multiple threads access a
ThreadLocal instance, separate copy of Threadlocal variable is maintained for
each thread.
· Common use is seen in DAO pattern where the
DAO class can be singleton but the Database connection can be maintained
separately for each thread. (Per Thread Singleton)
ThreadLocal variable are difficult to understand and I have
found below reference links very useful in getting better understanding on them
Q. When
InvalidMonitorStateException is thrown? Why?
A. This exception is thrown when you try to
call wait()/notify()/notifyAll() any of these methods for an Object from a
point in your program where u are NOT having a lock on that object.(i.e. u r
not executing any synchronized block/method of that object and still trying to
call wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw
IllegalMonitorStateException. since This exception is a subclass of
RuntimeException so we r not bound to catch it (although u may if u want to).
and being a RuntimeException this exception is not mentioned in the signature
of wait(), notify(), notifyAll() methods.
Q. What is the
difference between sleep(), suspend() and wait() ?
A. Thread.sleep() takes the current thread to a "Not
Runnable" state for specified amount of time. The thread holds the
monitors it has acquired. For example, if a thread is running a synchronized
block or method and sleep method is called then no other thread will be able to
enter this block or method. The sleeping thread can wake up when some other
thread calls t.interrupt on it. Note that sleep is a static method, that means
it always affects the current thread (the one executing sleep method). A common
mistake is trying to call t2.sleep() where t2 is a different thread; even then,
it is the current thread that will sleep, not the t2 thread. thread.suspend()
is deprecated method. Its possible to send other threads into suspended state
by making a suspend method call. In suspended state a thread keeps all its
monitors and can not be interrupted. This may cause deadlocks therefore it has
been deprecated. object.wait() call also takes the current thread into a
"Not Runnable" state, just like sleep(), but with a slight change.
Wait method is invoked on a lock object, not thread.
Here is the sequence of operations you can think
Here is the sequence of operations you can think
· A thread T1 is already running a synchronized
block with a lock on object - lets say "lockObject"
· Another thread T2 comes to execute the
synchronized block and find that its already acquired.
· Now T2 calls lockObject.wait() method for
waiting on lock to be release by T1 thread.
· T1 thread finishes all its synchronized block
work.
· T1 thread calls lockObject.notifyAll() to
notify all waiting threads that its done using the lock.
· Since T2 thread is first in the queue of
waiting it acquires the lock and starts processing.
A. Synchronized static methods have a lock on the class
"Class", so when a thread enters a synchronized static method, the
class itself gets locked by the thread monitor and no other thread can enter
any static synchronized methods on that class. This is unlike instance methods,
as multiple threads can access "same synchronized instance methods"
at same time for different instances.
Q. Can a thread
call a non-synchronized instance method of an Object when a synchronized method
is being executed ?
A. Yes,
a Non synchronized method can always be called without any problem. In fact
Java does not do any check for a non-synchronized method. The Lock object check
is performed only for synchronized methods/blocks. In case the method is not
declared synchronized Jave will call even if you are playing with shared data.
So you have to be careful while doing such thing. The decision of declaring a
method as synchronized has to be based on critical section access. If your
method does not access a critical section (shared resource or data structure)
it need not be declared synchronized. Below is the example which demonstrates
this, The Common class has two methods synchronizedMethod1() and method1()
MyThread class is calling both the methods in separate threads.
public class
Common {
public synchronized void synchronizedMethod1() {
System.out.println("synchronizedMethod1
called");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("synchronizedMethod1
done");
}
public
void method1() {
System.out.println("Method
1 called");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method
1 done");
}
}
public class MyThread extends Thread {
private int id
= 0;
private
Common common;
public
MyThread(String name, int no, Common object) {
super(name);
common =
object;
id = no;
}
public void run() {
System.out.println("Running
Thread" + this.getName());
try {
if (id == 0) {
common.synchronizedMethod1();
}
else {
common.method1();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public
static void main(String[] args) {
Common c = new
Common();
MyThread t1 =
new MyThread("MyThread-1", 0, c);
MyThread t2 =
new MyThread("MyThread-2", 1, c);
t1.start();
t2.start();
}
}
Here
is the output of the program
view
plainprint?
Running
ThreadMyThread-1
synchronizedMethod1
called
Running
ThreadMyThread-2
Method
1 called
synchronizedMethod1
done
Method
1 done
Q. Can two threads
call two different synchronized instance methods of an Object?
A. No. If a object has
synchronized instance methods then the Object itself is used a lock object for
controlling the synchronization. Therefore all other instance methods need to
wait until previous method call is completed. See the below sample code which
demonstrate it very clearly. The Class Common has 2 methods called
synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both
the methods.
public class Common {
public synchronized void synchronizedMethod1()
{
System.out.println("synchronizedMethod1
called");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("synchronizedMethod1
done");
}
public
synchronized void synchronizedMethod2() {
System.out.println("synchronizedMethod2
called");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("synchronizedMethod2
done");
}
}
public class MyThread extends Thread
{
private int
id = 0;
private
Common common;
public
MyThread(String name, int no, Common object) {
super(name);
common =
object;
id = no;
}
public
void run() {
System.out.println("Running
Thread" + this.getName());
try {
if (id == 0) {
common.synchronizedMethod1();
}
else {
common.synchronizedMethod2();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public
static void main(String[] args) {
Common c = new Common();
MyThread t1 = new MyThread("MyThread-1", 0,
c);
MyThread t2 = new MyThread("MyThread-2", 1,
c);
t1.start();
t2.start();
}
}
Q. What is a deadlock?
A. Deadlock
is a situation where two or more threads are blocked forever, waiting for each
other. This may occur when two threads, each having a lock on one resource,
attempt to acquire a lock on the other's resource. Each thread would wait
indefinitely for the other to release the lock, unless one of the user
processes is terminated. In terms of Java API, thread deadlock can occur in
following conditions:
·
When two threads call Thread.join() on each other.
·
When two threads use nested synchronized blocks to lock two
objects and the blocks lock the same objects in different order.
Q. What is Starvation? and What is a Livelock?
A. Starvation
and livelock are much less common a problem than deadlock, but are still
problems that every designer of concurrent software is likely to encounter.
LiveLock
Livelock occurs when all
threads are blocked, or are otherwise unable to proceed due to unavailability
of required resources, and the non-existence of any unblocked thread to make
those resources available. In terms of Java API, thread livelock can occur in
following conditions:
·
When all the threads in a program execute Object.wait(0) on an
object with zero parameter. The program is live-locked and cannot proceed until
one or more threads call Object.notify() or Object.notifyAll() on the relevant
objects. Because all the threads are blocked, neither call can be made.
·
When all the threads in a program are stuck in infinite loops.
Starvation
Starvation describes
a situation where a thread is unable to gain regular access to shared resources
and is unable to make progress. This happens when shared resources are made unavailable
for long periods by "greedy" threads. For example, suppose an object
provides a synchronized method that often takes a long time to return. If one
thread invokes this method frequently, other threads that also need frequent
synchronized access to the same object will often be blocked. Starvation occurs
when one thread cannot access the CPU because one or more other threads are
monopolizing the CPU. In Java, thread starvation can be caused by setting
thread priorities inappropriately. A lower-priority thread can be starved by
higher-priority threads if the higher-priority threads do not yield control of
the CPU from time to time.
Q. How to find a deadlock has occurred in Java?
How to detect a Deadlock in Java?
A. Earlier
versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5
there are some powerful methods added in the java.lang.management package to
diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface
is management interface for the thread system of the Java virtual machine. It
has two methods which can leveraged to detect deadlock in a Java application.
·
findMonitorDeadlockedThreads() -
This method can be used to detect cycles of threads that are in deadlock
waiting to acquire object monitors. It returns an array of thread IDs that are
deadlocked waiting on monitor.
·
findDeadlockedThreads() -
It returns an array of thread IDs that are deadlocked waiting on monitor or
ownable synchronizers.
Q. What is immutable
object? How does it help in writing concurrent application?
A. An
object is considered immutable if its state cannot change after it is
constructed. Maximum reliance on immutable objects is widely accepted as a
sound strategy for creating simple, reliable code. Immutable objects are
particularly useful in concurrent applications. Since they cannot change state,
they cannot be corrupted by thread interference or observed in an inconsistent
state. Examples of immutable objects from the JDK include String and Integer.
Immutable objects greatly simplify your multi threaded program, since they are
·
Simple to construct, test, and use.
·
Automatically thread-safe and have no synchronization issues.
To create a object
immutable You need to make the class final and all its member final so that
once objects gets crated no one can modify its state. You can achieve same
functionality by making member as non final but private and not modifying them
except in constructor.
Q. How will you take thread dump in Java? How
will you analyze Thread dump?
A. A
Thread Dump is a complete list of active threads. A java thread dump is a way
of finding out what each thread in the JVM is doing at a particular point of
time. This is especially useful when your java application seems to have some
performance issues. Thread dump will help you to find out which thread is
causing this. There are several ways to take thread dumps from a JVM. It is
highly recommended to take more than 1 thread dump and analyze the results
based on it. Follow below steps to take thread dump of a java process
·
Step 1
On UNIX, Linux and Mac OSX Environment run below command:
ps -el | grep java
On Windows:
Press Ctrl+Shift+Esc to open the task manager and find the PID of the java process.
On UNIX, Linux and Mac OSX Environment run below command:
ps -el | grep java
On Windows:
Press Ctrl+Shift+Esc to open the task manager and find the PID of the java process.
Step 2:
Use jstack command to print the Java stack traces for a given Java process PID
jstack [PID]
Use jstack command to print the Java stack traces for a given Java process PID
jstack [PID]
Q. What is a thread
leak? What does it mean in Java?
A. Thread leak is when a application does not
release references to a thread object properly. Due to this some Threads do not
get garbage collected and the number of unused threads grow with time. Thread
leak can often cause serious issues on a Java application since over a period
of time too many threads will be created but not released and may cause
applications to respond slow or hang.
Q. How can I trace whether the application has a
thread leak?
A. If an application has thread leak then with time it will have
too many unused threads. Try to find out what type of threads is leaking out.
This can be done using following ways
·
Give unique and descriptive names to the threads created in
application. - Add log entry in all thread at various entry and exit points in
threads.
·
Change debugging config levels (debug, info, error etc) and
analyze log messages.
·
When you find the class that is leaking out threads check how
new threads are instantiated and how they're closed.
·
Make sure the thread is Guaranteed to close properly by doing
following - Handling all Exceptions properly.
·
Make sure the thread is Guaranteed to close properly by doing
following
·
Handling all Exceptions properly.
·
releasing all resources (e.g. connections, files etc) before it
closes.
Q. What is thread pool? Why should we use thread
pools?
A. A thread pool is a collection of threads on which task can be
scheduled. Instead of creating a new thread for each task, you can have one of
the threads from the thread pool pulled out of the pool and assigned to the
task. When the thread is finished with the task, it adds itself back to the
pool and waits for another assignment. One common type of thread pool is the
fixed thread pool. This type of pool always has a specified number of threads
running; if a thread is somehow terminated while it is still in use, it is
automatically replaced with a new thread. Below are key reasons to use a Thread
Pool
·
Using thread pools minimizes the JVM overhead due to thread
creation. Thread objects use a significant amount of memory, and in a
large-scale application, allocating and de-allocating many thread objects
creates a significant memory management overhead.
·
You have control over the maximum number of tasks that are being
processed in parallel (= number of threads in the pool).
Most
of the executor implementations in java.util.concurrent use thread pools, which
consist of worker threads. This kind of thread exists separately from the
Runnable and Callable tasks it executes and is often used to execute multiple
tasks.
Q. Can we synchronize the run method? If yes
then what will be the behavior?
A. Yes, the run method of a runnable class can be synchronized. If
you make run method synchronized then the lock on runnable object will be
occupied before executing the run method. In case we start multiple threads
using the same runnable object in the constructor of the Thread then it would
work. But until the 1st thread ends the 2nd thread cannot start and until the
2nd thread ends the next cannot start as all the threads depend on lock on same
object.
Q. Can we synchronize the constructor of a Java
Class?
A. As per Java Language Specification, constructors cannot be
synchronized because other threads cannot see the object being created before
the thread creating it has finished it. There is no practical need of a Java
Objects constructor to be synchronized, since it would lock the object being
constructed, which is normally not available to other threads until all
constructors of the object finish.
Q. Define Serialization? What do you mean by Serialization in Java?
Q. Why
is Serialization required? What is the need to Serialize?
Q.
What is the Difference between Externalizable and Serializable Interfaces?
Q.
When will you use Serializable or Externalizable interface? and why?
Q.
What are the ways to speed up Object Serialization? How to improve
Serialization performance?
Q.
What is a Serial Version UID (serialVersionUID) and why should I use it? How to
generate one?
Q.
What would happen if the SerialVersionUID of an object is not defined?
Q.
Does setting the serialVersionUID class field improve Java serialization
performance?
Q.
What are the alternatives to Serialization? If Serialization is not used, is it
possible to persist or transfer an object using any other approach?
Q.
What are transient variables? What role do they play in Serialization process?
Q. Why
does serialization NOT save the value of static class attributes? Why static
variables are not serialized?
Q. How
to Serialize a collection in java? How to serialize a ArrayList, Hashmap or
Hashset object in Java?
Q. Is
it possible to customize the serialization process? How can we customize the
Serialization process?
Q. How
can a sub-class of Serializable super class avoid serialization? If
serializable interface is implemented by the super class of a class, how can
the serialization of the class be avoided?
Q.
What changes are compatible and incompatible to the mechanism of java
Serialization?
Java serialization is one of the most commonly misunderstood areas. Many developers still think its only used for saving objects on the file system.
Q. Why
Java uses Classpath parameter or environment variables?
Q. When does Java read values
of Classpath environment variable?
Q. How
to set Java Classpath on Windows, Unix, Linux and Mac?
A. Setting CLASSPATH on Windows
XP
Setting
CLASSPATH on Windows 7
Setting
CLASSPATH on Unix, Linux and Mac
Use export command to set the CLASSPATH environment variable in your system.
export CLASSPATH=/path/to/dir1:/path/to/dir2:path/to/abc.jar
Q. How do I check the
CLASSPATH variable is set in my machine?
A.
Checking CLASSPATH on Windows
Checking
CLASSPATH on Unix, Linux or Mac
If CLASSPATH variable is not set you will see CLASSPATH: Undefined variable error on Unix/Linux/Mac systems.
Setting
Multiple Jars in Classpath on Windows
Setting
Multiple Jars in Classpath on Unix, Linux or Mac
Older
version of Java
Q. What is the difference
between NoClassDefFoundError and ClassNotFoundException? When
NoClassDefFoundError and ClassNotFoundException are thrown?
ClassNotFoundException
NoClassDefFoundError
Key
Differences
Some
scenario when ClassNotFoundException may occur
Scenario 1 (Use of reflection) - You will see ClassNotFoundException when you are using reflection to load classes at runtime, and the class you are trying to load does not exist or not in classpath.
Scenario 2 (Multiple Classloaders being used) - You will see ClassNotFoundException when a class is being loaded from another class which was already loaded in a parent classloader and the class from the child classloader is not visible.
Q. How can we include Jar
within a Jar in java classpath?
Use
Jar class loader library
Explode
and combine into one jar
Q. How
to read a file from CLASSPATH in java?
Using
ClassLoader.getResourceAsStream
Using
Class.getResourceAsStream
Q. How to find which jar file
is being used by Java run-time?
Q. How
to find the load location of a Java class file at run-time?
Using
Classloader
Using
Protection Domain
Q. How Java handles Two classes with same name in classpath?
A. If I have two classes with same name say MyClass.java in two different jar in my classpath which one will be picked up by JVM , is there anyway I can suggest JVM to pick a specific one ?
Java interpreter loads classes based on the order they are specified in the CLASSPATH variable.
For example, lets say this is your classpath variable value
The Java interpreter will first look for MyClass class in the directory C:\Project\Dir1. Only if it doesn't find it in that directory it will look in the C:\Project\Dir2 directory.
Q. How
to Add A Jar File To Java Load Path At Run Time
You can run this code by below command. (Make sure to use forward slash "/" as directory separator.)
Q. Why
calling System.setProperty() does not affect the classpath at run-time?
Q. How to Add A Jar File To
Java System Classpath At Run-time?
Running this java class prints the number of bytes available. This indicates the file is available for further processing.
A. You can use Reflections library for doing this.
Reflections is a open source Java library. It scans Java classpath and indexes
it with metadata. This library allows you to query the classpath at runtime and
can be very handy for many run-time reflection code needs.
Q. How Generics works in Java ? What is type erasure ?
Q. What is Bounded and Unbounded wildcards in Generics ?
Q. What is difference between List<? extends T> and List <? super T> ?
Q. How to write a generic method which accepts generic argument and return Generic Type?
Q. Write a program to implement LRU cache using Generics ?
This is not an exhaustive list of questions and I am sure I have missed many important questions from Multi-threading area. Can you think of a question which should be included in this list? Please feel free to share any question/suggestion in the comments section.
Java Serialization Interview Questions
Q. Define Serialization? What do you mean by Serialization in Java?
A. Serialization is a mechanism by which
you can save or transfer the state of an object by converting it to a byte
stream. This can be done in java by implementing Serialiazable interface.
Serializable is defined as a marker interface which needs to be implemented for
transferring an object over a network or persistence of its state to a file.
Since its a marker interface, it does not contain any methods. Implementation
of this interface enables the conversion of object into byte stream and thus
can be transferred. The object conversion is done by the JVM using its default
serialization mechanism.
Q. Why
is Serialization required? What is the need to Serialize?
A. Serialization is required for a variety
of reasons. It is required to send across the state of an object over a network
by means of a socket. One can also store an object’s state in a file.
Additionally, manipulation of the state of an object as streams of bytes is
required. The core of Java Serialization is the Serializable interface. When
Serializable interface is implemented by your class it provides an indication
to the compiler that java Serialization mechanism needs to be used to serialize
the object.
Q.
What is the Difference between Externalizable and Serializable Interfaces?
A. This is one of top serialization
questions that is asked in many big companies to test your in-depth
understanding of serialization. Serializable is a marker interface therefore
you are not forced to implement any methods, however Externalizable contains
two methods readExternal() and writeExternal() which must be implemented.
Serializable interface provides a inbuilt serialization mechanism to you which
can be in-efficient at times. However Externilizable interface is designed to
give you greater control over the serialization mechanism. The two methods
provide you immense opportunity to enhance the performance of specific object
serialization based on application needs. Serializable interface provides a
default serialization mechanism, on the other hand, Externalizable interface
instead of relying on default Java Serialization provides flexibility to
control this mechanism. One can drastically improve the application performance
by implementing the Externalizable interface correctly. However there is also a
chance that you may not write the best implementation, so if you are not really
sure about the best way to serialize, I would suggest your stick to the default
implementation using Serializable interface.
Q.
When will you use Serializable or Externalizable interface? and why?
A. Most of the times when you want to do a
selective attribute serialization you can use Serializable interface with
transient modifier for variables not to be serialized. However, use of
Externalizable interface can be really effective in cases when you have to
serialize only some dynamically selected attributes of a large object. Lets
take an example, Some times when you have a big Java object with hundreds of
attributes and you want to serialize only a dozen dynamically selected
attributes to keep the state of the object you should use Externalizable
interface writeExternal method to selectively serialize the chosen attributes.
In case you have small objects and you know that most or all attributes are
required to be serialized then you should be fine with using Serializable
interface and use of transient variable as appropriate.
Q.
What are the ways to speed up Object Serialization? How to improve
Serialization performance?
A. The default Java Serialization
mechanism is really useful, however it can have a really bad performance based
on your application and business requirements. The serialization process
performance heavily depends on the number and size of attributes you are going
to serialize for an object. Below are some tips you can use for speeding up the
marshaling and un-marshaling of objects during Java serialization process.
· Mark the unwanted or non
Serializable attributes as transient. This is a straight forward benefit since
your attributes for serialization are clearly marked and can be easily achieved
using Serialzable interface itself.
· Save only the state of the
object, not the derived attributes. Sometimes we keep the derived attributes as
part of the object however serializing them can be costly. Therefore consider
calcualting them during de-serialization process.
· Serialize attributes only
with NON-default values. For examples, serializing a int variable with value
zero is just going to take extra space however, choosing not to serialize it
would save you a lot of performance. This approach can avoid some types of
attributes taking unwanted space. This will require use of Externalizable
interface since attribute serialization is determined at runtime based on the
value of each attribute.
· Use Externalizable
interface and implement the readExternal and writeExternal methods to
dynamically identify the attributes to be serialized. Sometimes there can be a
custom logic used for serialization of various attributes.
Q.
What is a Serial Version UID (serialVersionUID) and why should I use it? How to
generate one?
A. The serialVersionUID represents your
class version, and you should change it if the current version of your class is
not backwards compatible with its earlier versions. This is extract from Java
API Documentation
The serialization runtime
associates with each serializable class a version number, called a
serialVersionUID, which is used during deserialization to verify that the
sender and receiver of a serialized object have loaded classes for that object
that are compatible with respect to serialization.
Most of the times, we
probably do not use serialization directly. In such cases, I would suggest to
generate a default serializable uid by clicking the quick fix option in
eclipse.
Q.
What would happen if the SerialVersionUID of an object is not defined?
A. If you don't define serialVersionUID in
your serilizable class, Java compiler will make one by creating a hash code
using most of your class attributes and features. When an object gets
serialized, this hash code is stamped on the object which is known as the
SerialVersionUID of that object. This ID is required for the version control of
an object. SerialVersionUID can be specified in the class file also. In case,
this ID is not specified by you, then Java compiler will regenerate a
SerialVersionUID based on updated class and it will not be possible for the
already serialized class to recover when a class field is added or modified.
Its recommended that you always declare a serialVersionUID in your Serializable
classes.
Q.
Does setting the serialVersionUID class field improve Java serialization
performance?
A. Declaring an explicit serialVersionUID
field in your classes saves some CPU time only the first time the JVM process
serializes a given Class. However the gain is not significant, In case when you
have not declared the serialVersionUID its value is computed by JVM once and
subsequently kept in a soft cache for future use.
Q.
What are the alternatives to Serialization? If Serialization is not used, is it
possible to persist or transfer an object using any other approach?
A. In case, Serialization is not used,
Java objects can be serialized by many ways, some of the popular methods are
listed below:
· Saving object state to
database, this is most common technique used by most applications. You can use
ORM tools (e.g. hibernate) to save the objects in a database and read them from
the database.
· Xml based data transfer is
another popular mechanism, and a lot of XML based web services use this
mechanism to transfer data over network. Also a lot of tools save XML files to
persist data/configurations.
· JSON Data Transfer - is
recently popular data transfer format. A lot of web services are being
developed in JSON due to its small footprint and inherent integration with web
browser due to JavaScript format.
Q.
What are transient variables? What role do they play in Serialization process?
A. The transient keyword in Java is used
to indicate that a field should not be serialized. Once the process of
de-serialization is carried out, the transient variables do not undergo a
change and retain their default value. Marking unwanted fields as transient can
help you boost the serialization performance. Below is a simple example where
you can see the use of transient keyword.
class MyVideo implements Serializable {
private Video video;
private transient Image thumbnailVideo;
private
void generateThumbnail()
{
// Generate thumbnail.
}
private
void readObject(ObjectInputStream
inputStream) throws IOException,
ClassNotFoundException {
inputStream.defaultReadObject();
generateThumbnail();
}
}
Q. Why
does serialization NOT save the value of static class attributes? Why static
variables are not serialized?
A. The Java variables declared as static
are not considered part of the state of an object since they are shared by all
instances of that class. Saving static variables with each serialized object
would have following problems
· It will make redundant copy
of same variable in multiple objects which makes it in-efficient.
· The static variable can be
modified by any object and a serialized copy would be stale or not in sync with
current value.
Q. How
to Serialize a collection in java? How to serialize a ArrayList, Hashmap or
Hashset object in Java?
A. All standard implementations of
collections List, Set and Map interface already implement java.io.Serializable.
All the commonly used collection classes like java.util.ArrayList,
java.util.Vector, java.util.Hashmap, java.util.Hashtable, java.util.HashSet, java.util.TreeSet
do implement Serializable. This means you do not really need to write anything
specific to serialize collection objects. However you should keep following
things in mind before you serialize a collection object - Make sure all the
objects added in collection are Serializable. - Serializing the collection can
be costly therefore make sure you serialize only required data isntead of
serializing the whole collection. - In case you are using a custom
implementation of Collection interface then you may need to implement
serialization for it.
Q. Is
it possible to customize the serialization process? How can we customize the
Serialization process?
A. Yes, the serialization process can be
customized. When an object is serialized, objectOutputStream.writeObject (to
save this object) is invoked and when an object is read,
ObjectInputStream.readObject () is invoked. What most people do not know is
that Java Virtual Machine provides you with an option to define these methods
as per your needs. Once this is done, these two methods will be invoked by the
JVM instead of the application of the default serialization process. Classes
that require special handling during the serialization and deserialization
process must implement special methods with these exact signatures:
private
void writeObject(java.io.ObjectOutputStream
out) throws IOException
private
void readObject(java.io.ObjectInputStream
in) throws IOException,
ClassNotFoundException;
private
void readObjectNoData() throws ObjectStreamException;
Q. How
can a sub-class of Serializable super class avoid serialization? If
serializable interface is implemented by the super class of a class, how can
the serialization of the class be avoided?
A. In Java, if the super class of a class
is implementing Serializable interface, it means that it is already
serializable. Since, an interface cannot be unimplemented, it is not possible
to make a class non-serializable. However, the serialization of a new class can
be avoided. For this, writeObject () and readObject() methods should be
implemented in your class so that a Not Serializable Exception can be thrown by
these methods. And, this can be done by customizing the Java Serialization
process. Below the code that demonstrates it.
private
void writeObject(java.io.ObjectOutputStream
out) throws IOException
{
throw
new NotSerializableException(“Can
not serialize this class”);
}
private
void readObject(java.io.ObjectInputStream
in) throws IOException,
ClassNotFoundException {
throw
new NotSerializableException(“Can
not serialize this class”);
}
private
void readObjectNoData() throws ObjectStreamException; {
throw
new NotSerializableException(“Can
not serialize this class”);
}
Q.
What changes are compatible and incompatible to the mechanism of java
Serialization?
A. This is one of a difficult and tricky
questions and answering this correctly would mean you are an expert in Java
Serialization concept. In an already serialized object, the most challenging
task is to change the structure of a class when a new field is added or
removed. As per the specifications of Java Serialization, addition of any
method or field is considered to be a compatible change whereas changing of
class hierarchy or non-implementation of Serializable interface is considered
to be a non-compatible change. You can go through the Java serialization
specification for the extensive list of compatible and non-compatible changes.
If a serialized object need to be compatible with an older version, it is
necessary that the newer version follows some rules for compatible and
incompatible changes. A compatible change to the implementing class is one that
can be applied to a new version of the class, which still keeps the object
stream compatible with older version of same class. Some Simple
Examples of compatible changes are:
· Addition of a new field or
class will not affect serialization, since any new data in the stream is simply
ignored by older versions. the newly added field will be set to its default
values when the object of an older version of the class is un marshaled.
· The access modifiers change
(like private, public, protected or default) is compatible since they are not
reflected in the serialized object stream.
· Changing a transient field
to a non-transient field is compatible change since it is similar to adding a
field.
· Changing a static field to
a non-static field is compatible change since it is also similar to adding a
field.
Some Simple Examples of
incompatible changes are:
· Changing implementation
from Serializable to Externalizable interface can not be done since this will
result in the creation of an incompatible object stream.
· Deleting a existing
Serializable fields will cause a problem.
· Changing a non-transient
field to a transient field is incompatible change since it is similar to
deleting a field.
· Changing a non-static field
to a static field is incompatible change since it is also similar to deleting a
field.
· Changing the type of a
attribute within a class would be incompatible, since this would cause a
failure when attempting to read and convert the original field into the new
field.
· Changing the package of class
is incompatible. Since the fully-qualified class name is written as part of the
object byte stream.
Java serialization is one of the most commonly misunderstood areas. Many developers still think its only used for saving objects on the file system.
Classpath Interview Questions
Q. Why
Java uses Classpath parameter or environment variables?
A. In a Java class import statements are
used to access other classes. You also do a wild card import like org.fromdev.*
on your java file.
In such cases, It will become very impractical/slow for the Java Virtual Machine to search for classes in every file/folder on a machine, therefore you can provide the Java Virtual Machine with a list of places to look. This is done by putting folder and jar files on your classpath.
Environment variables in general are a set of dynamic name value pair that can be used by processes to decide the behavior based on a system. These are supported by all modern operating systems.
The CLASSPATH variable is a Java way to tell the possible locations of user classes or jar files for a Java application. Since each user/computer may choose to have classes in different location its best to have custom locations configured in Classpath variable.
In case you have not set the classpath environment variable, the default value is used as the "." (current directory). That means, the current directory is searched.
In such cases, It will become very impractical/slow for the Java Virtual Machine to search for classes in every file/folder on a machine, therefore you can provide the Java Virtual Machine with a list of places to look. This is done by putting folder and jar files on your classpath.
Environment variables in general are a set of dynamic name value pair that can be used by processes to decide the behavior based on a system. These are supported by all modern operating systems.
The CLASSPATH variable is a Java way to tell the possible locations of user classes or jar files for a Java application. Since each user/computer may choose to have classes in different location its best to have custom locations configured in Classpath variable.
In case you have not set the classpath environment variable, the default value is used as the "." (current directory). That means, the current directory is searched.
Q. When does Java read values
of Classpath environment variable?
A. Java uses the CLASSPATH environment
variable to read the classes and libraries from file system. This variable is
used by all JDK Tools and Extension including Java Compiler (javac) and
JRE(java) use this variable to locate the dependent user classes and jar files
to perform specific tasks.
Java Compiler uses it to locate the dependent user classes and jar files to compile Java source files.
Java Run-time Environment (JRE) uses the classpath variable to identify the location of files to be loaded for the run-time dependencies (e.g. classes and jar files) of java program.
Java Compiler uses it to locate the dependent user classes and jar files to compile Java source files.
Java Run-time Environment (JRE) uses the classpath variable to identify the location of files to be loaded for the run-time dependencies (e.g. classes and jar files) of java program.
Q. How
to set Java Classpath on Windows, Unix, Linux and Mac?
A. Setting CLASSPATH on Windows
XP
Follow
below steps on Windows XP to set Java CLASSPATH
· Right-click My Computer,
and then click Properties.
· Click the Advanced tab.
· Click Environment variables.
· Click one the following
options, for either a user or a system variable
· Click New to add a new
variable name and value.
· Enter Variable name as
CLASSPATH
· enter all directories and
jar files separated by semicolon. (e.g. c:\dir1;c:\dir2;c:\dir3\abc.jar)
Setting
CLASSPATH on Windows 7
· Click Start
· Then right-click on
Computer,
· select Properties
· click Select Advanced
System Settings tab.
· click the Environment
Variables button.
Setting
CLASSPATH on Unix, Linux and Mac
Use export command to set the CLASSPATH environment variable in your system.
export CLASSPATH=/path/to/dir1:/path/to/dir2:path/to/abc.jar
Q. How do I check the
CLASSPATH variable is set in my machine?
A.
Checking CLASSPATH on Windows
To
check CLASSPATH variable is set on Microsoft Windows, run following
command on command prompt
C:>
echo %CLASSPATH%
If CLASSPATH variable is not set you will see %CLASSPATH% on windows system.
If CLASSPATH variable is not set you will see %CLASSPATH% on windows system.
Checking
CLASSPATH on Unix, Linux or Mac
To
check CLASSPATH variable is set on Unix/Linux/Mac run following command on
shell
$
echo $CLASSPATH
If CLASSPATH variable is not set you will see CLASSPATH: Undefined variable error on Unix/Linux/Mac systems.
Q. How to set Multiple Jar Files in Java
Classpath ?
A. Java versions Older then Java 6 does
not support wildcard characters. Setting Multiple jars using wildcard in Java
classpath are allowed in Java 6 and later versions.
For example, to specify all jar files in a directory "lib" the classpath entry should look like this
lib/*
The wildcard entry (*) in classpath value will match only jar files NOT class files. To match both class files and JAR files in a same directory lib, you need to specify both values as shown below
For example, to specify all jar files in a directory "lib" the classpath entry should look like this
lib/*
The wildcard entry (*) in classpath value will match only jar files NOT class files. To match both class files and JAR files in a same directory lib, you need to specify both values as shown below
Setting
Multiple Jars in Classpath on Windows
Windows
environment variable values are separated by semicolon, therefore you classpath
entry would look like this
lib/*;lib
lib/*;lib
Setting
Multiple Jars in Classpath on Unix, Linux or Mac
Unix
environment variable values are separated by colon, therefore you classpath
entry would look like this
lib/*:lib
lib/*:lib
Older
version of Java
In
older version of Java(older than Java 6), each jar file needs to be specified
in the classpath. It can be a tedious and erroneous task if you are using many
third party libraries.
Q. What is the difference
between NoClassDefFoundError and ClassNotFoundException? When
NoClassDefFoundError and ClassNotFoundException are thrown?
A. NoClassDefFoundError and
ClassNotFoundException are very closely related and often confused with each
other by many developers. Below is the description of each from the Java API
Specifications
ClassNotFoundException
Thrown
when an application tries to load in a class through its string name using:
· The forName method in class
Class.
· The findSystemClass method
in class ClassLoader.
· The loadClass method in
class ClassLoader.
but
the definition of the class with the specified name could not be found due to
following reasons
· The specified name class
does not exist.
· The specified name class is
not in the classpath
· The specified name class is
not visible to the classloader.
NoClassDefFoundError
Thrown
if the Java Virtual Machine or a ClassLoader instance tries to load in the
definition of a class (as part of a normal method call or as part of creating a
new instance using the new expression) and no definition of the class could be
found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
Key
Differences
· The NoClassDefFoundError is
thrown when the source was successfully compiled, but during runtime, the
required class files were not found. This may be a case when some dependency
jar files were not included or not in classpath.
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader or not visible to the Classloader.
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader or not visible to the Classloader.
· Another important
distinction between these two is, NoClassDefFoundError is a sub class of
java.lang.Error and the ClassNotFoundException is a subclass of
java.lang.Exception.
· NoClassDefFoundError is a
critical error for JVM since its having problems finding a class it expected to
find.
On the other hand, the ClassNotFoundException is an Exception. Use of reflection api can be error-prone and there is no compile-time check to validate reflection call is loading right classes, so there can be situations when some classes may not be found.
On the other hand, the ClassNotFoundException is an Exception. Use of reflection api can be error-prone and there is no compile-time check to validate reflection call is loading right classes, so there can be situations when some classes may not be found.
Some
scenario when ClassNotFoundException may occur
Scenario 1 (Use of reflection) - You will see ClassNotFoundException when you are using reflection to load classes at runtime, and the class you are trying to load does not exist or not in classpath.
Scenario 2 (Multiple Classloaders being used) - You will see ClassNotFoundException when a class is being loaded from another class which was already loaded in a parent classloader and the class from the child classloader is not visible.
Q. How can we include Jar
within a Jar in java classpath?
A. There is no easy way to do this in
current java versions. There are 2 alternatives to deal with this problem using
third party libraries
Use
Jar class loader library
The JarClassLoader
library provides you the feature of loading resources from a top
JAR and from JARs inside the top JAR.
Explode
and combine into one jar
Instead
of trying to bundle jar file inside jar you can explode all required jars and
re-bundle them as one jar using following two libraries
· The first is One-Jar,
which uses a special classloader to allow the nesting of jars.
· The second is UberJar,
(or Maven Shade Plugin), which explodes the included
libraries and puts all the classes in the top-level jar.
Q. How
to read a file from CLASSPATH in java?
A. This can be done in two simple ways
Using
ClassLoader.getResourceAsStream
This
method can be used to load any file from CLASSPATH
InputStream in =this.getClass().getClassLoader().getResourceAsStream("MyFile.txt");
Using
Class.getResourceAsStream
This
method can be used to load files using relative path to the package of the
class
InputStream in =this.getClass().getResourceAsStream("SomeTextFile.txt");
This
method can also be used to load any files from CLASSPATH by prefixing a
"/"
Q. How to find which jar file
is being used by Java run-time?
A. On Windows
You need use below windows program Process Explorer that
lets you see which files are open for a particular process or program
On Unix, Linux or Mac
It can be done using lsof command. lsof is one of my favorite and useful
java debugging commands on Unix. Below is the syntax for using this
command –
lsof -p [pid]
Q. How
to find the load location of a Java class file at run-time?
A. There are two ways to find it
Using
Classloader
Below
code snippet can be used to find the location of java class com.fromdev.MyClass
this.getClass().getClassLoader().getResource("com/fromdev/MyClass.class")
this.getClass().getClassLoader().getResource("com/fromdev/MyClass.class")
Using
Protection Domain
We can use this to find the exact location a jar file containing
the class JVM is using
clazz.getProtectionDomain().getCodeSource().getLocation()
clazz.getProtectionDomain().getCodeSource().getLocation()
Q. How Java handles Two classes with same name in classpath?
A. If I have two classes with same name say MyClass.java in two different jar in my classpath which one will be picked up by JVM , is there anyway I can suggest JVM to pick a specific one ?
Java interpreter loads classes based on the order they are specified in the CLASSPATH variable.
For example, lets say this is your classpath variable value
C:\Project\Dir1;C:\Project\Dir2
The Java interpreter will first look for MyClass class in the directory C:\Project\Dir1. Only if it doesn't find it in that directory it will look in the C:\Project\Dir2 directory.
Q. How
to Add A Jar File To Java Load Path At Run Time
A. This can done by use of URLClassloader.
A sample implementation of this code is shown below.
import java.net.URL;
import java.net.URLClassLoader;
public class SimpleJarLoader {
public static void main(String args[]) {
if (args.length < 2) {
System.out.println("Usage: [Class name] [Jar Path]");
return;
}
try {
System.out.println("Trying to load the class...");
Class.forName(args[0]);
} catch (Exception ex) {
System.out.println("Not able to load class..." + args[0]);
}
try {
String url = "jar:file:/" + args[1] + "!/";
URL urls[] = { new URL(url) };
URLClassLoader cl = new URLClassLoader(urls,
SimpleJarLoader.class.getClassLoader());
System.out.println("Looking into jar... " + url);
cl.loadClass(args[0]);
System.out.println("Woohoo....I found it");
} catch (Exception ex) {
System.out.println("Oops...Still cant find the jar");
ex.printStackTrace();
}
}
}
You can run this code by below command. (Make sure to use forward slash "/" as directory separator.)
java
SimpleJarLoader org.springframework.core.SpringVersion C:/spring.jar
The
output is like this
Trying to load the class...
Not able to load class...org.springframework.core.SpringVersion
Looking into jar... jar:file:/C:/spring.jar!/
Woohoo....I found it
Q. Why
calling System.setProperty() does not affect the classpath at run-time?
A. You can easily set any system
properties in java using System.setPropoerty method, However it may not have
any effect in case of CLASSPATH property. This is mainly because the Java
system class loader is initialized very early in the JVM startup sequence. The
class loader copies the classpath into its own data structures, and the
classpath property is not read again. Therefore changing it after its already
copied does not affect anything. There are mainly two reasons for this - First
most important reason is security. You do not want a malicious code change the
classpath at runtime and load some unwanted classes. Second reason is
performance, since reading the classpath every-time its needed may not be
efficient.
Q. How to Add A Jar File To
Java System Classpath At Run-time?
A. This can be done by using a simple
reflection API hack as demonstrated in below sample code. This example assumes
you have a file "c:/Sample.txt" that is not already in class
path and at run-time c:/ is added the System classpath and then Sample.txt is
made available.
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class HackJavaClasspath {
public static void addURL(URL url) throws Exception {
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class clazz = URLClassLoader.class;
Method method = clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(cl, new Object[] { url });
}
public static void main(String[] args) throws Exception {
//Add c: to the classpath
addURL(new File("c:/").toURI().toURL());
//Now load the file from new location
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("Sample.txt");
System.out.println(in.available());
}
}
Running this java class prints the number of bytes available. This indicates the file is available for further processing.
Q. How to get a list of resources from a directory in Java classpath?
Java Generics Interview Questions
Generic interview questions in Java interviews are getting more and
more common with Java 5 around there for considerable time and many application
either moving to Java 5 and almost all new java development happening on
Tiger(code name of Java 5). Importance of Generics and Java 5 features
like Enum, Collection utilities are getting more and more popular on Java
interviews. Generic interview question can get real tricky if you are not
familiar with bounded and unbounded generic wildcards, How
generics works internally, type erasure and familiarity with writing parametrized
generics classes and methods in Java. Best way to prepare for Generics
interview is to try simple program best on various features of generics. Anyway
In this Java interview article we will see some popular interview questions and
there answers around generics in Java.
Q. What
is generics in Java ? What are advantages of using Generics?
A. This is one of the first interview questions
asked on generics in any Java interview, mostly at beginners and intermediate
level. Those who are coming from prior to Java 5 background knows that how
inconvenient it was to store object in Collection and then cast it back to
correct Type before using it. Generics prevents from those. it provides compile time type-safety and ensures that you only insert
correct Type in collection and avoids ClassCastException in runtime.
Q. How Generics works in Java ? What is type erasure ?
A. This is one of better interview question in
Generics. Generics is implemented using Type erasure, compiler
erases all type related information during compile time and no type related
information is available during runtime. for example List<String> is
represented by only List at runtime. This was done to ensure binary
compatibility with the libraries which were developed prior to Java 5. you
don’t have access to Type argument at runtime and Generic type is
translated to Raw type by compiler during runtime. you can get
lot of follow up question based on this Generic interview question based upon
your response e.g. Why Generics is implemented using Type erasure or
presenting some invalid generic code which results in compiler error. read my
post How Generics work in Java for more details
Q. What is Bounded and Unbounded wildcards in Generics ?
A. This is another very popular Java Interview
Questions on Generics. Bounded Wildcards are those which impose bound on
Type. there are two kinds of Bounded wildcards <? extends T> which impose
an upper bound by ensuring that type must be sub class of T and <? super
T> where its imposing lower bound by ensuring Type must be super class of T.
This Generic Type must be instantiated with Type within bound otherwise it will
result in compilation error. On the other hand <?> represent and
unbounded type because <?> can be replace with any Type. See more on my
post
Q. What is difference between List<? extends T> and List <? super T> ?
A. This is related to previous generics
interview questions, some time instead of asking what is bounded and unbounded
wildcards interviewer present this question to gauge your understanding of
generics. Both of List declaration is example of bounded wildcards, List<?
extends T> will accept any List with Type extending T while List<? super
T> will accept any List with type super class of T. for Example List<?
extends Number> can accept List<Integer> or List<Float> . see
more on above link.
Q. How to write a generic method which accepts generic argument and return Generic Type?
A. Writing generic method is not difficult,
instead of using raw type you need to use Generic Type like T, E or K,V which
are well known placeholders for Type, Element and Key, Value. Look on Java
Collection framework for examples of generics methods. In simplest form a
generic method would look like:
public V put(K key, V value) {
return cache.put(key, value);
}
Q. How to write parametrized class in Java using
Generics ?
A. This is an extension of previous Java
generics interview question. Instead of asking to write Generic method
Interviewer may ask to write a type safe class using generics.
again key is instead of using raw types you need to used generic types and
always use standard place holder used in JDK.
Q. Write a program to implement LRU cache using Generics ?
A. This is an exercise for anyone who like
Coding in Java. One hint is that LinkedHashMap can be used implement fixed size
LRU cache where one needs to remove eldest entry when Cache is full.
LinkedHashMap provides a method called removeEldestEntry() which is called by
put() and putAll() and can be used to instruct to remove eldest entry. you are
free to come up with your own implementation as long as you have a written a
working version along with Unit test.
Java String
interview Question
Q. What is String
in Java ? Is String is data type?
A. String in Java is
not a primitive data type like int, long or double. String is a class or in more simple term a
user defined type. This is confusing for some one who comes from C background.
String is defined in java.lang package and wrappers its content in a character
array. String provides equals() method to compare two String and provides
various other method to operate on String like toUpperCase() to convert String
into upper case, replace() to replace String contents, substring() to get
substring, split() to split long String into multiple String.
Q. Why String is
final in Java
A. String is final
by design in Java, some of the points which makes sense why String is final is
Security, optimization and to maintain pool of String in Java. for details on
each of this point see Why String is final in Java.
Q. What is
Difference between String and StringBuffer in Java
A. This is probably
the most common question on String I have seen in Java interviews. Though
String and Stringbuffer are two different class they are used in context of
concatenating two Strings, Since String is immutable in Java every operation
which changes String produces new String, which can be avoided by using
Stringbuffer. See String vs StringBuffer
for more details.
Q. What is
difference in String on C and Java
A. If you have
mentioned C in your resume, then you are likely to face this String interview
question. Well C String and Java String are completely different to each other,
C String is a null terminated character array while String in Java is an
Object. Also String is more feature rich in Java than C.
Q. Why char array
is better than String for storing password?
A. This String
interview question is debatable and you might not agree with interviewer but
this is also a chance to show that how deep and differently you can think of.
One of the reason which people give Why you should store password in char array
over String is related to immutability, since its not possible to remove erase
contents of String but you can erase contents of char array. See Why char array
preferred over String for password for complete discussion.
Q. How do you
compare two String in Java ?
A. This is another
common String interview question which appears on fresher level interviews.
There are multiple ways to compare two String like equals() method,
equalsIgnoreCase() etc, You can also see 4 ways to compare String in Java for
more examples. Main thing which interviewer checks is that whether candidate
mentioned equality operator or not "==", comparing String with
equality operator is common mistake which works in some case and doesn't work
in other. next String interview question is follow-up up of this.
Q. Can we compare
String using == operator? What is risk?
A. As discussed in
previous String question, You can compare String using equality operator but
that is not suggested or advised because equality operator is used to compare
primitives and equals() method should be used to compare objects. As we have
seen in pitfall of autoboxing in Java that how equality operator can cause
subtle issue while comparing primitive to Object, any way String is free from
that issue because it doesn't have corresponding primitive type and not
participate in autoboxing. Almost all the time comparing String means comparing
contents of String i.e. characters and equals() method is used to perform
character based comparison. equals() return true if two String points to same
object or two String has same contents while == operator returns true if two
String object points to same object but return false if two different String
object contains same contents. That explains why sometime it works and sometime
it doesn't. In short always use equals method in Java to check equality of two
String object.
Q. How substring
method work in Java
A. This is one of
the tricky Java question relate to String and until you are familiar with
internals of String class, its difficult to answer. Substring shares same
character array as original String which can create memory leak if original
String is quite big and not required to retain in memory but unintentionally
retained by substring which is very small in size and prevents large array from
begin claimed during Garbage collection in Java. See How Substring works in
Java for more details.
Q. What is String
pool in Java
A. Another tough
Java question asked in String interview.
String pool is a special storage area in Java heap, mostly located on PerGen
space, to store String literals like "abc". When Java program creates
a new String using String literal, JVM checks for that String in pool and if
String literal is already present in pool than same object is returned instead
of creating a whole new object. String pool check is only performed when you
create String as literal, if you create String using new() operator, a new
String object will be created even if String with same content is available in
pool.
Q. What does
intern() method do in Java
A. As discussed in
previous String interview question, String object crated by new() operator is
by default not added in String pool as opposed to String literal. intern()
method allows to put an String object into pool.
Q. Does String is
thread-safe in Java
A. If you are
familiar with the concept of immutability and thread-safety you can easily
answer this String interview question in Java. Since String is immutable, it is
thread-safe and it can be shared between multiple thread without external
synchronization.
That's
all on Java String interview question. In Summary there are lot of specifics
about String which needs to be know for any one who has started Java
programming and these String question will not just help to perform better on
Java Interviews but also opens new door of learning about String. I didn't know
many String related concepts until I come across these question which motivated
to research and learn more about String in Java.
How
to Convert Date to String in Java with Example?
Sometimes
we need to convert java.util.Date to string in java may for displaying purpose I need it that
while working on displaytag then I thought about this article to list down various way of converting this
in various ways, after some reading I found that SimpleDateFormat makes this
quite easy. To get the feel of Date API in java and to familiarize ourselves
with these classes we will see different examples of converting date to String
in our application. Both DateFormat and SimpleDateFormat class belongs
java.text package and they are very powerful and you can use them for
conversion. it also good for parsing string into date and can be used to show
in various locale also.
1)
First step is to create a date format using SimpleDateFormat class
2)
Call format() method of SimpleDateFormat by passing Date object this will
return String representation of date into specified date format.
Now
let’s see few examples of converting date to String in java:
//Creating
Date in java with today's date.
Date
dateNow = new Date();
//change
date into string yyyyMMdd format example "20110914"
SimpleDateFormat
dateformatyyyyMMdd = new SimpleDateFormat("yyyyMMdd");
String
date_to_string = dateformatyyyyMMdd.format(dateNow);
System.out.println("date
into yyyyMMdd format: " + date_to_string);
//converting date into ddMMyyyy format example
"14092011"
SimpleDateFormat
dateformatddMMyyyy = new SimpleDateFormat("ddMMyyyy");
date_to_string
= dateformatddMMyyyy.format(dateNow);
System.out.println("Today's
date into ddMMyyyy format: " + date_to_string);
//change
date to string on dd-MM-yyyy format e.g. "14-09-2011"
SimpleDateFormat
dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
date_to_string
= dateformatJava.format(dateNow);
System.out.println("Today's
date into dd-MM-yyyy format: " + date_to_string);
//converting
date to string dd/MM/yyyy format for example "14/09/2011"
SimpleDateFormat
formatDateJava = new SimpleDateFormat("dd/MM/yyyy");
date_to_string
= formatDateJava.format(dateNow);
System.out.println("Today's
date into dd/MM/yyyy format: " + date_to_string);
//date
to dd-MMM-yy format e.g. "14-Sep-11"
SimpleDateFormat
ddMMMyyFormat = new SimpleDateFormat("dd-MMM-yy");
date_to_string
= ddMMMyyFormat.format(dateNow);
System.out.println("Today's
date into dd-MMM-yy format: " + date_to_string);
//convert
date to dd-MMMM-yy format e.g. "14-September-11"
SimpleDateFormat
ddMMMMyyFormat = new SimpleDateFormat("dd-MMMM-yy");
date_to_string
= ddMMMMyyFormat.format(dateNow);
System.out.println("date
into dd-MMMM-yy format: " + date_to_string);
For
complete details on available symbols for date conversion you can check java
doc of DateFormat and SimpleDateFormat class.
Here are some important points about SimpleDateFormat which is worth
remembering
1) Common point of confusion between “m” and
“M” , small case “m” represent minutes while “M” represent Month Also “d”
represent date in month while “D” represent Day of week. This is most common
cause of error while converting String to date and back date to string. In shot
ddMMyy is not equal toDDmmyy.
2) It’s also worth noting that
SimpleDateFormat are not thread-safe.
They are not synchronized so its better you create separate DateFormat for each
thread to avoid any race condition while parsing date in java.
It’s
very important for any java developer be it senior or junior to get familiarize
himself with Date, Time and Calendar API. SimpleDateFormat is an excellent
utility for converting String to Date and then Date to String but you just need
to be little careful with format and thread-safety .
Q. Difference
between StringBuilder and StringBuffer in Java
A. StringBuffer is
very good with mutable String but it has one disadvantage all its public
methods are synchronized which makes it thread-safe but same time slow. In JDK
5 they provided similar class called StringBuilder in Java which is a copy of
StringBuffer but without synchronization. Try to use StringBuilder whenever
possible it performs better in most of cases than StringBuffer class. You can
also use "+" for concatenating two string because "+"
operation is internal implemented using either StringBuffer or StringBuilder in
Java. If you see StringBuilder vs StringBuffer you will find that they are
exactly similar and all API methods applicable to StringBuffer are also
applicable to StringBuilder in Java. On the other hand String vs StringBuffer
is completely different and there API is also completely different, same is
true for StringBuilder vs String.
Summary
In
summary here are list of difference between StringBuffer, String and
StringBuilder in Java :
1)
String is immutable while StringBuffer and StringBuilder is mutable object.
2)
StringBuffer is synchroonized while StringBuilder is not which makes StringBuilder
faster than StringBuffer.
3)
Concatenation operator "+" is internal implemented using either
StringBuffer or StringBuilder.
4)
Use String if you require immutability use Stringbuffer in java if you need
mutable + thread safty and use StringBuilder in Java if you require mutable +
without thread-safety.
That's
all on famous String vs StringBuffer or StringBuffer vs StringBuilder
discussion. All these differences helps to avoid common coding mistake of using
String in place of StringBuffer in many places. from Java 5 onwards either use
+ operator of StringBuilder for concatenating String in Java.
Q. How to convert
Enum to String in Java
A. Enum classes by
default provides valueOf (String value) method which takes a String parameter
and converts it into enum. String name should match with text used to declare
Enum in Java file. Here is a complete code example of String to Enum in Java
Code
Example String to Enum:
public
class EnumTest {
private enum LOAN {
HOME_LOAN {
@Override
public String toString() {
return "Always look for
cheaper Home loan";
}
},
AUTO_LOAN {
@Override
public String toString() {
return "Cheaper Auto Loan
is better";
}
},
PEROSNAL_LOAN{
@Override
public String toString() {
return "Personal loan is
not cheaper any more";
}
}
}
public static void main(String[] args) {
//Exmaple of String to Enum in Java
LOAN homeLoan =
LOAN.valueOf("HOME_LOAN");
System.out.println(homeLoan);
LOAN autoLoan =
LOAN.valueOf("AUTO_LOAN");
System.out.println(autoLoan);
LOAN personalLoan =
LOAN.valueOf("PEROSNAL_LOAN");
System.out.println(personalLoan);
}
Output:
Always
look for cheaper Home loan
Cheaper
Auto Loan is better
Personal
loan is not cheaper any more
Q.
How to create comma separated String from Collection in Java
A.
I am big fan on Spring framework and we use Spring in most of our projects and
we have already discussed few examples of Spring framework in Java before e.g.
Using Spring to calculate execution time and Spring security to control
Concurrent Sessions in Java. In this
Java tutorial I will share you an example of converting List to delimited String,
Set to delimit String or any other Collection class into delimited String by
using Spring framework's StringUtils class. Spring provides two convenient
method collectionToCommaDelimitedString and collectionToDelimitedString which
can be used here. This example is general and you can convert any Collection
into comma separated or any delimiter separated String by using this technique.
Order of individual String in delimited String is the order on which they are
stored in Collection e.g. List or Set This particular Java program shows How to
convert a List into comma, colon and pipe separated String.
import
java.util.Arrays;
import
java.util.Collection;
import
java.util.HashSet;
import
java.util.List;
import
org.springframework.util.StringUtils;
/**
* Simple Java program to demonstrate How to
convert List or Set into String in Java.
* Spring framework's StringUtils class provide
methods like
* collectionToCommaDelimitedString and
collectionToDelimitedString
* which can convert any Java collection class
like ArrayList or HashSet.
* into comma delimited String.
*
* @author Prabhat
*/
public
class CollectionToString{
public static void main(String args[]) {
//List with multiple Strings for
testing
List<String> frameworks =
Arrays.asList("Spring MVC", "Struts 2.0",
"Velocity", "Wicket");
//let's convert this list into comma
separated String
String commaDelimitedString =
StringUtils.collectionToCommaDelimitedString(frameworks);
System.out.println(commaDelimitedString);
//list to colon delimited String
String colonDelimitedString =
StringUtils.collectionToDelimitedString(frameworks, ":");
System.out.println(colonDelimitedString);
//List to pipe delimited String
String pipeDelimitedString =
StringUtils.collectionToDelimitedString(frameworks, "|");
System.out.println(pipeDelimitedString);
//Now let's convert Set into String in
Java
HashSet<String> frameworkSet =
new HashSet(frameworks);
//HashSet to comma separated String
commaDelimitedString =
StringUtils.collectionToCommaDelimitedString(frameworkSet);
System.out.println(commaDelimitedString);
//Set to delimiter separated String
using Spring
colonDelimitedString =
StringUtils.collectionToDelimitedString(frameworkSet, ":");
System.out.println(colonDelimitedString);
//Set to pipe delimited String using
Spring framework StringUtils
pipeDelimitedString =
StringUtils.collectionToDelimitedString(frameworkSet, "|");
System.out.println(pipeDelimitedString);
}
}
Output
Spring
MVC,Struts 2.0,Velocity,Wicket
Spring
MVC:Struts 2.0:Velocity:Wicket
Spring
MVC|Struts 2.0|Velocity|Wicket
Struts
2.0,Spring MVC,Velocity,Wicket
Struts
2.0:Spring MVC:Velocity:Wicket
Struts
2.0|Spring MVC|Velocity|Wicket
Q. How to convert
String to Double in Java
A. As with above
examples, there are multiple ways to convert a Double object into String. In
this example of converting double to String we will see atleast four ways of
doing same. this is rather much easier than opposite.
1)
First way to convert Double to string is using concatantion operator
"+" which produce a new string. This is by far simplest way of
converting double object to string.
Double
toBeString = 400.40;
String
fromDouble = "" + toBeString;
2)
Second way of double to String conversion is by using String.valueOf(double d)
method , which takes a double value as argument and returns it in a form of
String literal. here is an example of converting double to String using
valueOf() method.
String
strDouble = String.valueOf(toBeString);
3)
Third way to convert double into String is by using toString() method of Double
Class, which is essentially the same way used in first way because
concatanation oeprator internally calls toString() method of object to get its
string value.
String
stringDouble = toBeString.toString();
4)
Fourth way is rather more flexible way of getting String from Double. it uses
String.format() method and returns a formatted string so you can control the
precision level and get an String upto two decimal point or three decimal point
based on your requirement.
convertedString
= String.format("%.3f", toBeString);
This
convertedString contains double value upto 3 decimal point. "f" is
used to format floating point numbers. As you may have noticed we are passing
Double object to methods which are expecting double premitive value and that is
only possible due to autoboxing. if you are running below Java 5 use intValue()
doubleValue() methods to get value in primitive format.
These
are some basic ways to change any String into Double wrapper Class and vice
versa. Please let us know if you are familiar with any other utility or method
or doing same thing with less hassle may be overriding equals using
EqualsBuilder and HashCodeBuilder.
Q. How to reverse
String in Java with recursion or String Reverse Example using Iteration and
Recursion in Java?
A. Here is a code
example String reverse using iterative
and recursive function written in Java. Recursive solution is just for demonstrative
and education purpose, don’t use recursive solution in production code as it
may result in StackOverFlowError if String to be reversed is very long String
or if you have any bug in your reverse function, anyway its good test to make
yourself comfortable with recursive functions in java.
import
java.io.FileNotFoundException;
import
java.io.IOException;
/**
*
*@author
Prabhat
/
public
class StringReverseExample {
public static void main(String args[])
throws FileNotFoundException, IOException {
//original string
String str = "Sony is going to
introduce Internet TV soon";
System.out.println("Original
String: " + str);
//reversed string using Stringbuffer
String reverseStr = new
StringBuffer(str).reverse().toString();
System.out.println("Reverse String
in Java using StringBuffer: " + reverseStr);
//iterative method to reverse String in
Java
reverseStr = reverse(str);
System.out.println("Reverse String
in Java using Iteration: " + reverseStr);
//recursive method to reverse String in
Java
reverseStr = reverseRecursively(str);
System.out.println("Reverse String
in Java using Recursion: " + reverseStr);
}
public static String reverse(String str) {
StringBuilder strBuilder = new
StringBuilder();
char[] strChars = str.toCharArray();
for (int i = strChars.length - 1; i
>= 0; i--) {
strBuilder.append(strChars[i]);
}
return strBuilder.toString();
}
public static String
reverseRecursively(String str) {
//base case to handle one char string
and empty string
if (str.length() < 2) {
return str;
}
return
reverseRecursively(str.substring(1)) + str.charAt(0);
}
}
Q. How to format
String in Java?
A. String.format()
and System.out.printf() both works similarly and if you see the signature of
both method they also accept variable arguments . Both take minimum two
parameters, first of them is formatting instruction and other was actual String
or anything which needs to be formatted. Java formatting instructions are both
powerful and flexible and allows you to generate formatted String on many
different format. Its worth to understand format of "formatting
instruction" to take full benefit of String.format() method because this
is the only tricky part of String formatting specially if you have not used
printf() in past. I have seen developer struggle to understand the formatting
behavior because of lack of knowledge of different formatting options available
in Java.This is how we specify formatting instruction in Java :
String.format
"%[argument number] [flags] [width] [.precision] type"
Now
let's see what is meaning of each part of formatting instruction. "%"
is a special character in formatted String and it denotes start of formatting
instruction. String.format() can support multiple formatting instruction with
multiple occurrence of "%" character in formatting instruction.
"argument
number" is used to specify correct argument in case multiple arguments are
available for formatting. "flags" is another special formatting
instruction which is used to print String in some specific format for example
you can use flag as "," to print comma on output. "width" formatting
option denotes minimum number or character will be used in output but in case
if number is larger than width then full number will be displayed but if its
smaller in length then it will be be padded with zero. "precision" is
using for print floating point formatted String, by using precision you can
specify till how many decimal a floating point number will be displayed in
formatted String. "type" is the only mandatory formatting option and
must always comes last in format String also input String which needs to be
formatted must be with same type specified in "type" parameter. for
example you can not input a floating point number if you have specified
"type" as decimal integer "%d", that will result in error.
Now let's see an example of String format() method to understand these
formatting option better:
format
( "%,6.2f", 124.000)
In
above example of String.format() method
flag is comma "," , width is 6 and precision is upto 2 decimal point
and type is float.
String
format Example in Java
In
this section we will see different examples to format String in Java. We will
see how we can format numbers and dates. Introduce decimal points and aligning
number left or right etc. One of the common application of format() is to print
leading zero in a number as shown in this Java program example:
/**
* Java program to demonstrate How to format
String in Java by using
* format() method of String class and printf()
method of OutputStream in Java.
* String.format() is very powerful and not
only can format String but numbers
* and Date in Java
*
* @author Prabhat
*/
public
class StringFormatExample{
public static void main(String
args[]){
//simple example of formatted string in
Java
//%d is used to format decimals like
integers
//position of argument is the order in
which they appear in source String
e.g here 40021 will replace first %d
and 3000 will replace second %d.
String formattedString =
String.format("Order with OrdId : %d and Amount: %d is missing",
40021, 3000);
System.out.println(formattedString);
System.out.printf("Order with
OrdId : %d and Amount: %d is missing
\n", 40021, 3000);
//%s is used to denote String arguments
in formatted String
String str = String.format("Hello
%s", "Raj");
System.out.println(str);
//if argument is not convertible into
specified data type than
//Formatter will
throw following java.util.IllegalFormatConversionException
//e.g. specifying %d and passing 3.0
//str = String.format("Number
%d", 3.0);
// Exception in thread "main"
java.util.IllegalFormatConversionException: d != java.lang.Double
// at
java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:3999)
// at
java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2709)
// at
java.util.Formatter$FormatSpecifier.print(Formatter.java:2661)
// at
java.util.Formatter.format(Formatter.java:2433)
// at java.util.Formatter.format(Formatter.java:2367)
// at
java.lang.String.format(String.java:2769)
//common meta characters used in
String.format() and
//System.out.printf() method: %s - String , %d
- decimal integer
// %f - float %tD - date as MM/dd/yy while %td is day %tm
is month
// and %ty is 2 digit year while %tY is four
digit year
//Formatting date in String format
method - date in MM/dd/yy
str = String.format("Today is
%tD", new Date());
System.out.println(str);
Date today = new Date();
System.out.printf("Date in
dd/mm/yy format %td/%tm/%ty %n", today,today,today );
// date as July 25, 2012, difference
between %td and %te is that
// %td use leading zero while %te doesn't
System.out.printf("Today is %tB
%te, %tY %n", today,today,today,today);
//adding leading zero in numbers using
String format,
//%d is for decimal, 8 specify formatted
number should be 8 digit and 0 specify use
//leading zero, default is space, so if
you don't specify leading
// character space will be used.
System.out.printf("Amount : %08d
%n" , 221);
//printing positive and negative number
using String format
//+ sign for positive, - for negative and %n
is for new line
System.out.printf("positive number
: +%d %n", 1534632142);
System.out.printf("negative number
: -%d %n", 989899);
//printing floating point number with
System.format()
System.out.printf("%f %n",
Math.E);
//3 digit after decimal point
System.out.printf("%.3f %n",
Math.E);
//8 charcter in width and 3 digit after
decimal point
System.out.printf("%8.3f %n",
Math.E);
//adding comma into long numbers
System.out.printf("Total %,d
messages processed today", 10000000);
}
}
Output:
Order
with OrdId : 40021 and Amount: 3000 is
missing
Order
with OrdId : 40021 and Amount: 3000 is
missing
Hello
Raj
Today
is 07/25/12
Date
in dd/mm/yy format 25/07/12
Today
is July 25, 2012
Amount
: 00000221
positive
number : +1534632142
negative
number : -989899n
2.718282
2.718
2.718
Total
10,000,000 messages processed today
Top 10 Tricky Java
interview questions
Tricky
Java interview questions are those question which has some surprise element on
it and if you answer tricky Java question with common sense, you are likely to
fail because they are tricky, they require something special to know. Most of
the tricky Java questions comes from method overloading and overriding, Checked and Unchecked Exception and subtle
Java programming details like Integer overflow. Most important thing to answer
tricky Java question is attitude and analytical thinking , which helps even if
you don't know the answer. Anyway in this Java article we will see some Java
questions which is tricky and requires more than average knowledge of Java
programming language to answer. As per my experience there are always one or
two tricky or tough Java interview question on any core Java or J2EE
interviews, so its good to prepare tricky questions from Java in advance.
Here
is my list of some tricky Java interview questions, Though I have prepared and
shared lot of difficult core java interview question and answers, But I have
chosen them as Top 10 tricky questions because you can’t guess answers of this
tricky java questions easily, you need some subtle details of Java programming
language to answer these questions.
Q. What will
happen if you call return statement or System.exit on try or catch block ? will
finally block execute?
A. This is a very
popular tricky Java question and its tricky because many programmer think that
finally block always executed. This question challenge that concept by putting
return statement in try or catch block or calling System.exit from try or catch
block. Answer of this tricky question in Java is that finally block will
execute even if you put return statement in try block or catch block but
finally block won't run if you call System.exit form try or catch.
Q. Can you
override private or static method in Java ?
A. Another popular
Java tricky question, As I said method overriding is a good topic to ask trick
questions in Java. Anyway, you can’t
override private or static method in Java, if you create similar method with
same return type and same method arguments that's called method hiding. See Can
you override private method in Java or more details.
Q. Does Java
support multiple inheritance ?
A. This is the
trickiest question in Java, if C++ can support direct multiple inheritance than
why not Java is the argument Interviewer often give. See Why multiple
inheritance is not supported in Java to answer this tricky Java question.
Q. What will happen
if we put a key object in a HashMap which is already there ?
A. This tricky Java
questions is part of How HashMap works in Java, which is also a popular topic
to create confusing and tricky question in Java. well if you put the same key
again than it will replace the old mapping because HashMap doesn't allow
duplicate keys. See How HashMap works in Java for more tricky Java questions
from HashMap.
Q. If a method
throws NullPointerException in super class, can we override it with a method
which throws RuntimeException?
A. One more tricky
Java questions from overloading and overriding concept. Answer is you can very
well throw super class of RuntimeException in overridden method but you can not
do same if its checked Exception. See Rules of method overriding in Javafor
more details.
Q. What is the
issue with following implementation of compareTo() method in Java
public int
compareTo(Object o){
Employee emp = (Employee) emp;
return this.id - o.id;
}
Where id is an
integer number ?
A: Well there is
nothing wrong in this Java question until you guarantee that id is always
positive. This Java question becomes tricky when you can not guaranteed id is
positive or negative. If id is negative than subtraction may overflow and
produce incorrect result. See How to override compareTo method in Java for
complete answer of this Java tricky question for experienced programmer.
Q. How do you
ensure that N thread can access N resources without deadlock?
A. If you are not
well versed in writing multi-threading code then this is real tricky question
for you. This Java question can be tricky even for experienced and senior
programmer, who are not really exposed to deadlock and race conditions. Key
point here is order, if you acquire resources in a particular order and release
resources in reverse order you can prevent deadlock. See how to avoid deadlock
in Java for a sample code example.
Q. What is
difference between CyclicBarrier and CountDownLatch in Java?
A. Relatively newer
Java tricky question, only been introduced form Java 5. Main difference between
both of them is that you can reuseCyclicBarrier even if Barrier is broken but
you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch
in Java for more differences.
Q. What is
difference between StringBuffer and StringBuilder in Java ?
A. Classic Java
questions which some people thing tricky and some consider very easy.
StringBuilder in Java is introduced in Java 5 and only difference between both
of them is that Stringbuffer methods are synchronized while StringBuilder is
non synchronized. See StringBuilder vs StringBuffer for more differences.
Q. Can you access
non static variable in static context?
A. Another tricky
Java question from Java fundamentals. No you can not access static variable in
non static context in Java. Read why you can not access non-static variable
from static method to learn more about this tricky Java questions.
This
was my list of 10 most common tricky question in Java . It's not a bad idea to
prepare tricky Java question before appearing for any core Java or J2EE
interview. One or two open ended or tricky question is quite common in Java
interviews.
13 Singleton
Pattern Interview question in Java
Q. What is
Singleton class? Have you used Singleton before?
A. Singleton is a
class which has only one instance in whole application and provides a
getInstance() method to access the singleton instance. There are many classes
in JDK which is implemented using Singleton pattern like java.lang.Runtime
which provides getRuntime() method to get access of it and used to get free
memory and total memory in Java.
Q. Which classes
are candidates of Singleton? Which kind of class do you make Singleton in Java?
A. Here they will
check whether candidate has enough experience on usage of singleton or not.
Does he is familiar of advantage/disadvantage or alternatives available for
singleton in Java or not.
Answer:
Any class which you want to be available to whole application and whole only
one instance is viable is candidate of becoming Singleton. One example of this
is Runtime class , since on whole java application only one runtime environment
can be possible making Runtime Singleton is right decision. Another example is
a utility classes like Popup in GUI application, if you want to show popup with
message you can have one PopUp class on whole GUI application and anytime just
get its instance, and call show() with message.
Q. Can you write
code for getInstance() method of a Singleton class in Java?
A. Most of the java
programmer fail here if they have mugged up the singleton code because you can
ask lots of follow-up question based upon the code they have written. I have
seen many programmer write Singleton getInstance() method with double checked
locking but they are not really familiar with the caveat associated with double
checking of singleton prior to Java 5.
Answer:
Until asked don’t write code using double checked locking as it is more complex
and chances of errors are more but if you have deep knowledge of double checked
locking, volatile variable and lazy loading than this is your chance to shine.
I have shared code examples of writing singleton classes using enum, using
static factory and with double checked locking in my recent post Why Enum Singletons
are better in Java, please see there.
Q. Is it better to
make whole getInstance() method synchronized or just critical section is
enough? Which one you will prefer?
A. This is really
nice question and I mostly asked to just quickly check whether candidate is
aware of performance trade off of unnecessary locking or not. Since locking
only make sense when we need to create instance and rest of the time its just
read only access so locking of critical section is always better option. read
more about synchronization on How Synchronization works in Java
Answer:
This is again related to double checked locking pattern, well synchronization
is costly and when you apply this on whole method than call to getInstance()
will be synchronized and contented. Since synchronization is only needed during
initialization on singleton instance, to prevent creating another instance of
Singleton, It’s better to only
synchronize critical section and not whole method. Singleton pattern is also
closely related to factory design pattern where getInstance() serves as static
factory method.
Q. What is lazy
and early loading of Singleton and how will you implement it?
A. This is another
great Singleton interview question in terms of understanding of concept of
loading and cost associated with class loading in Java. Many of which I have
interviewed not really familiar with this but its good to know concept.
As
there are many ways to implement Singleton like using double checked locking or
Singleton class with static final instance initialized during class loading.
Former is called lazy loading because Singleton instance is created only when
client calls getInstance() method while later is called early loading because
Singleton instance is created when class is loaded into memory.
Q. Example of
Singleton in standard Java Development Kit?
A. This is open
question to all, please share which classes are Singleton in JDK. Answer to
this question is java.lang.Runtime
There
are many classes in Java Development Kit which is written using singleton
pattern, here are few of them:
• Java.lang.Runtime with
getRuntime() method
• Java.awt.Toolkit with
getDefaultToolkit()
• Java.awt.Desktop with getDesktop()
Q. What is double
checked locking in Singleton?
A. One of the most
hyped question on Singleton pattern and really demands complete understanding
to get it right because of Java Memory model caveat prior to Java 5. If a guy
comes up with a solution of using volatile keyword with Singleton instance and
explains it then it really shows it has in depth knowledge of Java memory model
and he is constantly updating his Java knowledge.
Double
checked locking is a technique to prevent creating another instance of
Singleton when call to getInstance() method is made in multi-threading environment.
In Double checked locking pattern as shown in below example, singleton instance
is checked two times before initialization.
public
Singleton getInstance(){
if(_INSTANCE == null){
synchronized(Singleton.class){
//double checked locking - because
second check of Singleton instance with lock
if(_INSTANCE == null){
_INSTANCE = new
Singleton();
}
}
}
return _INSTANCE;
}
Double
checked locking should only be used when you have requirement for lazy
initialization otherwise use Enum to implement singleton or simple static final
variable.
Q. How do you
prevent for creating another instance of Singleton using clone() method?
A. This type of
questions generally comes some time by asking how to break singleton or when
Singleton is not Singleton in Java.
Preferred
way is not to implement Clonnable interface as why should one wants to create
clone() of Singleto and if you do just throw Exception from clone() method
as “Can not create clone of Singleton
class”.
Q. How do you
prevent for creating another instance of Singleton using reflection?
A. Open to all. In
my opinion throwing exception from constructor is an option.
This
is similar to previous interview question. Since constructor of Singleton class
is supposed to be private it prevents creating instance of Singleton from
outside but Reflection can access private fields and methods, which opens a
threat of another instance. This can be avoided by throwing Exception from
constructor as “Singleton already initialized”
Q. How do you
prevent for creating another instance of Singleton during serialization?
A. Another great
question which requires knowledge of Serialization in Java and how to use it
for persisting Singleton classes. This is open to you all but in my opinion use
of readResolve() method can sort this out for you.
You
can prevent this by using readResolve() method, since during serialization
readObject() is used to create instance and it return new instance every time
but by using readResolve you can replace it with original Singleton instance. I have shared code on how to do it in my post
Enum as Singleton in Java. This is also one of the reason I have said that use
Enum to create Singleton because serialization of enum is taken care by JVM and
it provides guaranted of that.
Q. When is
Singleton not a Singleton in Java?
A. There is a very
good article present in Sun's Java site which discusses various scenarios when
a Singleton is not really remains Singleton and multiple instance of Singleton
is possible. Here is the link of that article http://java.sun.com/developer/technicalArticles/Programming/singletons/
Q. Why you should
avoid the singleton anti-pattern at all and replace it with DI?
A. Singleton
Dependency Injection: every class that needs access to a singleton gets the
object through its constructors or with a DI-container.
Singleton Anti-Pattern: with more and more
classes calling getInstance the code gets more and more tightly coupled,
monolithic, not testable and hard to change and hard to reuse because of not
configurable, hidden dependencies. Also, there would be no need for this clumsy
double checked locking if you call getInstance less often (i.e. once).
Q. How many ways
you can write Singleton Class in Java?
A. I know at-least
four ways to implement Singleton pattern in Java
1)
Singleton by synchronizing getInstance() method
2)
Singleton with public static final field initialized during class loading.
3)
Singleton generated by static nested class, also referred as Singleton holder
pattern.
4)
From Java 5 on-wards using Enums
Q. How to write
thread-safe Singleton in Java?
A. Thread-Safe
Singleton usually refers to write thread safe code which creates one and only
one instance of Singleton if called by multiple thread at same time. There are
many ways to achieve this like by using double checked locking technique as
shown above and by using Enum or Singleton initialized by classloader.
At
last few more questions for your practice, contributed by Mansi:
Singleton
vs Static Class?
When
to choose Singleton over Static Class?
Can
you replace Singleton with Static Class in Java?
Difference
between Singleton and Static Class in java?
Advantage
of Singleton over Static Class?
Java Interview Question
for Senior Developers
Here
are my list of questions which is worth preparing if you are going for core
java interview for senior position, these questions are mostly based upon Garbage collection , Concurrency,
Collections, design, Coding and testing.
Q. Can we compare
String using equality operator (==) operator?
A. We can compare
String using equality operator. But we mostly use equals() method because of
following reasons:
• The equality operator is used to
compare primitives values only where as equals method() should be used to
compare objects.
• The equality operator can invoke
subtle issue while comparing primitive to Object. Where as equals() method is
used to perform character based comparison.
• equals() return true if two
String represent to the same object or when both strings contents are exactly
same but equality() operator returns true if two String object represents to
same object but return false if two different String object contains same
contents
Q. What is
intern() method in Java?
A. The intern()
method is of String class. The intern() method is supposed to return the String
from the String pool if the String is found in String pool, otherwise a new
string object will be added in String pool and the reference of this String is
returned.
Example:
String
str1 = "hello";
String
str2 = "hello";
String
str3 = "hello".intern();
if
( s1 == s2 ){
System.out.println("str1 and str2
are same");
}
if
( str1 == str3 ){
System.out.println("str1 and str3
are same" );
}
We
are assuming that str1 and str3 are same will be printed as str3 is interned,
and str1 and str2 are same will not be printed. Actual output is: both lines
are printed. Which make clear that by default String constants are interned?
Q. When is class
garbage collected?
A. Java uses the
garbage collector to free memory which is occupied by those objects which is no
more reference by any of the program. An object becomes eligible for Garbage
Collection when no live thread can access it. There are many ways to make a
class reachable and thus prevent it from being eligible for Garbage Collection:
• Objects of that class are still
reachable.
• Class object representing the
class is still reachable.
• ClassLoader that loaded the class
is still reachable.
• Other classes loaded by the
ClassLoader are still reachable.
When
all of the above are false, then the ClassLoader together with all classes it
loaded are eligible for Garbage Collection.
Q. What is the
difference between a Choice and a List?
A. The between Choice
and list are following:
• Choice class presents a pop-up
menu of choices whereas List is a collection of different visible item.
• Choice is displayed in a compact
form, to see the list of available choices we need to scroll down whereas list
displays the entire available items.
• Choice allows selecting only one
items but List supports the selection of one or more List items.
• Lists typically allow duplicate
elements selection. List allow pairs of elements e1 and e2 such that
e1.equals(e2), and they typically allow multiple null elements if they allow
null elements at all.
Q. What is JCA in
java?
A. Java Cryptography
Architecture term from Sun for implementing security functions for the Java
platform. It provides a platform and gives architecture and APIs for encryption
and decryption. JCA is used by the developer to combine the application with
the security measure. A programmer uses the JCA to meet the security measure.
It helps in performing the third partly security rules. It uses the hash table,
encryption message digest, etc to implement the security.
Q. What is JPA in
java?
A. The Java
Persistence API is enabling us to create the persistence layer for desktop and
web applications. Java Persistence deals in following:
• Java Persistence API
• Query language
• Java Persistence Criteria API
• Object mapping metadata
Q. What is
difference between eager and lazy loading?
A. The difference
between eager and loading are:
• Eager loading means to load the
data before the requirement whereas lazy loading mean that load the data only
when required.
• Eager loading fetch the data in
one query whereas lazy loading fetch the data when needed by triggering the sub
query.
Q. What is JMS in
Java?
A. Java Message
Service (JMS) is used for creating the communication interface between two
clients by using the message passing services. This helps the application to
interact with other components irrespective of components location whether they
rely on same system or connect to the main system through LAN or internet.
Q. What is shallow
cloning and deep cloning?
A. Shallow copy: in
this object is copied without its contained objects. Shallow clone only copies
the top level structure of the object not the lower levels. It is an exact bit
copy of all the attributes.
Deep
copy: In this object is copied along with the objects it refers to. Deep clone
copies all the levels of the object from top to the bottom recursively.
Q. What is the
difference between applications and applets?
A. The differences
between an Applet and an application are as follows:
• Applets can be embedded in HTML
pages and downloaded over the Internet whereas Applications have no special
support in HTML for embedding or downloading.
• Application starts execution with
its main method whereas applet starts execution with its init method.
• Application must be run on local
machine whereas applet needs no explicit installation on local machine.
• Application must be run
explicitly within a java-compatible virtual machine whereas applet loads and
runs itself automatically in a java-enabled browser.
• Application can run with or
without graphical user interface whereas applet must run within a graphical
user interface.
Q. What are Class
loaders?
A. Class loader
enables the program to load the class at run time. This is located in the
java.lang package.
Using
Class Loader we can also load the customize classes which is required for the
application execution. The class loaders in Java are organized in a tree. When
JVM is started three class loaders are used:
• Bootstrap class loader: the core
java libraries. It is written in native code.
• Extensions class loader: loads
the code in the extension directories. It is implemented by ExtClassLoader
class.
• System class loader: code found
on the java.class.path which map to the system class path variables. It is
implemented by AppClassLoader class. All user classes by default are load by
the system class loader.
Q. What is the
Comparable interface?
A. The Comparable
interface is used to sort collections and arrays of objects using the
collections.sort() and java.utils. The objects of the class implementing the
Comparable interface can be ordered. All classes implementing the Comparable
interface must implement the compareTo() method that has the return type as an
integer. The signature of the compareTo() method is as follows:
int
i = object1.compareTo(object2)
• If object1 < object2: The
value of i returned will be negative.
• If object1 > object2: The
value of i returned will be positive.
• If object1 = object2: The value of
i returned will be zero.
Q. What is Single
Threaded Model in Servlets?
A. Single Thread
Model is a marker interface which contains no methods and variable in it.
• When using Single thread model
with Servlet, it make sure that that only one thread can be executed at a time.
It avoids running of two or more thead simultaneously.
• If we wants to make single
threaded we can implement this interface in the following fashion.
public
class SingleThreadedTest implements SingleThreadModel {
//some code
}
Q. What are the
different Authentication Options available in Servets?
A. Authentication
options available in Servlets: There are four different options for
authentication in servlet:
1.
Basic Authentication: Username and password provided by the client to
authenticate the user.
2.
Form-based authentication- In this the login form is made by the programmer by
using HTML.
3.
Digest Authentication- It is similar to basic authentication but in this the
passwords are encrypted using Hash formula. This makes digest more secured.
4.
Client certificate Authentication- It requires that each client accessing the
resource has a certificate that it send to authenticate itself. This requires
SSL protocol.
Q. What is the
disadvantage of garbage collector?
A. Garbage Collector
runs in its own thread which affects the performance of the system. It
increases the workload of JVM because it constantly monitor the object which is
not referenced.. The two main disadvantages of garbage collector are:
• TIME: to collect all those no
referenced object JVM spends a considerable amount of time by scanning the
entire heap.
• Mark and sweep: some time it is
difficult to implement mark and sweep in the application.
Q. Does java
support global variable?
A. No, java does not
support global variable because of the following reasons:
• Globally accessible: global
variables are globally accessible.
• Referential transparency:global
variable breaks the referential transparency and also a global variable
generate problem in the namespace.
• Object oriented: As JAVA is
object oriented language so where each variable is declared inside the class.
To use this variable, object should be initialized.
Q. Explain
different layout manager in Java.
A. There are
following types of layouts are used to organize or to arrange objects:
• Border Layout: Have five areas
for holding components: north, east, west, south and center.
• Flow Layout: Default layout
manager, lays out the components from left to right
• Card Layout: Different components
at different times are laid out, Controlled by a combo box.
• Grid Layout: Group of components
are laid out I equal size and displays them in certain rows and columns.
• Grid Bag Layout: Flexible layout
for placing components within a grid of cells.
Q. What is chained
exceptions in java?
A. When in a program
the first exception causes another exception that is termed as Chained
Exception. Chained exceptions helps in finding the root cause of the exception
that occurs during application’s execution. The constructors that support chained
exceptions in Throwable classes are:
• Throwable initCause(Throwable)
• Throwable(Throwable)
• Throwable(String, Throwable)
• Throwable getCause()
Q. When is the
main thread stop in java?
A. When we execute
the java program, it call the main() method because main() method is the first
thread in the program. This main() method or thread invokes the other thread
which is required for the complete execution of the program. The main thread
should be the last thread in the program to end. so to make main() method to be
last we make sure when we called to another function by giving execution
control to that must return the control back to the main() method.
Q. What are the
ways to create child threads?
A. There are two
ways to create java threads:
• Implementing the Runnable
interface: this overcomes the limitation of inheriting from only one parent
class Thread. Using Runnable interface, lays a path to ground work of a class
that utilizes threads
• Extending Thread class: It
inherits the methods and data members, fields from the class tread. In this
process only one class can be inherited from the parent class Thread.
The
advantage is a class can extend Thread class and also implements the Runnable
interface, if required. The Runnable interface is set for implementing a thread
and the class that implements the interface performs all the work.
Q. Why byte code
is important to Java?
A. The compiled Java
source code is known as byte code. We need bytecode due to following reasons:
• Is independent of the input
language.
• Plays an important role in the
execution speed of the application.
• Can run on any platform
irrespective of system architecture.
• Can be used for internet
applications where security is important
• Enable us to load classes which
are required for the execution of the application.
• allows the web applications to
run on various platforms, on various browsers on different infrastructures.
Q. What is an
Iterator and explain traversing through a collector using Iterator?
A. We can access
each element in the Collection by using Iterators irrespective of how they are
organized in the collector. Iterator can be implemented a different way for
every Collection. To use an iterator to traverse through the contents of a
collection we do:
• Obtain an iterator by calling the
collections iterator() method to the start of the collection.
• Set up a loop that makes a call
to hasNext(). Have the loop iterate as long as hasNext()returns true.
• Within the loop, obtain each element
by calling next().
• remove() method is used to remove
the current element in the iteration.
Q. What is Race
condition?
A. Race Condition:
it is the situation when two threads raise the request for the same resource
allocation, but the manner in which resources are allocated are significant, is
called race conditions.
• Race condition is created in
program in order to run the parallel execution of program by using multiple
threads in a same period.
• A race condition occurs when two
threads operate on same object without proper synchronization and there
operation interleaves on each other.
• The risk of Race condition is
higher in Java.
Q. What is
difference between Java and JavaScript?
A.The difference
between java and java scripts are:
• Java is an Object Oriented
Programming Language and capable of running on multiple operating systems with
the help of interpreter whereas Java Script is the object oriented scripting
language and it is embedded in HTML and runs directly on the browser.
• JVM is used to executed java
program on different program whereas Java Script code is not compiled they are
directly run on the browser.
• Java language is used to develop
the software whereas java script is used providing interactivity to the simple
HTML pages.
Q. What is the difference
between factory and abstract factory pattern?
A. The differences
between factory and abstract factory are following:
• Factory pattern is a single
method but abstract factory is an object.
• The Abstract Factory pattern is
one level of abstraction higher than the factory pattern.
• Factory pattern generally returns
the common parent class or method whereas the abstract factory pattern returns
the one of the several factories.
Q. What is
Singleton?
A. Singleton in Java
is a class with just one instance in whole Java application.
• This make sure that only one
instance of a class is created.
• getInstance() method is used to
get single instance of the class.
• It creates a global point to
access all object
Q. What is the
difference between JAR and WAR files?
A. The differences
between JAR and WAR files are:
• JAR files (Java Archive) allows
combining many files into one whereas WAR files (Web Application Archive)
stores XML, java classes, and JavaServer pages for Web Application purposes.
• JAR is used to hold Java classes
in a library whereas in WAR files are stored in lib directory of the
application.
• In this EJB module which contains
enterprise java beans class files and EJB deployment descriptor are packed as
JAR files with .jar extension whereas in WAR web modules which contains Servlet
class files, JSP Files, GIF and HTML files are packaged as JAR file with .war
extension.
Explain
the difference between StringBuilder and StringBuffer class.
Q. How are
Observer and Observable used?
A. The observable
class represents an observable object.
The
object to be observed can be represented by sub-classing observable class.
When
there is a change in an observable instance, an application calling the Observable's
notifyObservers method causes all of its observers to be notified of the change
by a call to their update method.
Q. Difference
between Swing and Awt.
A. AWT are
heavy-weight components. Swings are light-weight components. Thus, swing works
faster than AWT.
Q. Define inner
class in Java
A. Class that is
nested within a class is called as inner class. The inner class can access
private members of the outer class. It is mainly used to implement data
structure and some time called as a helper class.
Q. Differences
between constructors and methods.
A. A constructor is
used to create objects of a class. A method is an ordinary member in a class.
Constructor
does not have a return type. A method should have a return type.
Constructor
name is the name of the class. A method name should not be the name of the
class
Constructor
is invoked at the time of creation of the class. Method needs to be invoked in
another method by using the dot operator.
Constructor
can not have ‘return’ statement. All methods that return non-void return type
should have ‘return’ statement.
Q. Define Method
overriding. Explain its uses.
A. Method overriding
is the process of writing functionality for methods with same signature and
return type, both in super class and subclass The uses of method overriding:
Time
to invest method signature is reduced
Different
functionality in both super class and sub class by sharing same signature
The
functionality can be enhanced
The
behavior can be replaced in the sub class
More
advanced java interview questions - senior level java interview
Q. What is the
purpose of the File class?
A. File class
provides access to the files and directories of a local file system.
Q. Can you explain
Native methods in Java?
A. • The Java native method is used to
merge the power of C or C++ programming into Java.
• To enhance to high performance
language, when efficient native Java compilers are not fully implemented, use
of native method boosts the performance to at least the speed of C compiled
code.
Java applications can call code written
in C, C++, or assembler. This is sometimes done for performance and sometimes
to access the underlying host operating system or GUI API using the JNI.
Q. Explain class loaders
in Java with an example.
A. • The
class loader describes the behavior of converting a named class into the bits
responsible for implementing that class.
• Class loaders eradicate the JREs need
to know anything about files and file systems when running Java programs.
• A
class loader creates a flat name space of class bodies that are referenced by a
string name and are written as:
Class
r = loadClass(String className, boolean resolveIt);
Q. What is
Reflection API in Java?
A. • The Reflection API allows Java code to
examine classes and objects at run time.
• The
new reflection classes allow you to call another class's methods dynamically at
run time.
• With
the reflection classes, you can also examine an instance's fields and change
the fields' contents.
• It is also possible to instantiate new
objects, invoke methods and get/set field values using reflection.
• The Reflection API consists of the
java.lang.Class class and the java.lang.reflect classes: Field, Method,
Constructor, Array, and Modifier.
Q. Static class
loading vs. dynamic class loading.
A. • The static class loading is done
through the new operator.
• Dynamic
class loading is achieved through Run time type identification. Also called as
reflection
This
is done with the help of the following methods:
getClass();
getName(); getDeclaredFields();
Instance
can also be created using forName() method. It loads the class into the current
class memory.
Q. Can you explain
shallow cloning and deep cloning?
A. Cloning of
objects can be very useful if you use the prototype pattern or if you want to
store an internal copy of an object inside an aggregation class for example.
• Deep cloning - You clone the
object and their constituent parts.
• It should be used when it is
inappropriate to separate the parts; the object is formed of, from it.
• Shallow cloning - You clone only
the object, not their parts. You add references to their parts.
• It should be used when it is
adequate to have the references added to the cloned object
Q. Explain the
purpose of Comparator Interface.
A. • Comparators
can be used to control the order of certain data structures and collection of
objects too.
• The
interface can be found in java.util.Comparator
• A
Comparator must define a compare function which takes two Objects and returns a
-1, 0, or 1
• Sorting
can be done implicitly by using data structures of by implementing sort methods
explicitly.
Q. What is the
impact of private constructor?
A. • Private Constructors can't be access
from any derived classes neither from another class.
• So
you have to provide a public function that calls the private constructor if the
object has not been initialized, or you have to return an instance to the
object, if it was initialized.
This
can be useful for objects that can't be instantiated.
Q. Can you explain
static Initializers in Java?
A. A static
initializer block resembles a method with no name, no arguments, and no return
type. There is no need to refer to it from outside the class definition.
Syntax:
Static
{
//CODE
}
The
code in a static initializer block is executed by the virtual machine when the
class is loaded.
Because
it is executed automatically when the class is loaded, parameters don't make
any sense, so a static initializer block doesn't have an argument list.
Q. Define
Externalizable Interface and explain its purpose.
A. • The Externizable interface extends the
serializable interface.
• When you use Serializable
interface, your class is serialized automatically by default. But you can
override writeObject() and readObject()two methods to control more complex
object serailization process.
• When you use Externalizable
interface, you have a complete control over your class's serialization process.
The two methods to be implemented are : void readExternal(ObjectInput)
• The object implements the
readExternal method to restore its contents by calling the methods of DataInput
for primitive types and readObject for objects, strings and arrays.
void
writeExternal(ObjectOutput)
• The object implements the
writeExternal method to save its contents by calling the methods of DataOutput
for its primitive values or calling the writeObject method of ObjectOutput for
objects, strings, and arrays.
Q: How are
Observer and Observable used?
A: Objects that
subclass the Observable class maintain a list of observers. When an Observable
object is updated it invokes the update() method of each of its observers to
notify the observers that it has changed state. The Observer interface is
implemented by objects that observe Observable objects.
Q: What is the
difference between the >> and >>> operators?
A: The >>
operator carries the sign bit when shifting right. The >>> zero-fills
bits that have been shifted out.
Q: Which method of
the Component class is used to set the position and size of a component?
A: setBounds()
method is used to set the position and size of a component.
Q: Which java.util
classes and interfaces support event handling?
A: The EventObject
class and the EventListener interface support event processing.
Q: Does garbage
collection guarantee that a program will not run out of memory?
A: Garbage
collection does not guarantee that a program will not run out of memory. It is
possible for programs to use up memory resources faster than they are garbage
collected. It is also possible for programs to create objects that are not
subject to garbage collection.
Q: What
restrictions are placed on the location of a package statement within a source
code file?
A: package statement
must appear as the first line in a source code file (excluding blank lines and
comments).
Q: Can an object's
finalize() method be invoked while it is reachable?
A: An object's
finalize() method cannot be invoked by the garbage collector while the object
is still reachable. However, an object's finalize() method may be invoked by
other objects.
Q: What is the
immediate superclass of the Applet class?
A: Panel.
Q: What is the
difference between preemptive scheduling and time slicing?
A: Under preemptive
scheduling, the highest priority task executes until it enters the waiting or
dead states or a higher priority task comes into existence. Under time slicing,
a task executes for a predefined slice of time and then reenters the pool of
ready tasks.
The
scheduler then determines which task should execute next, based on priority and
other factors.
No comments:
Post a Comment