You are on page 1of 55

Page 42

Page - 55

Core Java
OOPs Concept:

Object-Oriented Programming (OOP) is a methodology or paradigm (describes distinct


concepts or thought patterns) using "objects" and class to design program/applications.

Object: An object is a real world entity (pen, chair) which having its own state and
behavior. State of an object is the current data and behavior is implemented as methods.

Ex: - A car has some properties like model, fuel type etc which are the state (or properties)
of that object.
Within banking system, Customer is an object which participates in day to day activity.

Class:

A class is a group of objects that have common property. It is a template or blueprint from
which objects are created.

A class in java contains:

Data member
Methods
Constructor
Block

1: Inheritance:

Inheritance: It is a mechanism in which one object acquires the properties and behavior
of its parents objects which are accessible only.
It represents IS-A relationship.

USE:
1: For Method Overriding (Run Time polymorphism).
2: For code Reusability.

Keyword: extends

Example: Employee programmer (IS-A relationship means programmer is a type of


Employee)
Why multiple inheritance not supported by Java?

To reduce the complexity and simplify the language.

Types of Inheritance:

Notes:

When we create Object of subclass then its constructor first calls its super class
constructor.
Private member or methods not acquired by its subclass. And also we cannot override
private/final methods.

2: Encapsulation: (Data hiding and prevent from other user)

Encapsulation is a process of wrapping code and data together in a single unit. It is way to
achieve data hiding.
It can be achieved by using access modifier private, protected and public.

Example: We saw our computer CPU box daily but we cant saw the internal things of that
box because our CPU box wraps the functionality of CPU.
As Code POJO class is an example.
BorderFactory class is a good example of Encapsulation, which encapsulate creation logic of
Border.

Advantage:

1. More flexible and easy to change with new requirements.


2. Makes unit testing easy.
3. Allows you to control who can access what.
4. Helps to write immutable class in Java which is a good choice in multi- threading
environment.
5. Encapsulation reduce coupling of modules and increase cohesion inside a module
because
all piece of one thing are encapsulated in one place.
6. Encapsulation allows you to change one part of code without affecting other part of code.

Design Pattern based on Encapsulation in Java:

1: Factory Pattern: Is used to create object better than creating object using new
operator.

2: Singleton pattern:

Use:

1: Used to design loose coupling and high cohesion of code.


2: Allows you to control who can access what.

3: Abstraction (Hiding implementation)

Abstraction is a process of hiding the implementation details and showing the required
functionality to the user.

It helps to reduce the complexity and also improves the maintainability of the system.

Way to Achieve:

1: Abstract class
2: Interface
Example:

Real life example is mobile.


We are using its function like receiving a call, making calls and listening music but we don't
know how they implemented.

Code:

abstract class Car


{
public abstract void ignition();
}

class Mazda extends Car


{
public void ignition(){
System.out.println("Code for starts Mazda engine");
}
}

class Audi extends Car


{
public void ignition(){
System.out.println("Code for starts Audi engine");
}
}

public class Test


{
public static void main(String[] args)
{
Car car = new Mazda();
car.ignition();

car = new Audi ();


car.ignition();
}
}

So you have a Car object but it can hold objects from Mazda or Audi and it can call the
appropriate ignition method. The Car object does not know anything about the
implementations of this method it just know that it can call it.
4: Polymorphism: (One interface act as different in different class)

Polymorphism is an Oops concept which advice use of common interface instead of doing
concrete implementation while writing code.

The word polymorphism literally means a state of having many shapes or the capacity to
take on different forms

Polymorphism in Java has two types:

1: Compile time polymorphism/ static polymorphism (static binding) Example:


Overloading

2: Runtime polymorphism/ dynamic polymorphism (dynamic binding). Example:


Overriding

Static polymorphism /Overloading: (Change in parameter passed)

In Overloading, parameter types/order/number of parameters must be different.


At compile time, Java knows which method to invoke by checking the method
signatures. So, this is called compile time polymorphism or static binding.
Constructor can be overloaded with in same class only but not override.
Constructor method doesn't specify a return type, they return instance of class itself.

Dynamic Polymorphism/ Overriding:

The method to call is determined at runtime; this is called dynamic binding or late
binding.

1: Overriding method MUST have the same argument list (if not, it might be a case of
overloading).
2: Overriding method MUST have the same return type; the exception is covariant return
(used
as of Java 5).
3: Overriding method MUST NOT have more restrictive access modifier, but MAY have less

restrictive one.
4: Abstract methods MUST be overridden.
5: Final methods CANNOT be overridden.
6: Static methods CANNOT be overridden.
7: Constructors CANNOT be overridden.
8: Private methods CANNOT be overridden.

Notes:

If the reference type is a class, the object it refers to MUST be either that same type or a subclass of that
type.
If the reference type is an INTERFACE, the object it refers to MUST be an object from a class
which implements the interface.
An object in Java that passes more than one IS-A tests is polymorphic in nature
Every object in Java passes a minimum of two IS-A tests: one for itself and one for Object class

Coupling vs Cohesion:

Coupling is the degree to which one class knows about another class. Loose coupling is a
good programming strategy.

Cohesion: The term cohesion is used to indicate the degree to which a class has a single,
well-focused purpose. The more focused a class is, the higher its cohesiveness.

Benefits:

The key benefit of high cohesion is that such classes are typically much easier to maintain
than classes with low cohesion. Another benefit of high cohesion is that classes with a well-
focused purpose tend to be more reusable than other classes.

Memory Allocation:

The JVM divided the memory into following sections.

1. Heap

2. Stack

3. Code

4. Static

This division of memory is required for its effective management.

The code section contains your bytecode.

The Stack section of memory contains methods, local variables and reference
variables.

The Heap section contains Objects (may also contain reference variables), arrays,
instance variable.

The Static section contains Static data/methods.

Abstract vs Interface:

Similarity between Abstract vs Interface:


1: Both cannot be instantiated.
2: All abstract methods of Abstract class and interface must be implemented in its
subclass.
Difference between Abstract vs Interface:
1: Abstract class needs to extends but interface needs to implements.
2: Multiple inheritance is possible using interface but not with abstract class.
3: It is practically not possible to add methods to an interface after it is released without
changing existing classes but you can add a concrete method to an abstract class without

breaking the existing classes.


4: With Abstract class we can minimize the accessibility of classes and members but in
interface
all of the classs methods from interface must be declared public.
5: Abstract class can have concrete methods but interface contains pure abstract methods.

