Skip to main content

Java Interview Questions

1)What if the main method is declared as private?
The program compiles properly but at runtime it will give “Main method not
public.” message.
2)What is meant by pass by reference and pass by value in Java?
Pass by reference means, passing the address itself rather than passing the
value. Pass by value means passing a copy of the value.
3)If you’re overriding the method equals() of an object, which other method you
might also consider?
hashCode()
What is Byte Code?
Or
What gives java it’s “write once and run anywhere” nature?
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.
4)Expain the reason for each keyword of public static void main(String args[])?
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.
5)What are the differences between == and .equals() ?
Or
what is difference between == and equals
Or
Difference between == and equals method
Or
What would you use to compare two String variables – the operator == or the
method equals()?
Or
How is it possible for two String objects with identical values not to be equal
under the == operator?
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
false
Using equals method : true
6)What if the static modifier is removed from the signature of the main method?
Or
What if I do not provide the String array as the argument to the method?
Program compiles. But at runtime throws an error “NoSuchMethodError”.
7)What is the difference between final, finally and finalize? What do you
understand by the java final keyword?
Or
What is final, finalize() and finally?
Or
What is finalize() method?
Or
What is the difference between final, finally and finalize?
Or
What does it mean that a class or member is final?
o final – declare constant
o finally – handles exception
o finalize – helps in garbage collection
Variables defined in an interface are implicitly final. A final class can’t be
extended i.e., final class may not be subclassed. This is done for security
reasons with basic classes like String and Integer. It also allows the compiler
to make some optimizations, and makes thread safety a little easier to achieve.
A final method can’t be overridden when its class is inherited. You can’t
change value of a final variable (is a constant). finalize() method is used
just before an object is destroyed and garbage collected. finally, a key word
used in exception handling and will be executed whether or not an exception is
thrown. For example, closing of open connections is done in the finally method.
8)What is the Java API?
The Java API is a large collection of ready-made software components that
provide many useful capabilities, such as graphical user interface (GUI)
widgets.
9)What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
10)What is the ResourceBundle class?
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.
11)Why there are no global variables in Java?
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 creates collisions in namespace.
12)How to convert String to Number in java program?
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();
13)What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
14)What is the difference between a while statement and a do statement?
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.
15)Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism,
Inheritance and Encapsulation.
16)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
17)What is a native method?
A native method is a method that is implemented in a language other than Java.
18)What are Encapsulation, Inheritance and Polymorphism
Or
Explain the Polymorphism principle. Explain the different forms of
Polymorphism.
Polymorphism in simple terms means one name many forms. Polymorphism enables
one entity to be used as a general category for different types of actions. The
specific action is determined by the exact nature of the situation.
Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
19)What is explicit casting?
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
20)What are Java Access Specifiers?
Or
What is the difference between public, private, protected and default Access
Specifiers?
Or
What are different types of access modifiers?
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
21)What is the difference between static and non-static variables?
Or
What are class variables?
Or
What is static in java?
Or
What is a static method?
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 its 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.
22)Which class is the superclass of every class?
Object.
Name primitive Java types.
The 8 primitive types are byte, char, short, int, long, float, double, and
boolean.
23)What is the difference between the boolean & operator and the && operator?
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.
24)How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the
type allowed by the operation.
25)What if I write static public void instead of public static void?
Program compiles and runs properly.
26)What is the difference between declaring a variable and defining a variable?
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.
27)What type of parameter passing does Java support?
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.
28)Explain the Encapsulation principle?
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
29)What do you understand by casting in java language? What are the types of
casting?
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.
30)Can an application have multiple classes having main method?
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.
31)When is static variable loaded? Is it at compile time or runtime? When
exactly a static block is loaded in Java?
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.
32)Can I have multiple main methods in the same class?
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.
33)Explain working of Java Virtual Machine (JVM)?
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.
34)What is data encapsulation?
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.
35)What is reflection API? How are they implemented?
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.
36)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
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP,
but references to those objects are on the STACK.

Core java FAQ’s


