|
|
JAVA Interview Questions 21 - 25
|
Back to the list of all Java Interview Questions
|
|
Question 21: When is a method said to be overloaded and when is a method said to be overridden?
|
|
Method Overloading
|
Method Overriding
|
|
Overloading deals with multiple methods in the same class
with the same name but different method signatures.
|
Overriding deals with two methods, one in the parent class and
the other one in the child class and has the same name and
signatures.
|
|
class
MyClass
{
public
void getInvestAmount(int
rate)
{
}
public
void getInvestAmount(int
rate, long principal)
{
}
} |
class
BaseClass
{
public
void getInvestAmount(int
rate)
{
}
}
class
MyClass extends BaseClass
{
public
void getInvestAmount(int
rate)
{
}
} |
|
Both the above methods have the same method names
but different method signatures, which mean the methods
are overloaded.
|
Both the above methods have the same method names and
the signatures but the method in the subclass MyClass
overrides the method in the superclass BaseClass.
|
|
Overloading lets you define the same operation in
different ways for different data.
|
Overriding lets you define the same operation in different
ways for different object types.
|
|
|
Question 22: What is the main difference between an ArrayList and a Vector? What is the main difference between HashMap
and Hashtable? What is the difference between a stack and a queue?
|
|
Vector/Hashtable
|
ArrayList/HashMap
|
|
Original classes before the introduction of Collections
API. Vector & Hashtable are synchronized. Any
method that touches their contents is thread-safe.
|
So if you don’t need a thread safe collection, use the ArrayList or
HashMap. Why pay the price of synchronization unnecessarily at
the expense of performance degradation.
|
So which is better?
As a general rule, prefer ArrayList/HashMap to Vector/Hashtable. If your application is a
multithreaded application and at least one of the threads either adds or deletes an entry into the collection
then use new Java collections API‘s external synchronization facility as shown below to temporarily synchronize
your collections as needed.
|
|
Map myMap
= Collections.synchronizedMap (myMap);
// single lock for the entire map
List myList = Collections.synchronizedList (myList); // single lock for the entire list |
J2SE 5.0: If you are using J2SE5, you should use the new “java.util.concurrent” package for improved
performance because the concurrent package collections are not governed by a single synchronized lock as
shown above. The “java.util.concurrent” package collections like ConcurrentHashMap is threadsafe and at the
same time safely permits any number of concurrent reads as well as tunable number of concurrent writes. The
“java.util.concurrent” package also provides an efficient scalable thread-safe non-blocking FIFO queue like
ConcurrentLinkedQueue.
J2SE 5.0: The “java.util.concurrent” package also has classes like CopyOnWriteArrayList, CopyOnWrite-
ArraySet, which gives you thread safety with the added benefit of immutability to deal with data that changes
infrequently. The CopyOnWriteArrayList behaves much like the ArrayList class, except that when the list is
modified, instead of modifying the underlying array, a new array is created and the old array is discarded. This
means that when a caller gets an iterator (i.e. copyOnWriteArrayListRef.iterator() ), which internally
holds a reference to the underlying CopyOnWriteArrayList object’s array, which is immutable and therefore can be
used for traversal without requiring either synchronization on the list copyOnWriteArrayListRef or need to
clone() the copyOnWriteArrayListRef list before traversal (i.e. there is no risk of concurrent modification) and
also offers better performance.
|
|
Array
|
List / Stack etc
|
|
Java arrays are even faster than using an ArrayList/Vector
and perhaps therefore may be preferable if you know the
size of your array upfront (because arrays cannot grow
as Lists do).
|
ArrayList/Vector are specialized data structures that internally
uses an array with some convenient methods like add(..),
remove(…) etc so that they can grow and shrink from their initial
size. ArrayList also supports index based searches with
indexOf(Object obj) and lastIndexOf(Object obj) methods.
|
|
In an array, any item can be accessed.
|
These are more abstract than arrays and access is restricted.
For example, a stack allows access to only last item inserted.
|
|
Queue (added in J2SE 5.0)
|
Stack
|
|
First item to be inserted is the first one to be removed.
|
Allows access to only last item inserted.
|
|
This mechanism is called First In First Out (FIFO).
|
An item is inserted or removed from one end called the “top” of
the stack. This is called Last In First Out (LIFO) mechanism.
|
Placing an item in the queue is called “enqueue or
insertion” and removing an item from a queue is called
“dequeue or deletion”. Pre J2SE 5.0, you should write your
own Queue class with enqueue() and dequeue() methods
using an ArrayList or a LinkedList class.
J2SE 5.0 has a java.util.Queue<E> interface.
|
Placing the data at the top is called “pushing” and removing an
item from the top is called “popping”. If you want to reverse
“XYZ” ?? ZYX, then you can use a java.util.Stack
|
|
|
Question 23: What is the main difference between a String and a StringBuffer class?
|
|
String
|
StringBuffer/StringBuilder (added in J2SE 5.0)
|
|
String is immutable: you can’t modify a string
object but can replace it by creating a new
instance. Creating a new instance is rather
expensive.
|
StringBuffer is mutable: use StringBuffer or StringBuilder when you want to modify
the contents. StringBuilder was added in Java 5 and it is identical in all respects
to StringBuffer except that it is not synchronized, which makes it slightly faster
at the cost of not being thread-safe. |
|
//Inefficient version using immutable String
String
output = “Some text”
Int count
= 100;
for(int i =0; i<count; i++)
{
output += i;
}
return
output; |
//More efficient version using mutable StringBuffer
StringBuffer
output = new StringBuffer(110);//
set an initial size of 110
output.append(“Some
text”);
for(int i =0; i<count; i++)
{
output.append(i);
}
return
output.toString(); |
|
The above code would build 99 new String
objects, of which 98 would be thrown away
immediately. Creating new objects is not
efficient.
|
The above code creates only two new objects, the StringBuffer and the
final String that is returned. StringBuffer expands as needed, which is
costly however, so it would be better to initialize the StringBuffer with the
correct size from the start as shown. |
|
Another important point is that creation of extra strings is not limited to overloaded mathematical operator “+” but
there are several methods like concat(), trim(), substring(), and replace() in String classes that generate new
string instances. So use StringBuffer or StringBuilder for computation intensive operations, which offer better
performance.
|
|
|
Question 24: What is an immutable object?
|
Immutable objects whose state (i.e. the object’s data) does not change once it is
instantiated (i.e. it becomes a read-only object after instantiation). Immutable classes are ideal for representing
numbers (e.g. java.lang.Integer, java.lang.Float, java.lang.BigDecimal etc are immutable objects), enumerated
types, colors (e.g. java.awt.Color is an immutable object), short lived objects like events, messages etc.
|
|
Question 25: What are the benefits of immutable objects?
|
- Immutable classes can greatly simplify programming by freely allowing you to cache and share the references to
the immutable objects without having to defensively copy them or without having to worry about their values
becoming stale or corrupted.
- Immutable classes are inherently thread-safe and you do not have to synchronize access to them to be used in a
multi-threaded environment. So there is no chance of negative performance consequences.
-
Eliminates the possibility of data becoming inaccessible when used as keys in HashMaps or as elements in
Sets. These types of errors are hard to debug and fix.
|
Back to the list of all Java Interview Questions
|
|
|