Interface:
An interface is not a class. It is an entity that is defined by the word Interface. An interface
has no implementation; it only has the signature or in other words, just the definition of the
methods without the body

*A constructor cannot be abstract, static, final, native, or synchronized.

Collection: It is a collection of Object in a single unit. Each collection class implements


Cloneable and Serializable interface.
List Interface: [ArrayList, LinkedList, Vector]. Maintain insertion order and it is
Index Based

List interface is the sub interface of collection. It contains methods to insert and delete on
index basis.
1: ArrayList: [Maintain insertion order]

ArrayList is a dynamic array for storing elements. It extends AbstractList and implements
List interface.

1: Arraylist is growable by [(Old capacity * 3/2) +1].


2: Can contain duplicate element.
3: Maintain insertion order.
4: Not Synchronized.
5: Random access because array works at index basis.
6: Manipulation slow because lots of shifting needs to be occurred while delete, insert
operation.
7: You can add any no. of NULL.
8: Fetch elements easily as compared to linked list.

Iteration Ways:
1: By iterator interface [Only traverse in forward direction].
2: By for-each loop.
3: ListIterator [traverse in both directions, used for List only].
4: Enumeration: Used to traverse Vector/ Properties.
Has methods: boolean hasMoreElements( ), Object nextElement( )

Methods:
1: add()
2: addAll(Collection c)
3: retainAll()- it copies only common elements and delete others.
4: removeAll()- remove from first to all elements presents in second/ time complexity
o(n^2) because it work on two loops.
5: clear()- arraylist become blank and time complexity is O (n).

2: LinkedList: [Maintain insertion order]

It is a collection of Object, it extends AbstractList and Implements List and Deque interface.

1: Uses doubly linked list to store elements. It is node based; each node contains the
address of
its previous node, Data value and next node.
2: Can contain duplicate elements.
3: Maintain Insertion order.
4: Not synchronized
5: No random access.
6: Manipulation (insertion and deletion) fast, no need of shifting of elements.
7: Can be used as list, stack or queue.
8: Its first and last must be null.

3: Vector: [Maintain insertion order]

Vector implements a dynamic array. Its capacity is increase by [2 * old capacity].


It is similar to ArrayList, but with two differences:

Vector is synchronized.

Vector contains many legacy methods that are not part of the collections framework.

ArrayList and HashMap superseded Vector and HashTable but it is used to support old code
run.

Legacy Class:

The following are the legacy classes defined by java.util package

1. Dictionary [ Abstract Key value]

2. HashTable [class Key value]

3. Properties [Concrete class Key value]

4. Stack [Concrete class value]

5. Vector [Concrete class value]

There is only one legacy interface called Enumeration

NOTE: All the legacy classes are synchronized


Hashtable class:

Difference between HashMap and Hashtable


Hashtable HashMap

Hashtable class is synchronized. HastMap is not synchronize.

Because of Thread-safe, Hashtable is HashMap works faster


slower than HashMap.

Neither key nor values can be null One key and many values can be null

Order of table remain constant over time. does not guarantee that order of map remain
constant over time

Properties class

1. Properties class extends Hashtable class.

2. It is used to maintain list of value in which both key and value are String

3. Properties class define two constructor


Properties()
Properties(Properties default)

4. One advantage of Properties over Hashtable is that we can specify a default


property that will be useful when no value is associated with a certain key.

Dictionary HashTable Properties

SET: [HashSet, LinkedHashSet, TreeSet] (Unordered, Unique Elements)

Set contain unique elements, when we add duplicate it will not throw any exception, only
returns false on add of elements.
It contains unique elements, due to override of hashcode () and equals () method in
AbstractSet class. Before addition of elements it check that the elements is present or not, if
presents then it prohibit to add.

1: HashSet: [Unordered, for fetch need to traverse]

HashSet extends AbstractSet and implements Set interface. It contains unique elements.
A HashSet is a collection set that neither allows duplicate elements nor order or position its
elements. It creates a collection that uses a hash table for storage. Hash table stores
information by using a mechanism called hashing. The hash code is then used as an index
at which the data associated with the key is stored
AbstractCollection AbstractSet

Iterable Interface: Implementing this interface allows an object to be the target of the
"foreach" statement.

Methods: iterator()--Returns an iterator over a set of elements.


Implementing this interface allows an object to be the target of the "foreach"
statement.

HASHSET: Not index based means for fetching elements we need to traverse from start.

1: Unordered
2: Non-synchronized
3: Allowed null values.
4: Unique elements
5: Performance is higher than LinkedHashSet and Tree set
6: Fetch elements using iterator/foreach loop.
7: No guarantee of Iteration order.

No get (Index) method in set interface.

Constructor:
HashSet( )
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)

Hash Map or Hash Set we heard two parameters that is load factor and initial
capacity.

Load Factor: Load factor is a measurement of how full hash table is allowed or number of
elements in the hash table. When the number of entries in the hash table exceeds the
product of LF and IC this all is performed by calling the rehash method and capacity will
increase by twice.

2: LinkedHashSet:[Store elements in insertion order because it implements Linked


List]

Contains unique elements and stored elements in insertion order and it extends hashSet
and implements set interface.
It maintains doubly linked list. And returns elements in insertion order.
Performance is like(add, remove, contains) to be same but Linked hash set slightly below
that of HashSet, due to the added expense of maintaining the linked list, with one exception.
A linked hash set has two parameters that affect its performance: initial capacity and load
factor.
Synchronized Linked hashset:
A LinkedHashSet requires time proportional to the size of the set, regardless of its capacity.

Set s = Collections.synchronizedSet(new LinkedHashSet(...));

1: Insertion Ordered
2: Non-synchronized
3: Allowed null values.
4: Unique elements
5: Performance is lower than HashSet but more efficient than Tree set(slower due to sorting
operation).
6: Fetch elements using iterator/foreach loop.
7: Guarantee of Iteration in insertion order.
8: Iteration more expensive if size is large.
Fail-Fast vs Fail-Safe:

Fail-Fast:
Fail-fast occurs when a structure of Collection is modified since Iteration has begun.
Structural modification of a collection includes adding, deleting, updating elements
of a collection. Fail-fast is identified internally using a modification count for the
collection and if the iterator realizes that the count is changed, it will thrown a
ConcurrentModificationException. except through the iterator's own remove method.

Fail-Safe:
Fail-safe are similar to fast-fail but they do not throw an Exception when Collection is
modified since they work on a clone of the collection. CopyOnWriteArrayList and
ConcurrentHashMap are fail-safe iterators which work on a copy of a collection for
modification.