1)Question: What do you understand by Synchronization?
————
*Answer: Synchronization is a process of controlling the access of shared
———
resources by the multiple threads in such a manner that only one thread can
access one resource at a time. In non synchronized multithreaded application,
it is possible for one thread to modify a shared object while another thread is
in the process of using or updating the object’s value. Synchronization
prevents such type of data corruption.
E.g. Synchronizing a function:
——————————–
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.
}
}
2)Question: What is Collection API?
————–
*Answer: The Collection API is a set of classes and interfaces that support
——–
operation on collections of objects. These classes and interfaces are more
flexible, more powerful, and more regular than the vectors, arrays, and
hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and
——————-
TreeMap.
Example of interfaces: Collection, Set, List and Map.
———————-
3)Question: Is Iterator a Class or Interface? What is its use?
Answer: Iterator is an interface which is used to step through the elements of
a Collection.
4)Question: What is similarities/difference between an Abstract class and
Interface?
Answer:  Differences are as follows:
Interfaces provide a form of multiple inheritance. A class can extend only
one other class.
Interfaces are limited to public methods and constants with no
implementation. Abstract classes can have a partial implementation, protected
parts, static methods, etc.
A Class may implement several interfaces. But in case of abstract class, a
class may extend only one abstract class.
Interfaces are slow as it requires extra indirection to to find
corresponding method in in the actual class. Abstract classes are fast.
Similarities:
Neither Abstract classes or Interface can be instantiated.
5)Question: How to define an Abstract class?
Answer: A class containing abstract method is called Abstract class. An
Abstract class can’t be instantiated.
Example of Abstract class:
abstract class testAbstractClass {
protected String myString;
public String getMyString() {
return myString;
}
public abstract string anyAbstractFunction();
}
6)Question: How to define an Interface?
Answer: In Java Interface defines the methods but does not implement them.
Interface can include constants. A class that implements the interfaces is
bound to implement all the methods defined in Interface.
Emaple of Interface:
public interface sampleInterface {
public void functionOne();
public long CONSTANT_ONE = 1000;
}
7)Question: Explain the user defined Exceptions?
Answer: User defined Exceptions are the separate Exception classes defined by
the user for specific purposed. An user defined can created by simply sub-
classing it to the Exception class. This allows custom exceptions to be
generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
// The class simply has to exist to be an exception
}
8)Question: Explain garbage collection?
Answer: Garbage collection is one of the most important feature of Java.
Garbage collection is also called automatic memory management as JVM
automatically removes the unused variables/objects (value is null) from the
memory. User program cann’t directly free the object from memory, instead it is
the job of the garbage collector to automatically free the objects that are no
longer referenced by a program. Every class inherits finalize() method from
java.lang.Object, the finalize() method is called by garbage collector when it
determines no more references to the object exists. In Java, it is good idea to
explicitly assign null into a variable when no more in use. I Java on calling
System.gc() and Runtime.gc(),  JVM tries to recycle the unused objects, but
there is no guarantee when all the objects will garbage collected.
9)Question: How you can force the garbage collection?
Answer: Garbage collection automatic process and can’t be forced.
10)Question: Describe the principles of OOPS.
Answer: There are three main principals of oops which are called Polymorphism,
Inheritance and Encapsulation.
11)Question: Explain the Encapsulation principle.
Answer: Encapsulation is a process of binding or wrapping the data and the
codes that operates on the data into a single entity. This keeps the data safe
from outside interface and misuse. 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.
12)Question: Explain the Inheritance principle.
Answer: Inheritance is the process by which one object acquires the properties
of another object.
13)Question: Explain the Polymorphism principle.
Answer: The meaning of Polymorphism is something like one name many forms.
Polymorphism enables one entity to be used as as general category for different
types of actions. The specific action is determined by the exact nature of the
situation. The concept of polymorphism can be explained as “one interface,
multiple methods”.
14)Question: Explain the different forms of Polymorphism.
Answer: From a practical programming viewpoint, polymorphism exists in three
distinct forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface
15)Question: What are Access Specifiers available in Java?
Answer: Access specifiers are keywords that determines the type of access to
the member of a class. These are:
Public
Protected
Private
Defaults
16)Question: Describe the wrapper classes in Java.
Answer: Wrapper class is wrapper around a primitive data type. An instance of a
wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper
classes:
Primitive     Wrapper
boolean       java.lang.Boolean
byte       java.lang.Byte
char       java.lang.Character
double       java.lang.Double
float       java.lang.Float
int       java.lang.Integer
long       java.lang.Long
short       java.lang.Short
void       java.lang.Void
——-collections——
17)What is Java Collections API?
Java Collections framework API is a unified architecture for representing and
manipulating collections. The API contains Interfaces, Implementations &
Algorithm to help java programmer in everyday programming. In nutshell, this
API does 6 things at high level
Reduces programming efforts. – Increases program speed and quality.
Allows interoperability among unrelated APIs.
Reduces effort to learn and to use new APIs.
Reduces effort to design new APIs.
Encourages & Fosters software reuse.
To be specific, There are six collection java interfaces. The most basic
interface is Collection. Three interfaces extend Collection: Set, List, and
SortedSet. The other two collection interfaces, Map and SortedMap, do not
extend Collection, as they represent mappings rather than true collections.
18)What is an Iterator?
Some of the collection classes provide traversal of their contents via a
java.util.Iterator interface. This interface allows you to walk through a
collection of objects, operating on each object in turn. Remember when using
Iterators that they contain a snapshot of the collection at the time the
Iterator was obtained; generally it is not advisable to modify the collection
itself while traversing an Iterator.
19)What is the difference between java.util.Iterator and
java.util.ListIterator?
Iterator : Enables you to traverse through a collection in the forward
direction only, for obtaining or removing elements ListIterator : extends
Iterator, and allows bidirectional traversal of list and also allows the
modification of elements.
20)What is HashMap and Map?
Map is Interface which is part of Java collections framework. This is to store
Key Value pair, and Hashmap is class that implements that using hashing
technique.
21)Difference between HashMap and HashTable? Compare Hashtable vs HashMap?
Both Hashtable & HashMap provide key-value access to data. The Hashtable is one
of the original collection classes in Java (also called as legacy classes).
HashMap is part of the new Collections Framework, added with Java 2, v1.2.
There are several differences between HashMap and Hashtable in Java as listed
below
The HashMap class is roughly equivalent to Hashtable, except that it is
unsynchronized and permits nulls. (HashMap allows null values as key and value
whereas Hashtable doesn’t allow nulls).
HashMap does not guarantee that the order of the map will remain constant
over time. But one of HashMap’s subclasses is LinkedHashMap, so in the event
that you’d want predictable iteration order (which is insertion order by
default), you can easily swap out the HashMap for a LinkedHashMap. This
wouldn’t be as easy if you were using Hashtable.
HashMap is non synchronized whereas Hashtable is synchronized.
Iterator in the HashMap is fail-fast while the enumerator for the Hashtable
isn’t. So this could be a design consideration.
22)What does synchronized means in Hashtable context?
Synchronized means only one thread can modify a hash table at one point of
time. Any thread before performing an update on a hashtable will have to
acquire a lock on the object while others will wait for lock to be released.
33)How can we make Hashmap synchronized?
HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);
34)Where will you use Hashtable and where will you use HashMap?
There are multiple aspects to this decision: 1. The basic difference between a
Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is
not. Thus whenever there is a possibility of multiple threads accessing the
same instance, one should use Hashtable. While if not multiple threads are
going to access the same instance then use HashMap. Non synchronized data
structure will give better performance than the synchronized one. 2. If there
is a possibility in future that – there can be a scenario when you may require
to retain the order of objects in the Collection with key-value pair then
HashMap can be a good choice. As one of HashMap’s subclasses is LinkedHashMap,
so in the event that you’d want predictable iteration order (which is insertion
order by default), you can easily swap out the HashMap for a LinkedHashMap.
This wouldn’t be as easy if you were using Hashtable. Also if you have multiple
thread accessing you HashMap then Collections.synchronizedMap() method can be
leveraged. Overall HashMap gives you more flexibility in terms of possible
future changes.
35)Difference between Vector and ArrayList? What is the Vector class?
Vector & ArrayList both classes are implemented using dynamically resizable
arrays, providing fast random access and fast traversal. ArrayList and Vector
class both implement the List interface. Both the classes are member of Java
collection framework, therefore from an API perspective, these two classes are
very similar. However, there are still some major differences between the two.
Below are some key differences
Vector is a legacy class which has been retrofitted to implement the List
interface since Java 2 platform v1.2
Vector is synchronized whereas ArrayList is not. Even though Vector class
is synchronized, still when you want programs to run in multithreading
environment using ArrayList with Collections.synchronizedList() is recommended
over Vector.
ArrayList has no default size while vector has a default size of 10.
The Enumerations returned by Vector’s elements method are not fail-fast.
Whereas ArraayList does not have any method returning Enumerations.
36)What is the Difference between Enumeration and Iterator interface?
Enumeration and Iterator are the interface available in java.util package. The
functionality of Enumeration interface is duplicated by the Iterator interface.
New implementations should consider using Iterator in preference to
Enumeration. Iterators differ from enumerations in following ways:
Enumeration contains 2 methods namely hasMoreElements() & nextElement()
whereas Iterator contains three methods namely hasNext(), next(),remove().
Iterator adds an optional remove operation, and has shorter method names.
Using remove() we can delete the objects but Enumeration interface does not
support this feature.
Enumeration interface is used by legacy classes. Vector.elements() &
Hashtable.elements() method returns Enumeration. Iterator is returned by all
Java Collections Framework classes. java.util.Collection.iterator() method
returns an instance of Iterator.
37)Why Java Vector class is considered obsolete or unofficially deprecated? or
Why should I always use ArrayList over Vector?
You should use ArrayList over Vector because you should default to non-
synchronized access. Vector synchronizes each individual method. That’s almost
never what you want to do. Generally you want to synchronize a whole sequence
of operations. Synchronizing individual operations is both less safe (if you
iterate over a Vector, for instance, you still need to take out a lock to avoid
anyone else changing the collection at the same time) but also slower (why take
out a lock repeatedly when once will be enough)?
Of course, it also has the overhead of locking even when you don’t need to.
It’s a very flawed approach to have synchronized access as default. You can
always decorate a collection using Collections.synchronizedList – the fact that
Vector combines both the “resized array” collection implementation with the
“synchronize every operation” bit is another example of poor design; the
decoration approach gives cleaner separation of concerns.
Vector also has a few legacy methods around enumeration and element retrieval
which are different than the List interface, and developers (especially those
who learned Java before 1.2) can tend to use them if they are in the code.
Although Enumerations are faster, they don’t check if the collection was
modified during iteration, which can cause issues, and given that Vector might
be chosen for its syncronization – with the attendant access from multiple
threads, this makes it a particularly pernicious problem. Usage of these
methods also couples a lot of code to Vector, such that it won’t be easy to
replace it with a different List implementation.
Despite all above reasons Sun may never officially deprecate Vector class.
38)What is an enumeration?
An enumeration is an interface containing methods for accessing the underlying
data structure from which the enumeration is obtained. It is a construct which
collection classes return when you request a collection of all the objects
stored in the collection. It allows sequential access to all the elements
stored in the collection.
39)What is the difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator
interface. Iterator has a remove() method while Enumeration doesn’t.
Enumeration acts as Read-only interface, because it has the methods only to
traverse and fetch the objects, where as using Iterator we can manipulate the
objects also like adding and removing the objects. So Enumeration is used when
ever we want to make Collection objects as Read-only.
40)Where will you use Vector and where will you use ArrayList?
The basic difference between a Vector and an ArrayList is that, vector is
synchronized while ArrayList is not. Thus whenever there is a possibility of
multiple threads accessing the same instance, one should use Vector. While if
not multiple threads are going to access the same instance then use ArrayList.
Non synchronized data structure will give better performance than the
synchronized one.
41)What is the importance of hashCode() and equals() methods? How they are used
in Java?
The java.lang.Object has two methods defined in it. They are – public boolean
equals(Object obj) public int hashCode(). These two methods are used heavily
when objects are stored in collections.
There is a contract between these two methods which should be kept in mind
while overriding any of these methods.
The Java API documentation describes it in detail. The hashCode() method
returns a hash code value for the object. This method is supported for the
benefit of hashtables such as those provided by java.util.Hashtable or
java.util.HashMap. The general contract of hashCode is:
Whenever it is invoked on the same object more than once during an execution of
a Java application, the hashCode method must consistently return the same
integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application. If two objects are
equal according to the equals(Object) method, then calling the hashCode method
on each of the two objects must produce the same integer result. It is not
required that if two objects are unequal according to the equals
(java.lang.Object) method, then calling the hashCode method on each of the two
objects must produce distinct integer results. However, the programmer should
be aware that producing distinct integer results for unequal objects may
improve the performance of hashtables. As much as is reasonably practical, the
hashCode method defined by class Object does return distinct integers for
distinct objects. The equals(Object obj) method indicates whether some other
object is “equal to” this one. The equals method implements an equivalence
relation on non-null object references:
It is reflexive: for any non-null reference value x, x.equals(x) should return
true.
It is symmetric: for any non-null reference values x and y, x.equals(y) should
return true if and only if y.equals(x) returns true.
It is transitive: for any non-null reference values x, y, and z, if x.equals(y)
returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any non-null reference values x and y, multiple
invocations of x.equals(y) consistently return true or consistently return
false, provided no information used in equals comparisons on the objects is
modified. For any non-null reference value x, x.equals(null) should return
false. The equals method for class Object implements the most discriminating
possible equivalence relation on objects; that is, for any non-null reference
values x and y, this method returns true if and only if x and y refer to the
same object (x == y has the value true).
Note that it is generally necessary to override the hashCode method whenever
this method is overridden, so as to maintain the general contract for the
hashCode method, which states that equal objects must have equal hash codes.
A practical Example of hashcode() & equals(): This can be applied to classes
that need to be stored in Set collections. Sets use equals() to enforce non-
duplicates, and HashSet uses hashCode() as a first-cut test for equality.
Technically hashCode() isn’t necessary then since equals() will always be used
in the end, but providing a meaningful hashCode() will improve performance for
very large sets or objects that take a long time to compare using equals().
42)What is the difference between Sorting performance of Arrays.sort() vs
Collections.sort() ? Which one is faster? Which one to use and when?
Many developers are concerned about the performance difference between
java.util.Array.sort() java.util.Collections.sort() methods. Both methods have
same algorithm the only difference is type of input to them. Collections.sort()
has a input as List so it does a translation of List to array and vice versa
which is an additional step while sorting. So this should be used when you are
trying to sort a list. Arrays.sort is for arrays so the sorting is done
directly on the array. So clearly it should be used when you have a array
available with you and you want to sort it.
43)Set & List interface extend Collection, so Why doesn’t Map interface extend
Collection?
Though the Map interface is part of collections framework, it does not extend
collection interface. This is by design, and the answer to this questions is
best described in Sun’s FAQ Page: This was by design. We feel that mappings are
not collections and collections are not mappings. Thus, it makes little sense
for Map to extend the Collection interface (or vice versa). If a Map is a
Collection, what are the elements? The only reasonable answer is “Key-value
pairs”, but this provides a very limited (and not particularly useful) Map
abstraction. You can’t ask what value a given key maps to, nor can you delete
the entry for a given key without knowing what value it maps to. Collection
could be made to extend Map, but this raises the question: what are the keys?
There’s no really satisfactory answer, and forcing one leads to an unnatural
interface. Maps can be viewed as Collections (of keys, values, or pairs), and
this fact is reflected in the three “Collection view operations” on Maps
(keySet, entrySet, and values). While it is, in principle, possible to view a
List as a Map mapping indices to elements, this has the nasty property that
deleting an element from the List changes the Key associated with every element
before the deleted element. That’s why we don’t have a map view operation on
Lists.
44)Which implementation of the List interface provides for the fastest
insertion of a new element into the middle of the list?
a. Vector b. ArrayList c. LinkedList ArrayList and Vector both use an array to
store the elements of the list. When an element is inserted into the middle of
the list the elements that follow the insertion point must be shifted to make
room for the new element. The LinkedList is implemented using a doubly linked
list; an insertion requires only the updating of the links at the point of
insertion. Therefore, the LinkedList allows for fast insertions and deletions.
45)What is the difference between ArrayList and LinkedList? (ArrayList vs
LinkedList.)
java.util.ArrayList and java.util.LinkedList are two Collections classes used
for storing lists of object references Here are some key differences:
ArrayList uses primitive object array for storing objects whereas
LinkedList is made up of a chain of nodes. Each node stores an element and the
pointer to the next node. A singly linked list only has pointers to next. A
doubly linked list has a pointer to the next and the previous element. This
makes walking the list backward easier.
ArrayList implements the RandomAccess interface, and LinkedList does not.
The commonly used ArrayList implementation uses primitive Object array for
internal storage. Therefore an ArrayList is much faster than a LinkedList for
random access, that is, when accessing arbitrary list elements using the get
method. Note that the get method is implemented for LinkedLists, but it
requires a sequential scan from the front or back of the list. This scan is
very slow. For a LinkedList, there’s no fast way to access the Nth element of
the list.
Adding and deleting at the start and middle of the ArrayList is slow,
because all the later elements have to be copied forward or backward. (Using
System.arrayCopy()) Whereas Linked lists are faster for inserts and deletes
anywhere in the list, since all you do is update a few next and previous
pointers of a node.
Each element of a linked list (especially a doubly linked list) uses a bit
more memory than its equivalent in array list, due to the need for next and
previous pointers.
ArrayList may also have a performance issue when the internal array fills
up. The arrayList has to create a new array and copy all the elements there.
The ArrayList has a growth algorithm of (n*3)/2+1, meaning that each time the
buffer is too small it will create a new one of size (n*3)/2+1 where n is the
number of elements of the current buffer. Hence if we can guess the number of
elements that we are going to have, then it makes sense to create a arraylist
with that capacity during object creation (using construtor new ArrayList
(capacity)). Whereas LinkedLists should not have such capacity issues.
46)Where will you use ArrayList and Where will you use LinkedList? Or Which one
to use when (ArrayList / LinkedList).
Below is a snippet from SUN’s site. The Java SDK contains 2 implementations of
the List interface – ArrayList and LinkedList. If you frequently add elements
to the beginning of the List or iterate over the List to delete elements from
its interior, you should consider using LinkedList. These operations require
constant-time in a LinkedList and linear-time in an ArrayList. But you pay a
big price in performance. Positional access requires linear-time in a
LinkedList and constant-time in an ArrayList.
47)What is performance of various Java collection implementations/algorithms?
What is Big ‘O’ notation for each of them ?
Each java collection implementation class have different performance for
different methods, which makes them suitable for different programming needs.
Performance of Map interface implementations
Hashtable
An instance of Hashtable has two parameters that affect its performance:
initial capacity and load factor. The capacity is the number of buckets in the
hash table, and the initial capacity is simply the capacity at the time the
hash table is created. Note that the hash table is open: in the case of a “hash
collision”, a single bucket stores multiple entries, which must be searched
sequentially. The load factor is a measure of how full the hash table is
allowed to get before its capacity is automatically increased. The initial
capacity and load factor parameters are merely hints to the implementation. The
exact details as to when and whether the rehash method is invoked are
implementation-dependent.
HashMap
This implementation provides constant-time [ Big O Notation is O(1) ]
performance for the basic operations (get and put), assuming the hash function
disperses the elements properly among the buckets.
Iteration over collection views requires time proportional to the
“capacity” of the HashMap instance (the number of buckets) plus its size (the
number of key-value mappings). Thus, it’s very important not to set the initial
capacity too high (or the load factor too low) if iteration performance is
important.
TreeMap
The TreeMap implementation provides guaranteed log(n) [ Big O Notation is
O(log N) ] time cost for the containsKey, get, put and remove operations.
LinkedHashMap
A linked hash map has two parameters that affect its performance: initial
capacity and load factor. They are defined precisely as for HashMap. Note,
however, that the penalty for choosing an excessively high value for initial
capacity is less severe for this class than for HashMap, as iteration times for
this class are unaffected by capacity.
Performance of Set interface implementations
HashSet
The HashSet class offers constant-time [ Big O Notation is O(1) ]
performance for the basic operations (add, remove, contains and size), assuming
the hash function disperses the elements properly among the buckets. Iterating
over this set requires time proportional to the sum of the HashSet instance’s
size (the number of elements) plus the “capacity” of the backing HashMap
instance (the number of buckets). Thus, it’s very important not to set the
initial capacity too high (or the load factor too low) if iteration performance
is important.
TreeSet
The TreeSet implementation provides guaranteed log(n) time cost for the
basic operations (add, remove and contains).
LinkedHashSet
A linked hash set has two parameters that affect its performance: initial
capacity and load factor. They are defined precisely as for HashSet. Note,
however, that the penalty for choosing an excessively high value for initial
capacity is less severe for this class than for HashSet, as iteration times for
this class are unaffected by capacity.
Performance of List interface implementations
LinkedList
- Performance of get and remove methods is linear time [ Big O Notation is
O(n) ] – Performance of add and Iterator.remove methods is constant-time [ Big
O Notation is O(1) ]
ArrayList
- The size, isEmpty, get, set, iterator, and listIterator operations run in
constant time. [ Big O Notation is O(1) ]
- The add operation runs in amortized constant time [ Big O Notation is O
(1) ] , but in worst case (since the array must be resized and copied) adding n
elements requires linear time [ Big O Notation is O(n) ]
- Performance of remove method is linear time [ Big O Notation is O(n) ]
- All of the other operations run in linear time [ Big O Notation is O(n)
]. The constant factor is low compared to that for the LinkedList
implementation.

Comments

  1. Very well answered and useful questions. Thanks a lot!

    ReplyDelete
  2. Thanks for your valuable comment....

    ReplyDelete
  3. All the posts in your blog are undeniably great. The best part is you are providing solutions too.
    Thank You very much and should be really appreciated.

    ReplyDelete

Post a Comment

Please post comments here:-)

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams

Android Interview questions