Anda di halaman 1dari 15

Some Important FAQs on Java

1. What is the difference between an Interface and Abstract class ?

A class may implement several interfaces where as it can extend only


one abstract class.
An interface cannot provide any code at all, much less default code
where as an abstract class can provide complete code, default code,
and/or just stubs that has to be overridden.
Static final constants can use the interfaces without qualification in
classes that implement the interface where as both static constants
and instance variables can use the abstract classes.
Interface implementation can be added to any existing third part
classes where as third party classes must be rewritten to extend from
the abstract classes.
Interfaces are used to often represent peripheral ability of a class, not
central identity where as abstract class defines core identity of its
descendants.
If various implementations share is method signature then Interface
works best where as If the various implementations are all of a kind
and share a common status and behavior, usually an abstract class
works best.
Interface is slow where as abstract class is fast in performance.
If you add a new method to an interface, you must track down all
implementations of that interface in the universe and provide them
with a concrete implementation of that method where as in case of
an abstract class if you add a new method to an abstract class, you
have the option of providing a default implementation of it. Then all
existing code will continue to work without change.
You can put shared code into an abstract class, where you cannot
into an interface.

2. How do you write user-defined exceptions in Java?

To write user-defined exception in java, you exception class should


extend Exception base class have call the super class methods in
your own methods.

3. What is multiple inheritance? Is it supported in java?

This means one object having multiple parents, which is not truly
supported in java but supported in C++. But overall design of java
suggests that we can implement multiple inheritances in java using
interfaces.

4. What is difference between an inner class and static inner class?

A non-static inner class may have object instances that are associated
with instances of the class's outer class. A static inner class does not
have any object instances.

5. What is an inner class and what is its advantage?

Inner class is class, which is defined inside a class as private class and
always bears a reference to the outer class.
o Inner classes can be nested within the body of a method.
Scope of inner class is the entire enclosing class in which the inner
class is nested.
Inner classes can access attributes and methods in nesting class.
Each inner class is compiled into a separate. class file
labeled:NestingClass$InnerClass.
Inner classes can contain methods that return handles to inner class
instances.
Major advantage of inner classes is the ability to create adaptor
classes that implement an interface.
o Make all inner classes private to ensure hidden implementation.
o Rather than handle classes returning inner classes, they return
interfaces.
Inner classes frequently used with event handling in applets.
6. What is a transient variable?
o The variable, which cannot be serialized, is known as transient
variable.
7. What are wrapped classes?
o Wrapped classes are classes that allow primitive types to be accessed
as objects.
8. What is an immutable object and what are its advantages?

An immutable object is an object and any object it references that does


not change after construction. The object is, therefore, immutable for
its lifetime.
Immutable classes are commonly used to represent strings, colors,
and numeric values.

Advantage:

They guarantee that their state cannot change after construction,


they are inherently thread-safe.

9. What are basic rules, which govern creation of immutable classes?


Declare the class final.
Declare all data private.
Provide only getter methods and no setter methods.
Set all instance data in the constructor.
Clone mutable objects for which a reference to them is returned.
Clone mutable objects for which a reference to them is received.
Implement a deep clone if the default shallow clone is not correct for a
properly behaved immutable object.
10. What is a Java package and how is it used?

A Java package is a naming context for classes and interfaces. A


package is used to create a separate name space for groups of
classes and interfaces. Packages are also used to organize related
classes and interfaces into a single API unit and to control accessibility
to these classes and interfaces

11. What restrictions are placed on method overriding?

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.
The overriding method may not throw any exceptions that may not be
thrown by the overridden method.

12. What is use of this and super key words?

13.

this is used for referring to current instance of the object where as


super is used to refer to variables and methods of its super class.
Incase of constructors, this() is used to invoke a constructor of the
same class. super() is used to invoke a superclass constructor.
What is the difference between a static and non-static variable?

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.

14. What is polymorphism and what are different types of polymorphism?

One name, different form and there are three forms.


1. Method overloading
2. Method overriding through Interfaces
3. Method overriding through java interfaces.

15. What is the essence of run-time polymorphism behavior?