NOTE Fail-safe iterators are too costly since a clone of a collection is created

3: TreeSet:
[Store elements in natural order because it implements NavigableSet interface
which implements SortedSet]

public class TreeSet<E>


extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable

Tree Set uses internally comparator for sorting.


This implementation provides guaranteed log(n) time cost for the basic operations (add,
remove and contains).

1: Ascending/natural Ordered
2: Non-synchronized
3: Allowed null values if only one element is there i.e. null otherwise compilation come.
4: Unique elements
5: Performance is slower than HashSet and LinkedHashSet due to sorting operation while
addition).
6: Fetch elements using iterator/foreach loop.
7: Guarantee of Iteration in natural order.
8: Iteration more expensive if size is large.

For synchronizing Tree Set use:

SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));


All elements inserted into the set must implement the Comparable interface.
Constructor:
public TreeSet(Comparator<? super E> comparator)
public TreeSet(Collection<? extends E> c)
public TreeSet(SortedSet<E> s)

Queue:
A Queue is a collection for holding elements prior to processing. Besides basic Collection
operations, queues provide additional insertion, removal, and inspection operations.
Queue is an interface basically orders the elements in FIFO.

Each Queue method exists in two forms:


(1) One throws an exception if the operation fails, and
(2) The other returns a special value if the operation fails (either null or false,
depending on the
operation).
(3): Queue implementations generally do not allow insertion of null elements because
when we fetch the element it will be very difficult to find Whether it return value or fetching
from Empty Queue.

Type of Throws exception/ Returns special value/ Exception Occured


Operation reason Return
add(e)Out of IllegalStateException
Insert capacity we add
offer(e) - false

remove()--Empty NoSuchElementException
Remove Queue
poll() - null

element()Empty NoSuchElementException
Examine Queue
peek() - null

In a FIFO queue, all new elements are inserted at the tail of the queue. It is possible for a
Queue implementation to restrict the number of elements that it holds; such queues are
known as bounded. If we add elements beyond its capacity then add method throws
Exception. It removes elements from peek.
The Deque Interface:
A Deque is a double-ended-queue. A double-ended-queue is a linear collection of elements
that supports the insertion and removal of elements at both end points.
Predefined classes like ArrayDeque and LinkedList implement the Deque interface.

Deque Methods
Type of First Element (Beginning of the Deque Last Element (End of the Deque
Operation instance) instance)
addFirst(e) addLast(e)
Insert offerFirst(e) offerLast(e)
removeFirst() removeLast()
Remove pollFirst() pollLast()
getFirst() getLast()
Examine peekFirst() peekLast()

Insert: When the capacity of the Deque instance is restricted, the preferred methods are
offerFirst and offerLast because addFirst might fail to throw an exception if it is full.
Deque is same as Queue but queue work on FIFO concept but Deque work on both
FIFO and LIFO.

PriorityQueue: An unbounded priority queue based on a priority heap. The elements of the
priority queue are ordered according to their natural ordering or by a Comparator provided at queue
construction time, depending on which constructor is used.

The head of this queue is the least element with respect to the specified ordering.
As elements are added to a priority queue, its capacity grows automatically

1: Not Synchronized.
2: Time complexity is O (log(n)).
3: Implements Queue.

Map:

The Map is an interface which describes a mapping from keys to values, without duplicate keys.
Each pair known as Map.Entry
Entry is sub interface of Map so we can access key value pair in Map.Entry.
A set of these map entries can be obtained by calling a map's entrySet ( ) method.
Iterating over a map is done by iterating over this set.

Two methods in Entry:-


1: public Object getKey()
2: public Object getValue()

Either a key or many values can be null.

Maps classes:
1: HashMap
2: HashTable
3: TreeMap
4: LinkedHashMap

1: HashMap: [Unordered, one null key]

HashMap Extends AbstractMap implements Map

The HashMap is a class which stored key-value pair and it is used to perform some basic
operations such as inserting, deleting, and locating elements in a Map.
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and
permits nulls.

1: It may have one Null Key and multiple null values.


2: It maintains NO Order.
3: When we add value on same key then value gets override no error occurred.
4: Unsynchronized.
5: Hashing technique used while adding elements.
6: Time complexity depends on capacity, so its very important not to set the intial capacity
too high (or the load
factor too low) if iteration performance is important.

Capacity = no. of buckets in the Hashtable


Load factor = How full the hash table is allowed to get before its capacity is automatically
increased

You can synchronize the map also:

Map m = Collections.synchronizedMap(new HashMap(...));

fail-fast: if the map is structurally modified at any time after the iterator is created, in any
way except through the iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException

2: LinkedHashMap: [one null key or many null Values, Insertion order]

Extends hashmap implements Map

A LinkedHashMap is implemented using both Hash table and linked list implementation of
the Map interface
It contains value based on key. It extends hashmap and implements Map. It
maintains a linked list of the entries in the map.

1: Elements retrieve in insertion- order.


2: It is non-synchronized.
3: One null key and many null values allowed.
4: If we insert null key again it override, no exception occur.

3: Hash Table: [No null key or Value, unordered]


A hashTable is an array of List, each list is known as a bucket. The position of bucket
is identified by calling hashcode() method.

Extends Dictionary implements Map

This class implements a hashtable, which maps keys to values. Any non-null object can be
used as a key or as a value. It uses hashCode() and equals() methods to retrieve and store
object in hashtable.
Its constructor can contain initial capacity and load factor. When the number of entries
in the hashtable exceeds the product of the load factor and the current capacity, the
capacity is increased by calling the rehash method.

Points:
1: It contains only unique key elements.
2: No null key or value allowed otherwise it will throw NullPointerException at
runtime.
3: It is synchronized.
Note: One bucket can store more than one key-value pair.

Ques: If two different objects have same HashCode, how


HashMap will retrieve these two objects?

ANS: It store both the Object at the same hashcode value, with in the same
bucket(as a linked list in single bucket), but while fetching it first find the
appropriate hashcode bucket and then comparing the key using equals method to
identify the exact key and then fetch the corresponding value.

4: TreeMap:[Natural/Sorted Order on key basis]

Implements- NavigableMap(extends SortedMap interface), Cloneable, Serializable


Extends- AbstractMap

Use: The TreeMap implementation is useful when you need to traverse the keys from a
collection in a sorted manner.

Sorted according to the natural order for the key's class (see Comparable), or by the
comparator provided at creation time, depending on which constructor is used.

Navigable Set:( Java 6):


