Java Notes
Java Notes
Java Notes
1) BootstrapClassLoader
2) ExtensionClassLoader
3) ApplicationClassLoader
1) BootstrapClassLoader
This ClassLoader is Responsible to load classes from jdk\jre\lib folder. All API classes (like
String, StringBufferetc) will be loaded by Bootstrap class Loader only.
3) ApplicationClassLoader
1. Method Area
For every method the JVM will create a Runtime stack all method calls performed by
that Thread and corresponding local variables will be stored in that stack.
4. PC Registers Area
The instruction which has to execute next will be stored in the corresponding PC
Registers.
The Just-In-Time (JIT) compiler is a component of the runtime environment that improves
the performance of Java applications by compiling bytecodes to native machine code at run
time.
methods are not compiled the first time they are called. For each method, the JVM
maintains an invocation count, which starts at a predefined compilation threshold value and
is decremented every time the method is called. When the invocation count reaches zero, a
just-in-time compilation for the method is triggered. Therefore, often-used methods are
compiled soon after the JVM has started, and less-used methods are compiled much later,
or not at all. The JIT compilation threshold helps the JVM start quickly and still have
improved performance. The threshold value was selected to obtain an optimal balance
between startup times and long-term performance.
3. It provides more flexibility to the end user to use system very easily.
Encapsulation
Binding of data and corresponding methods into a single unit is called Encapsulation. If any
java class follows data hiding and abstraction such type of class is said to be encapsulated
class.
Encapsulation=Datahiding+Abstraction
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
That is you can create new classes that are built upon existing classes. When you inherit
from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
Polymorphism
Polymorphism in Java is a concept by which we can perform a single action in different
ways. (i.e one object represents in many forms)
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means
many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism.
We can perform polymorphism in java by method overloading and method overriding.
1) Inheritance talks about reusability.
2) Polymorphism talks about flexibility.
3) Encapsulation talks about security.
Instance variable
A variable which is declared inside class but outside constructor, any method, or any block is
called as instance variable.
Instance variable will get a memory from heap memory allocation.
Initiation of instance variable is done by JVM.
For every object new copy of instance variable is created.
Life time of instance variable is same as of object life time that is from the object creation till
Object is ready for GC.
It is also called as object variable.
Array
Every array in java is an object hence we can create by using new operator
Example:
int[] a=new int[3];
At the time of array creation compulsory we should specify the size otherwise we will get
compile time error.
Example: int[] a=new int[3];
int[] a=new int[];//Compiletime Error:array dimension missing
It is legal to have an array with size zero in java.
Example: int[] a=new int[0];
If we are taking array size with -ve int value then we will get runtime exception saying
NegativeArraySizeException.
Multi dimensional array creation: In java multidimensional arrays are implemented as array
of arrays approach but not matrix form.
The main advantage of this approach is to improve memory utilization.
int[][] a
a= new int[2][];
a[0]=new int[3];
a[1]=new int[2];
Static
Static members belong to the class instead of a specific instance, this means if you make a
member static, you can access it without object.
Static Variable:-
In the case of instance variables for every object a separate copy will be created but
in the case of static variables for entire class only one copy will be created and
shared by every object of that class
Static variables will be crated at the time of class loading and destroyed at the time
of class unloading hence the scope of the static variable is exactly same as the scope
of the .class file
Static variables can be accessed from both instance and static areas directly.
We can access static variables either by class name or by object reference but usage
of class name is recommended.
For the static and instance variables it is not required to perform initialization
explicitly JVM will provide default values.
For entire class a single copy of static variable will be created.
Example
class Test {
static String s;
public static void main(String[] args) {
System.out.println(s);//null } }
Example:
class Test {
int x;
static int y=20;
Test(){
X=10;
}
public static void main(String[] args) {
Test t1=new Test();
t1.x=50;
t1.y=30;
Test t2=new Test();
System.out.println(t2.x+"----"+t2.y);//10----30 } }
Static Block
Static block is used for initializing the static variables.This block gets executed when the class
is loaded in the memory. A class can have multiple Static blocks, which will execute in the
same sequence in which they have been written into the program.
e.g
class Test
{
private static int x;
static{
System.out.println(“In static block”);
X=10;
}
public static void main(String []args){
System.out.println(“In main method”);
}
}
Output
In static block
In main method
Static method
is a method which belongs to the class and not to the object. A static method can access
only static data. It is a method which belongs to the class and not to the object(instance). A
static method can access only static data. It cannot access non-static data (instance
variables).
A static method can call only other static methods and can not call a non-static
method from it.
A static method can be accessed directly by the class name and doesn’t need any
object
A static method cannot refer to “this” or “super” keywords in anyway
main method
At runtime JVM always searches for the main() method with the following prototype.
If we are performing any changes to the above syntax then the code won't run and will get
Runtime exception saying NoSuchMethodError.
Overloading of the main() method is possible but JVM always calls string[] argument main()
method only.
Example
class Test {
public static void main(String[] args) {
System.out.println("String[] array main method"); //overloaded methods
}
public static void main(int[] args) {
System.out.println("int[] array main method");
}
}
Output is String[] array main method
The other overloaded method we have to call explicitly then only it will be executed
Inheritance:
It allows us to derived new class from existing class and derived class acquire properties of
base class.
It is is-A relationship
By using "extends" keywords we can implement.
The main advantage of IS-A relationship is reusability.
For all java classes the most commonly required functionality is define inside object class
hence object class acts as a root for all java classes
e.g
class Base{
public void display(){
System.out.println(“In Base”);
}
}
class Derived extends Base{
public void show(){
System.out.println(“In Derived”);
}
}
class Test{
public static void main(String []args){
Derived d=new Derived();
d.display();
d.show();
}
}
Whatever methods parent i.e base class have by default it is available in derived class. On
child object we can call both base and derived class methods. Whatever methods derived
class have by default not available to the base class and hence on base class object we cant
call derived class methods.
Note: For all java classes the most commonly required functionality is define inside object
class hence object class acts as a root for all java classes
All java API is based on inheritance concept. The most common methods which are
applicable for any java object are defined in “Object” class. Hence every class in java is
either a child class of Object either directly or indirectly so that object class methods are
default available for every java class.
Object
Exception Error
Multiple Inheritance:-Java class cant extend more than one class at a time. Hence java
wont support multiple inheritance in class.
If our class doesn’t extend any other class then only that class is direct child class of Object
class.
Polymorphism
Same name with different forms is the concept of polymorphism.
Two methods are said to be overload if and only if both having the same name but different
argument types
Types of Polymorphism
a. Compile time Polymorphism
b. Runtime Polymorphism
Method Overloading:
Two methods are said to be overload if and only if both having the same name but different
argument types.
All these methods are considered as overloaded methods.
Having overloading concept in java reduces complexity of the programming
e.g
class Demo{
public void m1(int a){
System.out.println(a);
}
public void m1(float a){
System.out.println(a);
}
public void m1(double a){
System.out.println(a);
}
}
class OverloadingExample{
public static void main(String []args){
Demo d=new Demo();
d.m1(10) ;
d.m1(12.4f);
d.m1(60.5);
}
}
In overloading compiler is responsible to perform method decision based on the reference
type. Hence overloading is also considered as compile time polymorphism (or) static
polymorphism (or) early biding.
Method Overriding
Whatever the Parent has by default available to the Child through inheritance, if the Child is
not satisfied with Parent class method implementation then Child is allow to redefine that
Parent class method in Child class in its own way this process is called overriding. i.e child
class redefine base class method.
The Parent class method which is overridden is called overridden method
The Child class method which is overriding is called overriding method.
e.g
class Base{
public void display(){
System.out.println(“Hello All”);
}
}
class Derived extends Base{
public void display(){
System.out.println(“Hello!! How are you?”);
}
}
class Demo{
public static void main(String []args){
Base b=new base();
b.display();//Hello All (Base method)
Derived d=new Derived ();
b.display();//Hello!! How are you? (Derived method)
Base b1=new Derived()
b1.display();//Hello!! How are you? (Derived method)
}
}
In overriding method decision is always takes care by JVM based on runtime object hence
overriding is also considered as runtime polymorphism or dynamic polymorphism or late
binding.
The process of overriding method resolution is also known as dynamic method dispatch.
If parent class is abstract or parent class object is not created then we have to use super
keyword to call overridden method
Rules for overriding
In overriding method names and arguments must be same. That is method prototype must
be same.
In overriding method names and arguments must be same. That is method signature must
be same.
Until 1.4 version the return types must be same but from 1.5 version covariant return types
are allowed.
According to this Child class method return type need not be same as Parent class method
return type its Child types also allowed.
class Parent {
public Object methodOne() {
return null;
}
}
class Child extends Parent {
public String methodOne() {
return null
}
}
It is valid in "1.5" and on-words but invalid in "1.4".
Co-variant return type concept is applicable only for object types but not for primitives.
Private methods are not visible in the Child classes hence overriding concept is not
applicable for private methods. Based on own requirement we can declare the same Parent
class private method in child class also. It is valid but not overriding.
Parent class non final methods we can override as final in child class
We can override a non-abstract method as abstract this approach is helpful to stop
availability of Parent method implementation to the next level child classes.
While overriding we can't reduce the scope of access modifier.
We can't override a static method as non static. Similarly we can't override a non static
method as static.
If both parent and child class methods are static then we won’t get any compile time error.
It seems overriding concept applicable to static methods but it is not overriding it is Method
hiding
All rules of method hiding are exactly same as overriding except the following differences.
Note:
In overloading we have to check only method names (must be same) and arguments (must
be different) the remaining things like return type extra not required to check.
But In overriding we should compulsory check everything like method names, arguments,
return types, throws keyword, modifiers etc.
Final Keyword
Final is the modifier applicable for classes, methods and variables.
Final Method
If the child is not allowed to override any method, that method we have to declare with
final in parent class. That is final methods cannot overridden
e.g
class Base{
public final void display(){
System.out.println(“Final method”);
}
}
class Derived extends Base{
public void display(){
System.out.println(“In derived”);
}
}
Output:- Compile time error.
As final method cannot allow to override.
Final class
If a class declared as the final then we can’t creates the child class that is inheritance
concept is not applicable for final classes
e.g
final class Base{
public void display(){
System.out.println(“In Base class”);
}
}
class Derived extends Base{
}
Output:- Compile time error.
Every method present inside a final class is always final by default whether we are declaring
or not. But every variable present inside a final class need not be final.
The main advantage of final keyword is we can achieve security. Whereas the main
disadvantage is we are missing the key benefits of oops: polymorsim (because of final
methods), inheritance (because of final classes) hence if there is no specific requirement
never recommended to use final keyboard.
Final variables
Generally, we can consider a final variable as a constant, as the final variable acts like a
constant whose values cannot be changed.
If the instance variable declared as the final compulsory we should perform initialization
explicitly and JVM won't provide any default values. Whether we are using or not otherwise
we will get compile time error.
To initialize final variable different ways are used
1. At the time of declaration:
2. Inside instance block:
3. Inside constructor:
Abstract method
Abstract methods have only declaration but not implementation.
e.g
public abstract void area();
Child classes are responsible to provide implementation for parent class abstract methods.
e.g
abstract class Shape{
public abstract void area();
}
Class Circle extends Shape{
public void area(){
System.out.println(“Area of circle”+a);
}
}
Class Demo{
Public static void main(String []args){
Circle c=new Circle();
c. area();
}
}
Abstract Class
If a class contain at least on abstract method then compulsory the corresponding class
should be declare with abstract modifier. Because implementation is not complete and
hence we can't create object of that class
Even though class doesn't contain any abstract methods still we can declare the class as
abstract that is an abstract class can contain zero no of abstract methods also.
If a class extends any abstract class then compulsory we should provide implementation for
every abstract method of the parent class otherwise we have to declare child class as
abstract.
Exception
An unwanted unexpected event that disturbs normal flow of the program is called
exception.
It is highly recommended to handle exceptions. The main objective of exception handling is
normal termination of the program.
Exception Error
Exception: Most of the cases exceptions are caused by our program and these are
recoverable.
Ex : If FileNotFoundException occurs then we can use local file and we can continue rest of
the program execution normally.
Error: Most of the cases errors are not caused by our program these are due to lack of
system resources and these are non-recoverable.
Ex :If OutOfMemoryError occurs being a programmer we can't do anything the program will
be terminated abnormally
Unchecked Exceptions:- The exceptions which are not checked by the compiler whether
programmer handing or not ,are called unchecked exceptions.
Note:
Whether exception is checked or unchecked compulsory it should occurs at runtime only
and there is no chance of occurring any exception at compile time.
toString(): This method prints exception information in the following format. Name of the
exception: description of exception.
Finally block:
It is not recommended to take clean up code inside try block because there is no guarantee
for the execution of every statement inside a try.
It is not recommended to place clean up code inside catch block because if there is no
exception then catch block won't be executed.
We require some place to maintain clean up code which should be executed always
irrespective of whether exception raised or not raised and whether handled or not handled.
Such type of best place is nothing but finally block.
Hence the main objective of finally block is to maintain cleanup code.
The speciality of finally block is it will be executed always irrespective of whether the
exception raised or not raised and whether handled or not handled.
Even though return statement present in try or catch blocks first finally will be executed and
after that only return statement will be considered. i.efinally block dominates return
statement.
If return statement present try, catch and finally blocks then finally block return statement
will be considered.
There is only one situation where the finally block won't be executed is whenever we are
using System.exit(0) method. When ever we are using System.exit(0) then JVM itself will be
shutdown , in this case finally block won't be executed.
finally:
finally is the block always associated with try-catch to maintain clean up code which should
be executed always irrespective of whether exception raised or not raised and whether
handled or not handled.
finalize:
finalize is a method, always invoked by Garbage Collector just before destroying an object to
perform cleanup activities.
finally block meant for cleanup activities related to try block where as finalize() method
meant for cleanup activities related to object
Thread:
Multi-Threading:-
Executing several tasks simultaneously is called as multi-tasking.
There are two types of multi-tasking
1) Process based
2) Thread based
Thread based multi-tasking:- Executing several tasks simultaneously where each task is a
separate independent part of same program is called as thread based multi-tasking. Where
each independent part is called as Thread.
Main task of multi-tasking is to reduce response time of the system and to improve
performance.
Thread Priority:
1) join()
2) sleep();
yield() method
yield() method causes "to pause current executing Thread for giving the chance of
remaining waiting Threads of same priority".
If all waiting Threads have the low priority or if there is no waiting Threads then the
same Thread will be continued its execution.
If several waiting Threads with same priority available then we can't expect exact
which Thread will get chance for execution.
The Thread which is yielded when it get chance once again for execution is depends
on Thread scheduler.
public static native void yield();
join() method
If a Thread wants to wait until completing some other Thread then we should go for
join() method.
For example t1 wants to continue its execution after t2 finish its execution then t1
will call t2.join().
As soon as t1 executes t2.join() , immediately t1 will go in waiting state until t2
completes its execution
Once t2 finish its execution then t1 will continue its execution.
Every join() method throws InterruptedException, which is checked exception hence
compulsory we should handle either by try catch or by throws keyword. Otherwise
we will get compile-time error.
Sleep() method
If a Thread don't want to perform any operation for a particular amount of time then
we should go for sleep() method.
Prototype of sleep() method
public static native void sleep(long ms) throws InterruptedException public static
void sleep(long ms,int ns)throws InterruptedException
Synchronization
It is modifier which is applicable for method and block but not for class and variable. If
multiple threads are operating on same java object simultaneously then there may be a
chance of data-inconsistency. To avoid data-inconsistency we should use synchronized
keyword. If a method or block is declared as synchronized then at a time only one thread is
allow to execute that method or block on the given java object. By using synchronized
method or block we can resolve data-inconsistency problem. Main advantage of
synchronization is to resolve data-inconsistency problem but the main disadvantage of
synchronization is it increases waiting time of thread and performance is reduce.
Synchronization concept is implemented by using Lock concept.
If thread wants to execute synchronized method or block on given object then thread has to
get lock of that object first.
Once thread acquires lock on object then it is allowed to execute any synchronized method
on that object. Once method execution completes automatically thread releases a lock.
Getting lock and releasing lock activity is done by JVM.
While a thread executing synchronized method or block on the given object
then remaining threads are not allowed to execute any synchronized method
simultaneously on same object.
But remaining threads can execute non-synchronized methods simultaneously.
Inter-thread communication
Two threads can communicate with each other by using wait(), notify() and notifyAll()
methods.
The thread which is expecting updation from other thread will call wait() method and then
immediately thread will enter into waiting state.
The thread which is responsible for updation is going to call notify() method then waiting
thread will get that notification and continue its execution with those updated items.
To call wait(), notify(), notifyAll() methods are present in Object class.
To call wait(), notify() , notifiAll() method on object thread must be a owner of that object.
We can call wait(), notify() or notifyAll() methods only from synchronized area otherwise we
will get runtime exception.
If thread call wait() method on object then it immediately releases the lock of that particular
object and enter into waiting state.
If thread calls notify() method on an object it releases the lock of that object but not
immediately.
Except wait(), notify(), notifyAll() there is no other method where thread release a lock.
Methods are
public final void wait() throws InterruptedException
public final void wait(long ms) throws InterruptedException
public final void wait(long ms,int ns) throws InterruptedException
public final native void notify()
public final native void notifyAll()
Collection FrameWork
Collection Framework
collection(I)
If we want to represent group of individual objects as a single entity then we
should use collection.
Collection interface defines most common methods which are applicable for
any collection object.
It is considered as root interface of collection framework.
collections(C)
Collections is an Utility Class Present in java.util Package to Define Several
Utility Methods for Collection Object
Methods available in collection interface
1. boolean add(Object o)
2. boolean addAll(collection c)
3. boolean remove(Object o)
4. boolean removeAll(collection c)
5. boolean retainAll(collection c) to remove all objects except those
present in c
6. void clear()
7. boolean contains(Object o)
8. boolean containsAll(collection c)
9. boolean isEmpty()
10. int size()
11. Object[] toArray()
12. Iterator iterator()
List(I)
If we want to represent group of individual object as single entity where
duplicates are allowed and insertion order is preserved then we should use
List.
Insertion order is preserved by using index
List interface specific methods
1. void add(int index,Object o);
2. boolean addAll(int index,collection c)
3. Object get(int index)
4. Object remove(int index)
5. Object set(int index, Object new) to replace object
6. int indexOf(Object o) first occurrence
7. int lastIndexOf(Object o)
8. ListIterator listIterator()
ArrayList(c)
• The underlying data structure is growable array or resizable array.
• Duplicates are allowed
• Insertion order is preserved
• Heterogeneous objects are allowed
• NULL insertion is allowed
• Impliments RandomAccess, serializable and cloneable interface
• Best suitable if frequent operation is retrieval operation
• Worst option if frequent operations is insertion or deletion in the
middle
Constructor
1. ArrayList al=new ArrayList()
creates an empty ArrayList object with default initial capacity as 10.
If ArrayList reaches its capacity then new capacity will be
calculated as follows
new_capacity=(current_capacity*3/2)+1
2. ArrayList al=new ArrayList(int capacity)
3. ArrayList al=new ArrayList(collection c)
creates an equivalent ArrayList object for the given collection.
Implements serializable, RandomAccess and cloneable interface.
ArrayList is best choice if your frequent operation is retrival whereas
ArrayList is worst operation if frequent operation is deletion or insertion in
the middle.
LinkedList :
• The underlying data structure is double linked list.
• Insertion order is preserved
• Duplicate objects are allowed
• Heterogeneous objects are allowed
• Null insertion is allowed
• Implements serializable and cloneable interface
• It is best choice if our frequent operation is insertion or deletion in the
middle whereas it is worst option if frequent operation is retrival.
Constructor:
• LinkedList l=new LinkedList()
It creates empty linklist object
• LinkedList l=new LinkedList(Collection c)
Creates an equivalent linkedlist object for given collection
object.
Vector:
• The underlying data structure is resizable array or growable array
• Insertion order is preserved
• Duplicates are allowed
• Heterogeneous objects are allowed
• Null insertion is allowed
• Implements serializable, cloneable and RandomAccess interface.
• Every method present in vector is synchronized and hence vector
object is thread safe.
Constructors
• Vector v=new Vector()
Creates an empty vector object with default initial capacity as 10.Once
it reaches to its
capacity then new capacity will be calculated by using following
New capacity=current capacity*2
• Vector v=new Vector(int initial_capacity)
Creates an empty vector object with specified initial capacity.
• Vector v=new Vector(int initial_capacity,int increment_capacity)
Creates an empty vector object with specified initial capacity and
once it reach to
its capacity then new capacity will be calculated using
increment_capacity value.
• Vector v=new Vector(Collection c)
Creates an equivalent vector object for the given collection
object
Vector Methods
1. add(Object O)
2. add(int index, Object O)
3. addElement(Object O)
4. remove(Object O)
5. removeElement(Object o)
6. remove(int index)
7. removeElementAt(int index)
8. clear()
9. removeAllElements()
10. Object get(int index)
11. Object elementAt(int index)
12. Object firstElement()
13. Object lastElement()
14. Int size()
15. Int capacity()
Iterator
• We can apply iterator to any collection object
• By using iterator concept we can perform read and remove operations
Methods of iterator
1. public boolean hasNext()
2. public Object next()
3. public void remove()
• using Iterator we can perform only read and remove operations but we
can’t perform add or replace operation.
Also iterator always move forward i.e iterator is single direction i.e forward
only cursor.
• To overcome limitation of Iterator we should use ListIterator.
ListIterator
• By using ListIterator we can move forward or backward direction and
hence it is called as bi-directional cursor.
• By using ListIterator we can add or replace Object along with read and
remove operation.
• Limitation- it can only applicable for List objects.
Methods of ListIterator
1. public boolean hasNext()
2. public Object next()
3. public int nextIndex()
4. public boolean hasPrevious()
5. public Object previous()
6. public int previousIndex()
7. public void remove()
8. public void add(Object o)
9. public void set(Object o)
Set(I)
Set is child interface of collection
If we want to represent a group of individual objects as a single entity
where duplicates are not allowed and insertion order not preserved.
HashSet(C)
1. Underlying data structure is Hash Table
2. Duplicates are not allowed
3. Insertion order is not preserved and it is based on hashCode of object.
4. NULL insertion is possible(only once)
5. Heterogeneous objects are allowed
6. Implements serializable and cloneable but not RandomAccess interface
7. Best choice if frequent operation is search
Constructor
1. HashSet h=new HashSet() – creates an empty object with initial capacity
16
2. HashSet h=new HashSet(int initial_capacity) – creates an empty object
with specified initial capacity.
3. HashSet h=new HashSet(Collection c) – creates an equivalent HashSet
object for given collection object
LinkedHashSet
It is child class of HashSet
Same as HashSet but it preserved insertion order.
Underlying data structure is combination of HashTable and LinkedList
SortedSet(I)
It is child interface of Set
If we want to represent group of individual objects according to some
sorting order without duplicates then we should go for SortedSet.
Methods
1. Object first()- returns first element of the SortedSet
2. Object last()- returns last element of the SortedSet
3. SortedSet headSet(Object obj)- returns SortedSet whose elements are
less than object.
4. SortedSet tailSet(Object o)- returns SortedSet whose elements are
greater or equal to object.
5. SortedSet subSet(Object obj1, Object obj2) – returns SortedSet whose
elements are greater than or equal to obj1 and less than obj2.
6. Comparator comparator()- returns Comparator object that describes
underlying sorting technique. If we are using default natural sorting
order then we will get null.
TreeSet
The underlying data structure is balanced Tree.
Duplicates are not allowed
Insertion order is not preserved
Heterogeneous objects are not allowed
NULL insertion possible(only once)(from 1.7v not allowed)
Implements serializable and cloneable but not RandomAccess
All objects are inserted based on some sorting order it may be default
natural sorting order or customized sorting order.
Constructor
1. TreeSet t=new TreeSet() – creates an empty object where the elements
will be inserted according to default natural sorting order.
2. TreeSet t=new TreeSet(Comparator c)- it creates an empty object where
the elements are inserted according to customized sorting order
specified by comparator object.
3. TreeSet t=new TreeSet(collection c)- it creates an equivalent TreeSet
object for given collection object.
Map(I)
It is not child interface of collection.
If we want to represent group of individual object as key-value pair then
you should use Map.
Both keys and values are objects only.
Duplicate key is not allowed but values can be duplicated.
Each key-value pair is called as Entry.
Methods
1. Object put(Object key,Object value) –to add one key value pair to the
map. If key is already present then old value will be replaced with new
value and returns old value.
2. void putAll(Map m)
3. Object get(Object key) – returns value associated with key.
4. Object remove(Object key)- removes the entry associated with key
5. boolean containsKey(Object key)
6. boolean containsValue(Object value)
7. boolean isEmpty()
8. int size()
9. void clear()
HashMap
The underlying data structure is HashTable
Insertion order is not preserved and it is based on hashCode of keys.
Duplicate keys are not allowed but values can be duplicated.
Heterogeneous objects are allowed but both keys and values are
heterogeneous.
Null is allowed for key(only once)
Null is allowed for values
Implements cloneable and serializable interface but not random access .
Best for searching
Constructor
1. HashMap h=new HashMap() – creates an empty object with default
initial capacity 16.
2. HashMap h=new HashMap(int initial_capacity) – creates an empty
HashMap object with specified initial capacity.
3. HashMap h=new HashMap(Map m) – creates an equivalent object for
specified Map object.
SortedMap(I)
It is child interface of Map.
If we want to represent a group of key-Value pairs according to some
sorting order of keys then we should go for sortedMap.
Sorting is based on key but not based on value
Methods
1. Object firstKey()
2. Object lastKey()
3. SortedMap headMap(Object key)
4. SortedMap tailMap(Object key)
5. SortedMap subMap(Object key1,Object key2)
6. Comparator comparator()
TreeMap
Underlying data structure is red black tree
Insertion order is not preserved and it is based on some sorting order of
keys
Duplicate keys are not allowed but values can be duplicated
If we are depending on default natural sorting order then keys should be
homogenous and the comparable otherwise we will get runtime
exception saying ClassCastException
If we are defining our own sorting by comparator then keys need not be
homogeneous and comparable. We can take heterogeneous non
comparable objects also.
We are depending on default natural sorting order or customized sorting
order there are no restrictions for values.
For non-empty TreeMap if we are trying to insert an entry with NULL key
then we will get runtime exception saying NullPointerException. (till
1.6v)
For empty TreeMap as a first entry with a NULL key is allowed but after
inserting that entry if we are trying to insert any other entry with NULL
then we will get runtime exception saying NullPointerException (till 1.6v)
Constructor
TreeMap t=new TreeMap()- create an empty TreeSet object with default
natural sorting order.
TreeMap t=new TreeMap(Comparator c)- for customized sorting order.
Queue(I):
From V1.5 enhancements (Queue Interface)
It is a child interface of Collection.
If we want to represent a group of individual objects prior to processing then
we should go for queue.
Eg: before sending sms message all mobile nos we have to store all mobile nos
in some data structures. In which order we added mobile nos in the same
order only message should be send. For this FIFO requirement queue is the
best choice.
Usually queue follows FIFO but based on our requirement we can implement
our own priority order also(PriorityQueue)
From 1.5V onwards LinkedList class also implements Queue Interface.
LinkedList base implementation of Queue always follows FIFO.
Lambda Expression:
Use of lambda expression-
To enable functional programming in java lambda expression is
introduce. You can use procedure as variable. you can send procedure as
argument to function using lambda.
Write more clean, maintainable and readable code
To use API’s easy and efficiently
To handle parallel programming
Lambda Expression
It is an anonymous function. i.e a function without name
Modifier does not applicable to lambda function
Return type not applicable
When we use return statement then in lambda we don’t required to write
return keyword. Only single statement is present then we don’t required to
use {}. Only one parameter then we can remove ()
Eg
Find length of a string
Lambda expression will be
s->str.length()
Functional Interface
Once we write lambda expression then to invoke lambda expression we
required functional interface.
What is functional interface?
Functional interface is a interface which contains only single abstract method.
Some of java functional interface are
Runnable ---- contains public void run() method
Callable ----- contains public void call() method
actionListener----- it contains actionPerformed(Event e) method
Comparable---- it contains compareTo() method.
Note: you can have any no of default method or static method in interface but
only one abstract method must be present for functional interface.
What is purpose of functional interface?
To indicate interface explicitly as functional interface. Even if we don’t
use @FunctionalInterface annotation still compiler will consider
interface as functional if it contains single abstract method.
If we use annotation @FunctionalInterface and still we define more than
one abstract methods then we will get compile time error saying
unexpected @FunctionalInterface annotation multiple non overriding
abstract method.
If we use annotation @FunctionalInterface and in did not define any
method then we will get compile time error.
Case 3:
In the child interface we can’t define any new abstract otherwise we will get
compile time error.
Ex:
@FunctionalInterface
Interface f1
{
Public void m1()
}
@FunctionalInterface
Interface f2
{
Public void m2();
}
Case 4:
We can add any no of abstract methods in derived or child interface if it is not
declared using annotation @FunctionalInterface.
Eg:
@FunctionalInterface
Interface P
{
Public void m1();
}
Interface M extends P
{
Public void m2();
Default int add(int,int);
}
Function
function <T t>
if we want to perform something and then we want to return something which
is not boolean then we have to use function
interface Function<T.R>
{
public R apply(T t);
}
Consumer
Consumer<T>
It is same as function only it does not return anything
Interface Consumer<T>
{
public void accept(T t>
}
Supplier
Supplier<T>
interface Supplier<R>
{
public R get();
}
Streams:
If we want to process objects from collection then we should use Stream
concept
Stream can be applied to group of data , array or collection
Stream s=any collection object.stream().
Stream() is available in collection package.
If I want to get some object filtered based on some boolean condition
then we should go for filter().
filter(Predicate)
If we want to process a group of objects and create new collection
object then we will go for map(). Eg if we want to increase salary of
employee by 1k then we can use map()
map(Function)
Some more functions from Stream
o count()-it will give you count of object based on condition which
we use in filter or map. Only work on stream not on collector
o collect()-if after processing we want to collect result then we have
to use collect() method. In collect() method we can convert that
object into specific type using Collectors
o stream()
o sorted() – it will sort collection object based on natural sorting
order. It work on stream only not on collector.
o Min() – according to sorting it is fixed that 1st element is always a
min and last is max. it does not check value for min or max.
o Max() - according to sorting it is fixed that 1st element is always a
min and last is max. it does not check value for min or max.
forEach – we can use of forEach loop from stream to process one by one
object from collection. You can use lambda expression inside forEach,
you can use Consumer(Function Interface) to process object, you can
use method reference to print object one by one from collection.
toArray() - it is used to convert stream of element into array. Using
constructor reference we can convert stream of object to array. To print
array we can use for loop as we can’t use forEach as it apply to only
stream.
Stream.of() – it is used to convert group of values into stream