With runtime polymorphism based on method overriding, the
decision as to which version of a method will be executed is based
on the actual type of object whose reference is stored in the
reference variable, and not on the type of the reference variable on
which the method is invoked.
The decisions as to which version of the method to invoke cannot
be made at compile time. That decision must be deferred and
made at runtime. This is sometimes referred to as late binding.
16. What is a singleton class and how to implement it? What are the
advantages of Singleton class?
Singleton classes are created to have only one instance.
A singleton may be used to represent some unique system.
It is generally implemented by keeping the constructor private.
It should have static members and methods.
The main advantage of singleton class is memory management(
Garbage collection)
17. Why java prohibits use of synchronized inside a constructor ?
because other threads cannot get a reference to the object until
construction of the object completes. This has got a performance
overhead.
18. What do you mean by Garbage collection and what are its advantages
and disadvantages?
The purpose of garbage collection is to identify and discard objects
that are no longer needed by a program so that their resources may
be reclaimed.
An object is eligible for garbage collection when its reference is set to

null. Method variables or local variables are eligible for Garbage collection
when they go out of scope.
Garbage Collection cannot be forced explicitly. JVM may do garbage
collection if it is running short of memory.The call System.gc() does NOT
force the garbage collection but only suggests that the JVM may make an
effort to do garbage collection.

It frees up the heap space and takes care of heap fragmentation.


It also helps to ensure program integrity as programmers are
unable to crash the JVM by incorrectly freeing the memory
accidentally or purposefully.

The only disadvantage is garbage-collected heap is a performance


overhead.
19. What do you mean by conservative garbage collector?
The garbage collectors that cannot distinguish between genuine
object references and look-alikes.
20. Can an object's finalize () method be invoked while it is reachable?
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.
21. How many times may an object's finalize() method be invoked by the
garbage collector and when it is invoked ?
An object's finalize() method may only be invoked once by the
garbage collector when the object is unreachable.

22. Does garbage collection guarantee that a program will not run out of
memory?
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.

23. How does the distributed garbage collection work in java?


The RMI subsystem implements a reference counting-based
distributed garbage collection (DGC) algorithm to provide automatic
memory management facilities for remote server objects.
Basically, DGC works by having the remote server keep track of all
external client references to it at any given time. When a client
obtains a remote reference, it is addded to the remote object's
referenced set. The DGC then marks the remote object as dirty and
increases its reference count by one. When a client drops a
reference, the DGC decreases its reference count by one, and
marks the object as clean. When the reference count reaches zero,
the remote object is free of any live client references. It is then
placed on the weak reference list and subject to periodic garbage
collection.
24. What is the priority of Garbage collection thread in java ?
This is a low-priority thread in java.
25. How many applications can be run by one run-time instance of JVM ?

One run-time instance of java application can run only one


instance.
26. When the JVM terminates ?
The Java Virtual machine terminates when all the non-daemon
threads of java application terminates.
If permitted by the security manager it can also call
System.runtime.ext () for terminating the JVM.

27. Is it possible to know from the content of a class file whether it is a java
class file or not?
The first four bytes of every java class file is a magic number
0xCAFEBABE. So it is very easy to identify whether it is a java
class file or not.

28. Name the process thru which JVM makes the types available to the
running program?
The Java Virtual Machine makes types available to the running
program through a process of loading, linking, and initialization.

29. Define loading, linking and initialization of java class ?

Loading : Loading is the process of bringing a binary form for a


type into the Java Virtual Machine.
Linking : Linking is the process of incorporating the binary type
data into the runtime state of the virtual machine. Linking is divided
into three sub-steps: verification, preparation, and resolution.
Initialization: During initialization the class variables are their
proper initial values.

30. What do you mean by first active use of a class in JVM?

The invocation of a constructor on a new instance of the class.


The creation of an array that has the class as its an element type.
The invocation of a method declared by the class (not inherited
from a super class) .

The use or assignment of a field declared by the class (not


inherited from a superclass or super interface), except for fields that
are both static and final, and are initialized by a compile-time
constant expression.

31. What are steps involved in loading of a class file into JVM?

Produce a stream of binary data that represents the type.


Parse the stream of binary data into internal data structures in the
method area.
Create an instance of class java.lang.Class that represents the
type.

32. Is it possible to detect a malformed class file during early loading by the
class loader?
No it is not possible. If a class loader encounters a missing or
malformed class file during early loading, it must wait to report that
error until the class is first active use by the program.
33. What are the different stages of linking after the class is loaded?
Verification, prepare and resolve are the three phases of linking.

34. What is verification stage and what are steps involved during verification?
It ensures that the types obey the semantics of java language and
doesnt violate the integrity of JVM.
The entire process of detecting any kind of problem with loaded
types is placed under the category of verification.
Verification of symbolic references and converting them to direct
references.

checking that final classes are not sub classed


checking that final methods are not overridden
if the type being checked is a non-abstract class, checking that all
the methods declared in any interfaces implemented by the class
are indeed implemented by the class
Making sure no incompatible method declarations (such as two
methods that have the same name, the same number, order, and
types of parameters, but different return types) appear between the
type and its supertypes.