The java.util.NavigableSet interface is a subtype of the java.util.SortedSet interface. It
behaves like a SortedSet with the exception you have navigation methods available in
addition to the sorting mechanisms of the SortedSet.

Actually Navigable Set provides some new methods to make it easy in operations in present
collection classes. ConcurrentSkipListSet is one of the class which implements
NavigableSet.
All Superinterfaces:

Collection<E>, Iterable<E>, Set<E>, SortedSet<E>

All Known Implementing Classes:

ConcurrentSkipListSet, TreeSet

extends SortedSet<E>

Methods:

1. descendingIterator() and descendingSet()

2. headSet(), tailSet() and subSet(): return sortedset.

3. ceiling(), floor(), higher() and lower()

4. pollFirst() and pollLast()

Points:

1: A NavigableSet may be accessed and traversed in either ascending or descending order.


2: This interface additionally defines methods pollFirst and pollLast that return and remove
the lowest and highest element, if one exists, else returning null.
3: Subsets of any NavigableSet must implement the NavigableSet interface.
4: Note that sorted sets of Comparable elements intrinsically do not permit null.

Problem with NavigableSet:


If we fetch/remove elements from this set than it returns value but if there is no value then
it returns null, but this interface do not permit null to remove this ambiguity.
If you add then it throw runtime exception- null pointer

NavigableMap (Java 6):

NavigableMap in Java 6 is an extension of SortedMap like TreeMap which provides convenient


navigation method like lowerKey, floorKey, ceilingKey and higherKey. NavigableMap is added
on Java 1.6 and along with these popular navigation method it also provide ways to create a Sub Map
from existing Map in Java

All Superinterfaces: Map<K,V>, SortedMap<K,V>

All Known Subinterfaces: ConcurrentNavigableMap<K,V>

All Known Implementing Classes: ConcurrentSkipListMap, TreeMap

Extends SortedMap
Methods:

Methods inherited from interface java.util.SortedMap

comparator, entrySet, firstKey, keySet, lastKey, values

Methods inherited from interface java.util.Map

clear, containsKey, containsValue, equals, get, hashCode, isEmpty, put, putAll,


remove, size

1: lowerEntry: Returns a key-value mapping associated with the greatest key


strictly less than the
given key, or null if there is no such key.

Throws:

ClassCastException - if the specified key cannot be compared with the keys currently
in the map

NullPointerException - if the specified key is null and this map does not permit null
keys.

2: lowerKey: Returns the greatest key strictly less than the given key, or null if
there is no such key.

3: floorEntry: Returns a key-value mapping associated with the greatest key less
than or equal to the
given key, or null if there is no such key.

4: floorKey: Returns the greatest key less than or equal to the given key, or null
if there is no such
key.

5: ceilingEntry: Returns a key-value mapping associated with the least key


greater than or equal to
the given key, or null if there is no such key.

6: ceilingKey: Returns the least key greater than or equal to the given key, or
null if there is no such
key.
7: higherEntry: Returns a key-value mapping associated with the least key strictly
greater than the
given key, or null if there is no such key.

8: higherKey: Returns the least key strictly greater than the given key, or null if
there is no such key.

9: firstEntry:
Returns a key-value mapping associated with the least key in this map, or null if the
map is empty.

10: lastEntry
Returns a key-value mapping associated with the greatest key in this map, or null if
the map is empty.

11: pollFirstEntry
Removes and returns a key-value mapping associated with the least key in this map,
or null if the map is empty.

12: pollLastEntry
Removes and returns a key-value mapping associated with the greatest key in this
map, or null if the map is empty.

13: descendingMap
a reverse order view of this map. If either map is modified while an iteration over a
collection view of either map is in progress (except through the iterator's own remove
operation), the results of the iteration are undefined.

