Вы находитесь на странице: 1из 12

Why the methods of the Math class are static?

Its to reduce un-necessary object creation.

Generally utility class methods should be kept static.
See if the methods of Math class are non static then you will have to create object of
Math class every time and that object is of no use after method is called once.
To reduce un necessary object creation and keep the garbage collector heap healthy
method should be made static if they are utility methods.

Math class methods do not depend on instance variables ...

hence, why to create a object of math class....

math.min(2,1) -> 1

Method execution in math class depend on method args, and not instance variables...
Even if u tries to create an object of Math class ...
U will get an exception... Since math class has a private constructor..

Can we define an interface within an interface?

Yes u can write interface within another interface.
And if u want to implement inner interface u have to access it using
// abc.java
interface abc {
void show();

public interface xyz {

void calc();

// InterfaceImpl.java

public class InterfaceImpl implements abc.xyz {

public void show()


public void calc(){}

What is the meaning of persistence?

Persistence means 'to save'. In java, persistence is referred to saving the state of an object
from memory to some other media (mostly permanent media such as hard disk, but it can
be a database, a network stream etc. etc.).

Hibernate is an Object to Relational mapping framework. It helps in persisting (or saving)

and loading (a.k.a mapping) the state of objects in your application to a relational
database management system. The reason it is so popular is because it is based on
configuration files (also called as declarative programming). It generate all the boilerplate
JDBC code for you, you just have to focus on the API's methods to persist the objects
from your java programs.

Is Java fully object oriented?

There is lot many reasons to say...
Java supports OOP concepts partially...
But not fully...
The main aim of java is to avoid any complexity for programmers...
So they avoided almost all the complexity from the OOP...
Like multiple inheritance, friend functions, operator overloading... Etc...

The main reason for keeping primitive types as non-objects is speed. For all the places
where primitive types don’t make sense (such as containers etc.) you have the option to
'wrap' then in their equivalent objects. JDK 1.5 even introduces the concept of autoboxing
to make this transition even more programmers friendly.

Why interfaces cannot contain static methods whereas they

can contain static variables?

1) Interface means, you can say that it is really incomplete....

that is the reason, you can not create the instances....

2) In second point, the all methods in the interface are abstract method... Simply you can
say, abstract methods are also the incomplete method.

3) And when the methods are incomplete, the class is also incomplete, so even for the
abstract class which is partially incomplete, you can't create the object. Because it
restricts the abstract methods to be called by object because they are abstract.

4) And you know very well, that, static methods do not need any object to be created to
get called of. So directly they can be called as <classname>.<methodname>.

5) Now think, when the method is abstract (may be in abstract class or interface), and it is
incomplete, and you invoke that method, then, how it can be used when it is
incomplete???? So you can't use static. (When you use static with a method, you can call
directly without creating an object). So you can't do it.

encodeURL vs. encodeRedirectURL

Both these methods revolve around the concept of URL rewriting. I don’t know whether
u r aware bout this. But basically it involves suffixing the URL with a
HTTP_QUERY_STRING, which mostly is a session id used to keep track of a particular
users context. URL re-writing is used get over the usage of cookies which are dependent
on browser configuration, thus not reliable at all. Now Session is a comprehensive topic
on its own, so won’t discuss it now.

But yes the difference between the methods is in their usage and not their functionality.
Both perform the same task of re-writing a URL.

us use encodeRedirectURL when u send a redirect header to the browser using

response.sendRedirect(string URL)

for e.g. lets say on a particular condition u want to redirect to different page