35. What is done during Preparation Stage?

The Java Virtual Machine allocates memory for the class variables
and sets them to default initial values. The class variables are not
initialized to their proper initial values until the initialization phase.
Java Virtual Machine implementations may also allocate memory
for data structures that are intended to improve the performance of
the running program.
36. What happens during Resolution Phase?

Resolution is the process of locating classes, interfaces, fields, and


methods referenced symbolically from a types constant pool, and
replacing those symbolic references with direct references.

37. How the initialization of class is is different from initialization of interface?

Initialization of class requires initialization of its super classes but


initialization of interfaces doesnt require initialization of it super
interfaces.

38. What is a JIT compiler?


JIT compilers are used to convert the java byte codes to native
types on the fly.

39. What is the difference between instance method and class method ?

Instance methods require an instance before they can be invoked;


class methods do not.
Instance methods use dynamic (late) binding; class(static methods)
methods use static (early) binding.

40. What is the difference between a process and Thread?


A process is a self-contained running program within its own
address space while a Thread is a single sequential flow of control
within a process.
Each process has its own set of variables where as Threads share
the same data.

Inter-process communication is much slower and restrictive as


compared to inter-thread communication is faster.
Creating and destroying Thread is much cheaper in terms of
performance overhead as compared to launching a new process.
41. What is the difference between pre-emptive multi-tasking and cooperative multi-tasking?
In case of pre-emptive multitasking, the program is interrupted
without consulting first where as in case of co-operative
multitasking; programs are interrupted only when they are willing to
yield control.
Windows 95,NT pre-emptive multi-tasking where Windows 3.1 is
co-operative multitasking.
Pre-emptive multi-tasking is more effective as compared cooperative multitasking.

42. What is difference between creating a thread by extending Thread class


and implementing Runnable?

43. Explain the four different states of a thread


The four different states of a thread are
1. new: When a thread is created with new operator .It is not
yet running.
2. Runnable: Once you invoke the start method on the thread it
becomes runnable. It is up to the OS to decide when to give
time to the thread to run. A runnable thread may or may not
be running.
3. Blocked : Thread enters this state under the following
condition.
1. Someone calls sleep () on the thread.
2. Thread calls an operation that blocks on input/output.
3. Thread calls wait() method.
4. Thread tries to lock an object that is currently locked
by another thread.
4. Dead : The Thread is dead for one of two reasons.
1. It dies a natural death because the run method exits
normally.
2. It dies abruptly because an uncaught exception
terminates the run method.

44. What happens when there are more than one highest priority threads
having same priority?
In that case only one of the thread is picked up. It is up to the
thread Scheduler to arbitrate between threads of same priority.
There is no guarantee that all the same priority threads will be fairly
treated.

45. Why do threads block on I/O ?


Threads block on I/O so that other threads may execute while the
I/O operation is performed.

46. What are the methods which can only be called from within a
Synchronized method or block ?
Notify (): unblocks one randomly selected thread among the
threads that called wait() on this object.
NoitifyAll() : unblocks the threads that called wait() on this object.
Wait (): causes the thread to wait until it is notified.
47. What is the difference between yield and sleep methods of Thread?

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.
48. Why stop and suspend method are deprecated?
Stop() terminates the thread abruptly while suspend() method
blocks a thread until another thread calls resume () on it.
Stop () method will leave an object in inconsistent state because it
immediately gives up locks on all other object that it has locked. For
example, during transfer of money from one account to other
account if the transfer thread is stopped, the bank account object is
damaged. When a thread wants to stop another thread, it doesnt
know when it is safe to stop that thread. So it has been deprecated.
Suspend () method frequently leads to deadlocks .It can be invoked
on a thread externally at any point of time without the threads
consent which is not desired. For this reason it has been
deprecated.

49. What is difference between sleep() ,wait()and suspend() of a Thread ?


Thread.sleep() sends the current thread into the "Not Runnable"
state for some amount of time. The thread keeps the monitors it
has acquired -- i.e. if the thread is currently in a synchronized block
or method no other thread can enter this block or method. If
another thread calls t.interrupt () it will wake up the sleeping thread.

Note that sleep is a static method, which means that it