14: navigableKeySet
Returns a NavigableSet view of the keys contained in this map. The set's iterator
returns the keys in ascending order. The set is backed by the map, so changes to the
map are reflected in the set, and vice-versa. If the map is modified while an iteration
over the set is in progress (except through the iterator's own remove operation), the
results of the iteration are undefined. The set supports element removal, which
removes the corresponding mapping from the map, via the Iterator.remove,
Set.remove, removeAll, retainAll, and clear operations. It does not support the add or
addAll operations.

15: descendingKeySet
NavigableSet<K> descendingKeySet()
Returns a reverse order NavigableSet view of the keys contained in this map. The
set's iterator returns the keys in descending order. The set is backed by the map, so
changes to the map are reflected in the set, and vice-versa. If the map is modified
while an iteration over the set is in progress (except through the iterator's own remove
operation), the results of the iteration are undefined. The set supports element
removal, which removes the corresponding mapping from the map, via the
Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not
support the add or addAll operations.
16: subMap
NavigableMap<K,V> subMap(K fromKey,
boolean fromInclusive,
K toKey,
boolean toInclusive)
Returns a view of the portion of this map whose keys range from fromKey to toKey. If
fromKey and toKey are equal, the returned map is empty unless fromExclusive and
toExclusive are both true..

The returned map will throw an IllegalArgumentException on an attempt to insert a key outside
of its range, or to construct a submap either of whose endpoints lie outside its range.

17: headMap
NavigableMap<K,V> headMap(K toKey,
boolean inclusive)
Returns a view of the portion of this map whose keys are less than (or equal to, if
inclusive is true) toKey.

The returned map will throw an IllegalArgumentException on an attempt to insert a key outside
its range.

18: tailMap
NavigableMap<K,V> tailMap(K fromKey,
boolean inclusive)
Returns a view of the portion of this map whose keys are greater than (or equal to, if
inclusive is true) fromKey. The returned map is backed by this map, so changes in the
returned map are reflected in this map, and vice-versa. The returned map supports all
optional map operations that this map supports.

The returned map will throw an IllegalArgumentException on an attempt to insert a key outside
its range.

19: subMap
SortedMap<K,V> subMap(K fromKey,
K toKey)
Returns a view of the portion of this map whose keys range from fromKey, inclusive, to
toKey, exclusive. (If fromKey and toKey are equal, the returned map is empty.) The
returned map is backed by this map, so changes in the returned map are reflected in
this map, and vice-versa. The returned map supports all optional map operations that
this map supports.

Equivalent to subMap(fromKey, true, toKey, false).

Specified by:

subMap in interface SortedMap<K,V>

20: headMap
SortedMap<K,V> headMap(K toKey)
Returns a view of the portion of this map whose keys are strictly less than toKey. The
returned map is backed by this map, so changes in the returned map are reflected in
this map, and vice-versa. The returned map supports all optional map operations that
this map supports.

The returned map will throw an IllegalArgumentException on an attempt to insert a key outside
its range.

Equivalent to headMap(toKey, false).

Specified by:

headMap in interface SortedMap<K,V>

21: tailMap
SortedMap<K,V> tailMap(K fromKey)
Returns a view of the portion of this map whose keys are greater than or equal to
fromKey. The returned map is backed by this map, so changes in the returned map are
reflected in this map, and vice-versa. The returned map supports all optional map
operations that this map supports.
The returned map will throw an IllegalArgumentException on an attempt to insert a
key outside its range.
Equivalent to tailMap(fromKey, true).

Time Complexity:
This implementation provides guaranteed log(n) time cost for the containsKey, get, put and
remove operations.

Map m = Collections.synchronizedMap(new TreeMap(...));

1: The ordering maintained by a sorted map.


2: Tree Map is not synchronized.
3: Sorting on the basis of comparator or comparable.
4: It cannot have null key but can have null value.

Note:

1: Time Complexity:

For()
{
For()
For() // two for loop inside n + n = 2n

} // one outer-> outer must be multiply 2n*n =2n^2 = O (2n^2) time complexity.

Collection.sort(arrayList):
ArrayList contains object must implements comparable/comparator, if not
implemented then it must be implement comparable/comparator explicitly.

Comparator vs Comparable:
1: Use comparable when we need to compare between same class, and Comparator
interface when we need to compare with two Object or two different classes Object.

2: Comparator interface need to implements compare() method and on Comparable


interface needs to implements compareTo() methods.

3: Both returns I > J=positive, i< j= negative, i=j Equals.

4: Comparable sort in natural order where Comparator sort in customized order (you can
sort in your
own ways).

5: If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while
Comparable interface compares "this" reference with the object specified.

* If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted
automatically by using Collections.sort(list, comparator) or Arrays.sort() method.

* If we require to sort on different parameter basis then choose Comparator interface. For example Employee can be sorted on
name, salary or department and clients needs an API to do that. Comparator implementation can sort out this problem.

Implementations:

class ComparableThing implements Comparable{


public String feature;// i know public var is bad...

public int compareTo(Object o){


//here this object of this class compares itself to object o
ComparableThing other = (ComparebleThing) o;
return feature.compareTo(other.feature);//so here this object
//is compare-d-To other object
}
}

class ThingComparator implements Comparator{


public int compare(Object thing1, Object thing2){
ComparableThing first = (ComparableThing) thing1;
ComparableThing second = (ComparableThing) thing2;
return first.feature.compareTo(second.feature);

// return first.isbn-second.isbn; For sorting in natural order


// return second.isbn- first.isbn; For sorting in reverse order

//here used compareTo of class String but important thing to remember is


that this class is not compared it even doesn't have any other
member except this method
}
You implements comparator/comparable in any class and while using
Collection.sort(list, newObject) pass Object for sorting.
String.equals(StringBuffer) returns false because StringBuffer does not override
equals method of Object class. But it is possible if you use
String.contentEquals(StringBuffer) returns true.

Equals Vs HashCode:
equals() method is used to compare Objects for equality while hashCode is used to
generate an integer code corresponding to that object. They are used while inserting
and retrieving Object in HashMap, hashset. String, Integer already overrides equals
methods.

hashCode(): (First check address through hashcode on comparison of two Objects


that the object present or not if yes then call equal method):

It provides the hashcode of an Object. The default implementation of hashCode()


provided by Object is derived by mapping the memory address to an integer value.
public native int hashCode();

Equals(): (Then verify equals methods)

In Object class the equals methods is implemented as:

public boolean equals(Object obj) {


return (this == obj);
}

To find the actual hash Code of any Object:

Emp emp1 = new Emp(23);


int originalHashCode = System.identityHashCode(emp1);

Why do we need to implements hashcode() and equals() methods?

ANS: When we need to compare two Objects based on equals () methods, But we
need to override both methods not only hashcode ().

Example:
Case 1: You can override hashcode () your own ways:
public class Emp
{
private int age ;

public Emp( int age )


{
super();
this.age = age;
}

public int hashCode()


{
return age;
}

public boolean equals( Object obj )


{
boolean flag = false;
Emp emp = ( Emp )obj;
if( emp.age == age )
flag = true;
return flag;
}
}

Case2: if we want to store Object in HashSet and then find that object in set and
remove any particular
Object.
If we pass reference in comparison of objects then it will be compare easily but if we
pass Object(new EMP()) with same value for comparison then it needs to override
HashCode() and Equals() methods.

Example:
public class Emp1 {
private int age ;

public Emp1( int age )


{
super();
this.age = age;
}

public int hashCode()


{
return age;

}
public boolean equals( Object obj )
{
boolean flag = false;
Emp1 emp = ( Emp1 )obj;
if( emp.age== age )
flag = true;
return flag;
}
}

public class TestEmp1 {

public static void main(String[] args)


{
Emp1 emp1 = new Emp1(23);
Emp1 emp2 = new Emp1(24);
Emp1 emp3 = new Emp1(25);
Emp1 emp4 = new Emp1(26);
Emp1 emp5 = new Emp1(27);
HashSet<Emp1> hs = new HashSet<Emp1>();
hs.add(emp1);
hs.add(emp2);
hs.add(emp3);
hs.add(emp4);
hs.add(emp5);

System.out.println("HashSet Size--->>>"+hs.size());
System.out.println("hs.contains( new Emp1(25))--->>>"+hs.contains(new Emp1(25)));
System.out.println("hs.remove( new Emp1(24)--->>>"+hs.remove( new Emp1(24)));
System.out.println("Now HashSet Size--->>>"+hs.size());
}
}

O/P:
Contains and remove method return true if we implements hashcode and Equals
methods else return both false.

Case 3

In this case you want to use your object as key not the value in the HashMap. So you have to override
both the methods hashCode() and equals().

Immutable Object:

1: Are automatically thread-safe and have no synchronization issues.


2: Do not need a copy constructor
3: Do not need an implementation of clone
4: The best use of the immutable objects is as the keys of a map.

How to make class Immutable?

1. Create a final class.

2. Set the values of properties using constructor only.

3. Make the properties of the class final and private

4. Do not provide any setters for these properties.

5. If the instance fields include references to mutable objects, don't allow those objects
to be changed:

1. Don't provide methods that modify the mutable objects.


2. Don't share references to the mutable objects. Never store references to
external, mutable objects passed to the constructor; if necessary, create
copies, and store references to the copies. Similarly, create copies of your
internal mutable objects when necessary to avoid returning the originals in
your methods.

Array Vs Array List:

1: Array Stores primitive data types and also objects Vs ArrayList Stores only objects.
2: Fixed size Vs Growable and resizable. Elements can be added or removed.
3: Stores similar data of one type Vs Can store heterogeneous data types.
4: It is not a class (An array is a container object that holds a fixed number of values of a
single type. The length
of an array is established when the array is created. After creation, its length is fixed )
Vs
It is a class with many methods.
5: Cannot be synchronized Vs Can be obtained a synchronized version.
6: Elements retrieved with for loop Vs Can be retrieved with for loop and iterators.
7: Elements accessible with index number Vs Accessing methods like get() etc. are available.
8: Array can be multi-dimensional.

Method:

1: System.arraycopy( srs, index, destn, index, size);

2: java.util.Arrays.copyOfRange(copyFrom, 2, 9);

Array is a container but Arrays is a class which is used to perform actions on array.

Serial Version UID:


The serialVersionUID have to match during the serialization and deserialization
process. If it found different then it will throw InvalidClassException

3. Whats wrong with the default serialVersionUID?


If no serialVersionUID is declared, JVM will use its own algorithm to generate a
default SerialVersionUID.
The default serialVersionUID computation is highly sensitive to class
details and may vary from different JVM implementation, and result in an
unexpected InvalidClassExceptions during the deserialization process.

Ex: The client sends a serializable class with default generated serialVersionUID (e.g
123L) to the server over socket, the server may generate a different
serialVersionUID (e.g 124L) during deserialization process, It raises an unexpected
InvalidClassExceptions.

1: serialVersionUID is a static final field.


2: it contains Long value

Static Import: (Static Import is a new feature added in Java 5 specification):

In order to access static members, it is necessary to qualify references with the class they came from.

Ex- double r = Math.cos (Math.PI * theta);

But you can use directly without className through static import.

Ex-

import static java.lang.System.out;


import static java.lang.Math.PI;
import static java.lang.Math.cos;

// through import you can change above code as:

double r = cos (PI * theta);

The main advantage is that you can directly write the static method or member variable name/
Main advantage of using static import in Java is saving keystrokes.

LIMIT:

1: Ambiguous static import is not allowed. i.e. if you have imported java.lang.Math.PI and
you want to import mypackage.Someclass.PI, the compiler will throw an error.

2: You cannot do static import having same name, gives compiler Error Remove Unused
import

Note condition about Collection [Ordered/Unordered, synchronized/non-


synchronized, duplicates/Unique, Performance, internal implementation,
null allowed]

EXCEPTION:
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions.

When Occurred:
When an error occurs within a method, the method creates an object and hands it off to the
runtime system. The object, called an exception object, contains information about the
error, including its type and the state of the program when the error occurred.
When exception occurs then runtime system searches the top of the methods in call stack
(Methods calls) for a method that contains a block of code that can handle the exception.
This block of code is called an exception handler

Three Kinds of Exception:

1: Checked Exception: Checked Exceptions are those Exceptions which occur at compile
time. If Compiler doesnt
see try or catch block handling a Checked Exception, it throws
Compilation error.

Example: IOException, SQLException, DataAccessException, ClassNotFoundException,


InvocationTargetException

2: Unchecked Exception: Unchecked Exceptions are those exceptions which occurs at


runtime, These exceptions is occur due to programming bugs, such as logic errors or
improper use of an API.

Example: ArithematicException, NullPointerException, NumberFormatException,


ClassCastException,
ArrayIndexOutOfBoundException.

3: Error: Errors are exceptional conditions that are external to the application, and that the
application usually
cannot anticipate or recover from. It cannot be handled by program.

Example: OutOfMemoryError, AssertionError, VirtualMachineError.

** Errors and runtime exceptions are collectively known as unchecked exceptions.

Note: If the try block executes with no exceptions, the finally block is executed immediately
after the try block completes. It there was an exception thrown, the finally block executes
immediately after the proper catch block completes

** Pair of Blocks occurs as: try catch, try-catch-finally, try-finally


Catching More Than One Type of Exception with One Exception Handler:

In Java SE 7 and later, a single catch block can handle more than one type of exception. This
features removes Code duplication.

Ex- catch (IOException|SQLException ex) {


logger.log(ex);
throw ex;
}

Note: If a catch block handles more than one exception type, then the catch parameter is
implicitly final. In this example, the catch parameter ex is final and therefore you cannot
assign any values to it within the catch block.

1: try block:
This block contains code that might be able to throw an exception.
2: Catch Block
Catch block is an exception handler and handles the type of exception indicated by its
argument.
3: Finally block:
Finally block always executes whether exceptions occurs or not. Finally block may
return any value or
may throw new Exceptions. Finally block is used to clean up the used resources.

NOTE:
1: If the JVM exits/ thread executing the try or catch code is interrupted or killed, then
the finally block may
not execute.
2: If System.exit(0); is called then finally block do not get executed.

1. An exception arising in the finally block itself.

2. The death of the thread.

3. The use of System.exit()

4. Turning off the power to the CPU.

In JAVA 7:

The try-with-resources Statement:


The try-with-resources statement is a try statement that declares one or more resources. A
resource is an object that must be closed after the program is finished with it. The try-with-
resources statement ensures that each resource is closed at the end of the statement. Any
object that implements java.lang.AutoCloseable, which includes all objects which
implement java.io.Closeable, can be used as a resource.

Syntax:
try (Resource1 r; Resource2 r2 )
{
// resources get automatically closed after use
}

Ex-
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}

No need to closed br in finally block, It will be closed automatically whether the try
statement completes normally or abruptly.

You may declare one or more resources in a try-with-resources statement:

try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
)
{

Note:
1: Note that the close methods of resources are called in the opposite order of their
creation.
2: A try-with-resources statement can have catch and finally blocks just like an ordinary
try statement. In a
try-with-resources statement, any catch or finally block is run after the resources
declared have been
closed.

Suppressed Exceptions:

An exception can be thrown from the block of code associated with the try-with-resources
statement is called Suppressed Exception. You can retrieve these suppressed exceptions by
calling the Throwable.getSuppressed method from the exception thrown by the try block.

**Need To Implements AutoCloseable and Closeable interfaces for this features. The
Closeable interface extends the AutoCloseable interface. The close method of the Closeable
interface throws exceptions of type IOException while the close method of the
AutoCloseable interface throws exceptions of type Exception.

Throws clause:
When we are not sure that the methods at what lines may throw Exception then you
can define that exception at the methods level. It must be compile time Exception
Like IO, runtime is optional.
public void writeList() throws IOException, ArrayIndexOutOfBoundsException {

The throw Statement:

All methods use the throw statement to throw an exception.

Syntax: throw new EmptyStackException();

// Must be last statement in methods or block.

How to create your own Exception:

: By extending Exception class

Chained Exception:

When one Exception is cause to throw another Exception then this process is called
chained exception.

Try
{

}
catch (IOException e)
{
throw new SampleException("Other IOException", e);
}

Definition: A stack trace provides information on the execution history of the current
thread and lists the names of the classes and methods that were called at the point when
the exception occurred.

ACCESS:

catch (Exception cause)


{
StackTraceElement elements[] = cause.getStackTrace();

for (int i = 0, n = elements.length; i < n; i++)


{
System.err.println(elements[i].getFileName()
+ ":" + elements[i].getLineNumber()
+ ">> "
+ elements[i].getMethodName() + "()");
}
}
Advantages of Exceptions:
1: Separating Error-Handling Code from "Regular" Code:

2: Propagating Errors Up the Call Stack:


A second advantage of exceptions is the ability to propagate error reporting up the
call stack of methods.

3: Grouping and Differentiating Error Types:


Means Exception accept all time of exception occur where FileNotFoundException
accept only one time of exception

Custom Exception:
// Main class
public class MyOwnException {
public static void main(String[] a){
try{
MyOwnException.myTest(null);
} catch(MyAppException mae){
System.out.println("Inside catch block: "+mae.getMessage());
}
}

static void myTest(String str) throws MyAppException{


if(str == null){
throw new MyAppException("String val is null");
}
}
}
// Custom Exception created and its use
class MyAppException extends Exception {

private String message = null;

public MyAppException() {
super();
}
public MyAppException(String message) {
super(message);
this.message = message;
}
public MyAppException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return message;
}
@Override
public String getMessage() {
return message;
}

MULTI-THREADING:
Multi threading is a process of executing multiple threads simultaneously.
Thread:

A light weight sub processing, a smallest unit of processing.

Multitasking:

Multitasking is a process of executing multiple tasks simultaneously. It is used to save CPU


time.
It can be achieved by: Multiprocessing and Multithreading

Multiprocessing:

1: Each process has its own address in memory.


2: Cost of communication between process is high.

Multithreading:

1: Thread shared the same address space.


2: Cost of communication between thread is low.
3: At least one process is required for each thread.

Thread Life Cycle:


Ways to create a new thread:

1: By extending Thread class.


2: By Implementing Runnable Interface.

**Thread class extends Object class and implements Runnable interface.


2: Runnable Interface:
Daemon Thread:
Daemon threads in Java are like a service providers for other user threads or objects running
in the same process as the daemon thread. Daemon threads are used for background
supporting tasks and are only needed while normal threads are executing. If normal threads
are not running and remaining threads are daemon threads then the interpreter exits.

Daemon thread in Java are those thread which runs in background and mostly
created by JVM for performing background task like Garbage collection and other
house keeping tasks.

1: Thread.setDaemon(true) makes a Thread daemon but it can only be called before


starting Thread in Java. It will throw IllegalThreadStateException if corresponding
Thread is already started or running.

2: finally blocks are not called, Stacks are not unwounded and JVM just exits.

3: After starting a thread you cannot start that thread again if you do so then
IllegalThreadStateException occur.

4: In Multithreading each thread runs in a separate thread call stack.

Methods:

1: Join: The thread on which join method calls, stops others thread to execute until this
thread completes its
process. If you given milliseconds then other thread do not run up to that time.

Priority of a Thread:
** Min (1), Normal (5), Max (10)
** Thread Priority must be set before start method call.

Sleep () - To suspend the currently executing thread within the specified time, but it will not
release the lock flag.
Not recommended.
Join () - If any executing thread t1 calls join () on t2 i.e.; t2.join () immediately t1 will
enter into waiting state until
t2 completes its execution.
Yield () - Method pauses the currently executing thread temporarily for giving a chance to
the remaining waiting
threads of the same priority to execute. If there is no waiting thread or all the
waiting threads have a
lower priority then the same thread will continue its execution.
Stop ()
Wait ()-

Deep Copy Vs Shallow Copy:


Shallow Copy:
It contains the copy of the objects but any changes done on one object get reflection
on other object

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy
of the values in the original object. If any of the fields of the object are references to other
objects, just the reference addresses are copied i.e., only the memory address is copied.
Deep Copy:
It contains the copy of the objects but any changes done on one object do not get
reflection on other object.

Important Questions

Interview Questions:

1: Difference between Vector and Array List?


1: Vector is synchronized and costlier whereas Array List is not.

2: Data growth: A Vector defaults to doubling the capacity of its current array,
while the ArrayList increases its array size by adding element.

3: All methods of vector are synchronized but this is not in Array List.

4: Array List is faster than Vector.

2: Difference between Iterator and list Iterator?

1: We can use Iterator to traverse a Set or a List or a Map but ListIterator can only
be used to traverse a List, it can't traverse a Set.

2: Iterator we can travel in only one direction but with ListIterator we can travel
both directions.

Different kind of traversing methods like [for-loop ,while loop,do-while,for each lop
etc],they all are index based traversing but as we know Java is purely object oriented
language there is always possible ways of doing things using objects so Iterator .

Traverse Ways: Enumeration, Iterator, ListIterator.


Enumeration Vs Iterator:
Iterator has an extra method > remove() and if any other thread trying to modify the
collection while iterating than it will throw ConcurrentModificationException.
1: Enumeration: Methods used

Enumeration days = vector.elements();

1: boolean hasMoreElements( )
2: Object nextElement( )

2: Iterator: Methods used

1: hasNext()
2: next()
3: remove() - Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a
call to next( ).

Iterator itr = al.iterator();


while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}

3: ListIterator: Methods used

1 void add(Object obj)

2 boolean hasNext( )

3 boolean hasPrevious( )

4 Object next( )

5 int nextIndex( )

6 Object previous( )

7 int previousIndex( )
8 void remove( )

9 void set(Object obj)

3: Difference between HashTable and HashMap?

1: Hashtable is synchronized, whereas HashMap is not

2: Hashtable does not allow null keys or values. HashMap allows one null key and any number of null
values.

4: What is Hashing?

Hashing means using some function or algorithm to map object data to some
representative integer value. This so-called hash code (or simply hash) can then be used as
a way to narrow down our search when looking for the item in the map.

5: HashSet Vs TreeSet vs LinkedHashSet?

1: HashSet is much faster than TreeSet.

2: HashSet doesnt guarantee that the order of elements remains constant but in case of TreeSet it
is possible.

HashSet: Unordered, Not Synchronized

TreeSet: Natural/Sorted order (Comparable is used for natural order sorting and Comparator
for custom order sorting of objects), Not Synchronized
LinkedHashSet: Insertion order, Not Synchronized,
6: Difference between fail-fast Iterator and fail-Safe Iterator?

fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since
iteration has begun. It found thread realizes the change in modification count then it throws
ConcurrentModificationException.

fail-safe iterator doesn't throw any Exception if Collection is modified structurally while one thread is
Iterating over it because they work on clone of Collection instead of original collection and thats why
they are called as fail-safe iterator. Iterator of CopyOnWriteArrayList is an example of fail-safe
Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw
ConcurrentModificationException in Java.

Why to use HQL?

1: Full support for relational operations

2: Return result as Object

3: Polymorphic Queries: Polymorphic queries results the query results along with all the child objects if any.

4: Database independent:

5: Support for Advance features: HQL contains many advance features such as pagination, fetch join with
dynamic profiling, Inner/outer/full joins. It also supports Projection, Aggregation (max, avg) and grouping, Ordering,
Sub queries and SQL function calls.

Hebernate:

Clauses in the HQL are:

from
select

where

order by

group by

Aggregate functions are:

avg(...), sum(...), min(...), max(...)

count(*)

count(...), count(distinct ...), count(all...)

Subqueries
Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the underlying
database supports it.
Difference between get and load method
1: get method of Hibernate Session class returns null if object is not found in cache as well as on database while load()
method throws ObjectNotFoundException if object is not found on cache as well as on database but never return null

2: Get: Always Hit Database Load: May Hit Database

3: Get: Get method never returns a proxy, it either returns null or fully initialized Object.

Load: load() method may return proxy, which is the object with ID but without initializing other properties

4: Load Methods performance is better than Get methods. Coz get methods call Database in
round trip but Load method initialize a proxy object with ID and returns.

What is the difference between and merge and update ?

Use update() if you are sure that the session does not contain an already persistent instance with the same
identifier, and merge() if you want to merge your modifications at any time without consideration of the state of
the session.

Hashing Technique:

For a single character, the hashCode is the ASCII value. For the Integer, the value itself, otherwise some function
combines the object's data bits to create the hashCode. The same element will generate the same hash code
every time.

If no collisions occur while hashing, then the search for any elements is easy and it will take O (1) time constant.

A hash function is a function which when given a key, generates an address in the table.

The method hasCode has different implementation in different classes. In the String class, hashCode is
computed by the following formula

s.charAt(0) * 31n-1 + s.charAt(1) * 31n-2 + ... + s.charAt(n-1)

where s is a string and n is its length. An example


"ABC" = 'A' * 312 + 'B' * 31 + 'C' = 65 * 312 + 66 * 31 + 67 = 64578
Collisions: When we put objects into a hashtable, it is possible that different objects (by the equals() method)
might have the same hashcode. This is called a collision. Here is the example of collision. Two different strings
""Aa" and "BB" have the same key: .

"Aa" = 'A' * 31 + 'a' = 2112


"BB" = 'B' * 31 + 'B' = 2112
HashMap:

CORE- Java Important Concept:

1: ArrayList vs LinkedList:

1: ArrayList is faster than LinkedList if I randomly access its elements. I think random
access means "give me the nth element".

Quiz: Why ArrayList is faster?

ANS: ArrayList has direct references to every element in the list, so it can get the n-th
element in constant time. LinkedList has to traverse the list from the beginning to get to
the n-th element.

2: LinkedList is faster than ArrayList for insertion/deletion. ArrayList's slower because the
internal backing-up array needs to be reallocated.

Reason: ArrayList is slower because it needs to copy part of the array in order to remove
the slot that has become free. LinkedList just has to manipulate a couple of references.

3: ArrayList is Index Based whereas LinkedList is Node Based.


--------------------------------------------------
ArrayList Grow its capacity by:

int newCapacity = (oldCapacity * 3)/2 + 1;

-----------------------------
2: ListIterator VS Iterator:

1: Iterator is used to iterate set, list, and map but list iterator is only used to iterate
only list.
2: Iterator moved only in forward direction and listIterator moved in both direction.

3: Hashtable Vs HashMap:

1: Hashtable is synchronized, whereas HashMap is not.


2: Hashtable does not allow null keys or values. HashMap allows one null key and any
number of null
Values.
3: HashMap is faster than HashTable because hashtable is synchinized.

4: Comparator Vs Comparable:

1: Classes should implement the Comparable interface to control their natural ordering
where as Use
Comparator to sort objects in an order other than their natural ordering.
2: Comparable should be used when you compare instances of same class where Comparator
can be used to compare instances of different classes.

Class class:
WAYS TO GET Instance of class:
1. Using new keyword
2. using Class.forName()
3. using clone().
4. using object deserialization
ObjectInputStream ois =new ObjectInputStream();
Hello hello = (Hello)ois.readObject();

Static Synchronized:

Four conditions occur:

1: Two methods- static synchronized and if two thread want to access each
one method at a time.
A:
1: Method: Static Synchronized
2: Method: Static Synchronized
O/p = At a time one method can be access by any one thread and other thread
wait to call second method. Lock applied on that class.

In other case both the method access randomly.

Reflection:
1:class name to call methods:

Class abc=Class.forName("com.test.Test");
Method m=abc.getMethod("m1");
m.invoke(abc.newInstance());

2: Invoke main method:

Class abc=Class.forName("com.test.Test");
Method[] m=abc.getDeclaredMethods();
for(int i=0; i<m.length;i++)
{
if(m[i].getName().equals(s))
{
m[i].invoke(abc.newInstance(), (Object)abcd);
}
else if(m[i].getName().equals(t))
{
m[i].invoke(abc.newInstance());
}
}

3: Get superclass:

Class.getSuperClass()

4: How to call private methods:

Method m=TestPrivate.class.getDeclaredMethod("Meth1");
m.setAccessible(true);
m.invoke(TestPrivate.class.newInstance());

DataBase:
Nth highest Fetch: SELECT max(loanamount) FROM SI_LOANACCOUNT Emp1
WHERE (nth-1) = (SELECT COUNT(DISTINCT(Emp2.loanamount)) FROM
SI_LOANACCOUNT Emp2
WHERE Emp2.loanamount > Emp1.loanamount)

You might also like