if (name == null){


on the other hand lets say u want to provide a link to shopping cart page to a user -

printWriter.println("A HREF=" + response.encodeURL("shoppingCart.jasp") + ">")

thus essentially they do same thing of re-writing the URL for non-cookie compliant
In short.....
encodeURL is used for all URLs in a servlet's output.
It helps session ids to be encoded with the URL.

encodeRedirectURL () is used with res.sendRedirect only. It is also used for encoding

session ids with URL but only while redirecting.

Transient variable can't be final or static

The modifier transient can be applied to field members of a class to turn off serialization
on these field members. Every field marked as transient will not be serialized. You use
the transient keyword to indicate to the Java virtual machine that the transient variable is
not part of the persistent state of an object.

Java classes often hold some globally relevant value in a static class variable. The static
member fields belong to class and not to an individual instance. The concept of
serialization is concerned with the object's current state. Only data associated with a
specific instance of a class is serialized, therefore static member fields are ignored during
serialization (they are not serialized automatically), because they do not belong to the
serialized instance, but to the class. To serialize data stored in a static variable one must
provide class-specific serialization.

Surprisingly, the java compiler does not complaint if you declare a static member field as
transient. However, there is no point in declaring a static member field as transient, since
transient means: "do not serialize” and static fields would not be serialized anyway.

On the other hand, an instance member field declared as final could also be transient, but
if so, you would face a problem a little bit difficult to solve: As the field is transient, its
state would not be serialized, it implies that, when you deserialize the object you would
have to initialize the field manually, however, as it is declared final, the compiler would
complaint about it.

For instance, maybe you do not want to serialize your class' logger, then you declared it
this way:

private transient final Log log = LogFactory.getLog(EJBRefFactory.class);

Now, when you deserialize the class your logger will be a null object, since it was
transient. Then you should initialize the logger manually after serialization or during the
serialization process. But you can't, because logger is a final member as well.

How JVM performs Thread Synchronization?

JVM associates a lock with an object or a class to achieve multithreading. A lock is like a
token or privilege that only one thread can "possess" at any one time. When a thread
wants to lock a particular object or class, it asks the JVM.JVM responds to thread with a
lock maybe very soon, maybe later, or never. When the thread no longer needs the lock, it
returns it to the JVM. If another thread has requested the same lock, the JVM passes the
lock to that thread. If a thread has a lock, no other thread can access the locked data until
the thread that owns the lock releases it.

The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in
that it watches over a sequence of code, making sure only one thread at a time executes
the code. Each monitor is associated with an object reference. It is the responsibility of
monitor to watch an arriving thread must obtain a lock on the referenced object.

When the thread leaves the block, it releases the lock on the associated object. A single
thread is allowed to lock the same object multiple times. JVM maintains a count of the
number of times the object has been locked. An unlocked object has a count of zero.
When a thread acquires the lock for the first time, the count is incremented to one. Each
time the thread acquires a lock on the same object, a count is incremented. Each time the
thread releases the lock, the count is decremented. When the count reaches zero, the lock
is released and made available to other threads.

In Java language terminology, the coordination of multiple threads that must access
shared data is called synchronization. The language provides two built-in ways to
synchronize access to data: with synchronized statements or synchronized methods.

The JVM does not use any special opcodes to invoke or return from synchronized
methods. When the JVM resolves the symbolic reference to a method, it determines
whether the method is synchronized. If it is, the JVM acquires a lock before invoking the
method. For an instance method, the JVM acquires the lock associated with the object
upon which the method is being invoked. For a class method, it acquires the lock
associated with the class to which the method belongs. After a synchronized method
completes, whether it completes by returning or by throwing an exception, the lock is

Two opcodes, monitorenter and monitorexit are used by JVM for accomplishing this task.

When monitorenter is encountered by the Java virtual machine, it acquires the lock for
the object referred to by objectref on the stack. If the thread already owns the lock for that
object, a count is incremented. Each time monitorexit is executed for the thread on the
object, the count is decremented. When the count reaches zero, the monitor is released.

What is a class loader and what are its responsibilities?

The Class loader is a subsystem of a JVM which is responsible, predominantly for

loading classes and interfaces in the system. Apart from this, a class loader is responsible
for the following activities:

-Verification of imported types(classes and interfaces)

-Allocating memory for class variables and initializing them to default values. Static
fields for a class are created and these are set to standard default values but they are not
explicitly initialized. The method tables are constructed for the class.

-Resolving symbolic references from type to direct references The class loaders can be of
two types: a bootstrap or primordial class loader and user defined class loaderEach JVM
has a bootstrap class loader which loads trusted classes , including classes from Java
API.JVM specs do not tell how to locate these classes and is left to implementation
A Java application with user defined class loader objects can customize class loading.
These load untrustworthy classes and not an intrinsic part of JVM.They are written in
Java, converted to class files and loaded into the JVM and installed like any other objects.
Does Java support multi dimensional arrays?

The Java programming language does not really support multi-dimensional arrays. It
does, however, support arrays of arrays. In Java, a two-dimensional array 'arr' is really an
array of one-dimensional arrays:
int[][] arr = new int[4][6];

The expression arr[i] selects the one-dimensional array; the expression arr[i][j] selects the
element from that array.
The built-in multi-dimensional arrays suffer the same indignities that simple one-
dimensional arrays do: Array indices in each dimension range from zero to, where length
is the array length in the given dimension. There is no array assignment operator. The
number of dimensions and the size of each dimension is fixed once the array has been

What is Early Binding?

The assignment of types to variables and expressions at compilation time is known as

'Early Binding’, it is also called 'static binding' and 'static typing'.

What is Java class file's magic number?

A Magic Number of a class file is a unique identifier for tools to quickly differentiate
class files from non class files. The first four bytes of each Java class file has the magic
value as 0xCAFEBABE.And the answer to why this number, I do not actually know but
there may be very few sensible and acceptable options possible constructed from letters
A-F which can surely not be 'CAFEFACE' or 'FADECAFE'....

What is the difference between JVM and JRE?

A Java Runtime Environment (JRE) is a prerequisite for running Java applications on any
computer. A JRE contains a Java Virtual Machine (JVM), all standard, core java classes
and runtime libraries. It does not contain any development tools such as compiler,
debugger, etc. JDK (Java Development Kit) is a whole package required to Java
Development which essentially contains JRE+JVM, and tools required to compile and
debug, execute Java applications.

Does a class inherit constructors from its superclass?

Is 'sizeof' a keyword?

No, 'sizeof' is an operator used in C and C++ to determine the bytes of a data item, but it
is not used in Java as all data types are standard sized in all machines as per
specifications of the language.
A JVM is free to store data any way it pleases internally, big or little endian, with any
amount of padding or overhead, though primitives must behave as if they had the official
sizes.In JDK 1.5+ you can use java.lang.instrument.Instrumentation. getObjectSize() to
get the object size.

What is the difference between process and threads?

A thread is part of a process; a process may contain several different threads. Two threads
of the same process share a good deal of state and are not protected against one another,
whereas two different processes share no state and are protected against one another. Two
threads of the same process have different values of the program counter; different stacks
(local variables); and different registers. The program counter, stack pointer, and registers
are therefore saved in the thread table. Two threads share open files and memory
allocation; therefore, file information and memory information (e.g. base/limit register or
page table) is stored in the process table.

Can an inner class be defined inside a method?

Yes it can be defined inside a method and it can access data of the
enclosing methods or a formal parameter if it is final.

What is an anonymous class?

It is a type of inner class with no name. Once defined an object can be

created of that type as a parameter all in one line. it cannot have
explicitly declared constructor. The compiler automatically provides an
anonymous constructor for such class.

An anonymous class is never abstract. An anonymous class is always an

inner class; it is never static. An anonymous class is always
implicitly final.

What modifiers may be used with an inner class that is a member of an

outer class?

A (non-local) inner class may be declared as public, protected,

private, static, final, or abstract.
Why are wait(), notify(), and notifyAll() in the Object class?

Many new Java programmers ask this question when they're just starting out, and it's a
good question. After all, these methods have something to do with threads, so why aren't
they in the thread class?

The answer is that Threads can use Objects to transmit messages from one thread to
another, and these methods allow that to happen. A Thread calls wait() to say "I am
waiting for a message to be sent to this object." Another thread can call notify() to say "I
am sending a message to that object." The Object is therefore a conduit through which
threads communicate without explicitly referencing each other. If the methods were in the
Thread class, then two threads would need to have references to one another to
communicate. Instead, all communicating threads just need to agree to use some specific
shared resource.

What is Composition and how it maps into a Java class

A Composition is a tight Association and denotes "whole-part" relationship.So when an

object is destroyed then all its constituents are also destroyed, these 'parts' have no
meaning/sense in their lone existence from their 'whole'.

The best example of Composition is a 'Human body' which is composed of two legs,two
hands,two eyes,two ears and so on.During the lifetime of a human being,all organs make
sense being part of whole,but once a human being is dead most of these parts are also
dead,unless some of his body parts are not medically reused.

Now come to map composition to Java world, the best example is garbage collection
feature of the language.While garbage collecting objects, whole has the responsibility of
preventing all its parts being garbage collected by holding some references to them.

It is the responsibility of whole to protect references to its parts not being exposed to
outside world.The only way to have true composition in Java is to never let references to
internal objects escape their parent's scope.

An example of Inner class as shown in the following code snippet may give you an idea
how to implement Composition in Java.

public class Human


public Human()
Brain brain = new Brain();
private class Brain

What is a Daemon thread?

A ''daemon'' thread is one that is supposed to provide a general service in the background
as long as the program is running, but is not part of the essence of the program. Thus,
when all of the non
daemon threads complete the program is terminated. Conversely, if there are any non-
daemon threads still running the program doesn' t terminate.

What is the difference between Serializable and Externalizable interface?

java.io.Serializable interface is an empty interface with no methods and attributes.It is

implemented by objects which are needed to be serialized and serves only to identify the
semantics of being serializable.
When process of serializing an object is to be controlled then Externalizable interface is
used.The Externizable interface extends Serializable and adds two
methods,writeExternal() and readExternal() which are automatically called during
serialization and deserialization.
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,


What is memory leak?

A memory leak occurs when all references (pointers) to a piece of allocated memory are
overwritten, cleared, or pass out of scope. The result is that the program simply "forgets"
about that particular piece of memory.Unfortunately , the operating environment (usually
an OS) is not aware of the application's amnesia. That memory is treated by the outside
world as though it still belongs to the application. The memory is therefore completely
unavailable;it has "leaked". (In the worst case, the memory can become unavailable to all
applications in the system, even if the application that created the leak is terminated. The
memory can only be reclaimed by rebooting the system.)
Explain StreamTokenizer?

The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the
tokens to be read one at a time. The parsing process is controlled by a table and a number
of flags that can be set to various states. The stream tokenizer can recognize identifiers,
numbers, quoted strings, and various comment styles.

Each byte read from the input stream is regarded as a character in the range '\u0000'
through '\u00FF'. The character value is used to look up five possible attributes of the
character: white space, alphabetic, numeric, string quote, and comment character. Each
character can have zero or more of these attributes.

In addition, an instance has four flags. These flags indicate:

Whether line terminators are to be returned as tokens or treated as white space that
merely separates tokens.
Whether C-style comments are to be recognized and skipped.
Whether C++-style comments are to be recognized and skipped.
Whether the characters of identifiers are converted to lowercase.
A typical application first constructs an instance of this class, sets up the syntax tables,
and then repeatedly loops calling the nextToken method in each iteration of the loop until
it returns the value TT_EOF.

What is the purpose of Void class? - The Void class is an uninstantiable placeholder
class to hold a reference to the Class object representing the primitive Java type void.

Can an anonymous class implement an interface and extend a class at the

same time?

No, an anonymous class can either implement an interface or extend a class at a particular
time but not both at the same time.

Can protected or friendly features be accessed from different packages?

No,when features are friendly or protected they can be accessed from all the classes in
that package but not from classes in another package.

How many ways can one write an infinite loop ?

Personally I would recommend following ways to implement infinite loop in Java but
their can be other ways like calling a method recursively , though I never tested that.
- while (true)
- for (;;) { }
What is Exception ?

An exception is an abnormal behavior existing during a normal execution of a program.

For example: When writing to a file if there does not exist required file then an
appropriate exception will be thrown by java code.

What is a user-defined exception?

For every project you implement you need to have a project dependent exception class so
that objects of this type can be thrown so in order to cater this kind of requirement the
need for user defined exception class is realized.
for example:

class MyException extends Exception

public MyException(){};
public MyException(String msg)

What is the difference between Java class and bean?

What differentiates Beans from typical Java classes is introspection. The tools that
recognize predefined patterns in method signatures and class definitions can "look inside"
a Bean to determine its properties and behavior. A Bean's state can be manipulated at the
time it is being assembled as a part within a larger application. The application assembly
is referred to as design time in contrast to run time. In order for this scheme to work,
method signatures within Beans must follow a certain pattern in order for introspection
tools to recognize how Beans can be manipulated, both at design time, and run time.

How do you set Java library path programatically?

Java library path can be set by choosing an option as:-


While setting the java.library.path property to "." instructs the Java virtual
machine to search for native libraries in the current directory.
And you execute your code as :
java -Djava.library.path=. HelloWorld

The "-D" command-line option sets a Java platform system property. But these
values are 'read only' like many of the system properties, the value in java.library.path
is just FYI and changing it doesn't actually change the behaviour of the JVM.
If you want to load a library from a specific location, you can use System.load() instead
with the full path to the library.

What is a thread?

A thread is most fundamental unit of a computer program which is under execution

independent of other parts.A thread and a task are similar and often confused.An
operating system executes a program by allocating it certain resources like memory,CPU
cycles and when there are many a programs doing several things corresponding to several
users requests.In such a scenario each program is viewed as a 'task' by OS for which it
identifies an allocate resources. An OS treats each application e.g. Word
Processor,spreadsheet,email client etc as a separate task , if a certain program initiates
some parallel activity e.g. doing some IO operations,printing then a 'thread' will be
created fro doing this job.