always affects the current thread (the one that is executing the
sleep method). A common mistake is to call t.sleep() where t is a
different thread; even then, it is the current thread that will sleep,
not the t thread.
t.suspend() is deprecated. Using it is possible to halt a
thread other than the current thread. A suspended thread keeps all
its monitors and since this state is not interruptible it is deadlock
prone.
object.wait() sends the current thread into the "Not
Runnable" state, like sleep(), but with a twist. Wait is called on a
object, not a thread; we call this object the "lock object." Before
lock.wait() is called, the current thread must synchronize on the
lock object; wait() then releases this lock, and adds the thread to
the "wait list" associated with the lock. Later, another thread can
synchronize on the same lock object and call lock.notify(). This
wakes up the original, waiting thread. Basically, wait()/notify() is like

sleep()/interrupt(), only the active thread does not need a direct


pointer to the sleeping thread, but only to the shared lock object.
50. What is "starvation" when used in the context of the Java threading
model?
Starvation is when the Java runtime (JVM) doesn't allocate time to
a thread to execute. This may be due to a poor scheduling
algorithm (like green Threads under Solaris, where a for loop from
1 to 1 million doing something CPU intensive wouldn't yield the
CPU under Solaris but would under Windows), poor programming
practice (not returning from the paint() method in an applet), or a
hostile attack (like hitting a host with a denial of service attack
where the CPU is busy outside the Java process).

51. What is a daemon thread?


Daemon is a thread that has only purpose in life is to serve others.

When only daemon threads remain, the program exits.

52. What is the difference between a Green thread and Native thread

Green Threads" are the default threads that are provided in the
JDK, while the "Native Threads" are the one provided by the native
Operating System.
Normally "Native Threads" provide better performance because
they are controlled by the kernel of the system, allowing the JVM to
better use the resources offered by the system itself.
For example, in a multiprocessor system "Green Threads" will
never be able to use Solaris or Linux or Windows specified kernel
calls to optimize the use of the processors.

53. What is an object graph?

When used in connection with serialization, an object graph is a


tree structure rooted at the object you have written to the
ObjectOutputStream. The branches and leaves of the tree are all
the objects, which are reachable by following references from the
root object. This structure is maintained by the ObjectOutputStream
in order to ensure that the complete reachable state of the given
object is serialized and to handle cyclic dependencies. The graph is
computed on the fly, during the serialization process.
A side-effect of maintaining this graph is that an object which
has already been written to the stream will not be written again - it
will be replaced by an object stream identifier, simply a number
used to point at the previously object. To force a changed object to
be written in its entirety, you need to reset() the stream, which
clears the object graph

54. Can a Vector or a Hashtable be serialized and deserialized?

Both these classes implement Serializable, and have been


designed for serialization. So yes, they can be serialized.
In order to serialize a collection like Vector or Hashtable, you must
also be able to serialize all of the objects contained in these
collections. Otherwise, the collection would not be able to be
completely restored. Your program will throw a
NotSerializableException unless all objects stored in the Vector or
Hashtable are also serializable.

55. Is writing an object to an ObjectOutputStream a thread-safe operation?

Absolutely not. Serialization, i.e. passing an object reference to the


writeObject () method of ObjectOutputStream, is not an atomic
operation. Serialization involves traversing a graph of objects, each
of which contributes to the state of the object being serialized,
saving the state of each object in turn. This is a time-consuming
procedure. If other threads are allowed to concurrently access or
modify any one of the objects in the graph you could get undefined
and unwanted results.

56. What is the advantage of using Externalizable over Serializable?

Externalization allows a class to specify the methods to be used to


write the object's contents to a stream and to read them back . By
implementing Externalizable you can win performance at the cost of
flexibility and extra code to maintain. If you implement
Externalizable you stream the data directly without the need for
reflection, which is used in the case of Serializable.

57. What is JNDI and what is its use?

JNDI is Java Naming and Directory Services provides a standard


interface to locate users, machines, networks, objects and services.

58. Define a naming service?

Associates names with objects, which is otherwise called binding.


It provides a facility to find objects based on names, which is
otherwise known as look-up.

When it is required to locate a machine on the network, DNS is


used to translate the machine name to IP Address.

59. What is a directory object? Is it different from naming object?


A directory object can store attributes with it. A directory metadata
contains how the directory is structured.
60. What are the standard naming and directory services available?

LDAP, NIS (Network Information services) and NDS (Novell


Directory Services).

61. What are the advantages of using JNDI?

It is unified to system to access all sorts of directory service


information.

It is single API to access different directories with different


protocols.

It insulates application from protocol and implementation details.

It is extensible. Future provider of directories can plug in their


particular directory services to JNDI without affecting client code.

Source : Core Java, JVM Fundamentals etc

Anda mungkin juga menyukai