Professional Documents
Culture Documents
Page - 55
Core Java
OOPs Concept:
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.
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
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.
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: Factory Pattern: Is used to create object better than creating object using new
operator.
2: Singleton pattern:
Use:
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:
Code:
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
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:
1. Heap
2. Stack
3. Code
4. Static
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.
Abstract vs Interface:
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
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.
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).
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.
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:
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
2. It is used to maintain list of value in which both key and value are String
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.
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.
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.
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.
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.
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]
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.
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.
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.
Maps classes:
1: HashMap
2: HashTable
3: TreeMap
4: LinkedHashMap
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.
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
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.
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.
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.
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.
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:
ConcurrentSkipListSet, TreeSet
extends SortedSet<E>
Methods:
Points:
Extends SortedMap
Methods:
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.
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.
Specified by:
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.
Specified by:
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.
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.
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:
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.
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 ;
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 boolean equals( Object obj )
{
boolean flag = false;
Emp1 emp = ( Emp1 )obj;
if( emp.age== age )
flag = true;
return flag;
}
}
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:
5. If the instance fields include references to mutable objects, don't allow those objects
to be changed:
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:
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.
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.
In order to access static members, it is necessary to qualify references with the class they came from.
But you can use directly without className through static import.
Ex-
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
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
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.
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.
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
In Java SE 7 and later, a single catch block can handle more than one type of exception. This
features removes Code duplication.
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.
In JAVA 7:
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.
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 {
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:
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());
}
}
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:
Multitasking:
Multiprocessing:
Multithreading:
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.
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.
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 ()-
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:
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.
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 .
1: boolean hasMoreElements( )
2: Object nextElement( )
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( ).
2 boolean hasNext( )
3 boolean hasPrevious( )
4 Object next( )
5 int nextIndex( )
6 Object previous( )
7 int previousIndex( )
8 void remove( )
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.
2: HashSet doesnt guarantee that the order of elements remains constant but in case of TreeSet it
is possible.
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.
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:
from
select
where
order by
group by
count(*)
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
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.
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
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".
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.
-----------------------------
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:
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:
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.
Reflection:
1:class name to call methods:
Class abc=Class.forName("com.test.Test");
Method m=abc.getMethod("m1");
m.invoke(abc.newInstance());
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()
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)