Sunteți pe pagina 1din 143

What are the principle concepts of OOPS?

There are four principle concepts upon which object oriented design and
programming rest. They are:

 Abstraction
 Polymorphism
 Inheritance
 Encapsulation

(i.e. easily remembered as A-PIE).

Topics:

Data Hiding
Abstraction => Encapsulation

(PIE)
Polymorphim
Inhertance
Encapsulation
Inhertance vs Aggration/Composition(IS-A or HAS-A)
Overloading vs Overriding(Compile time or static binding or early binding vs Runtime
or dynamic binding or late binding)
Coupling
Cohersion

Data Hiding Def:


Data hiding is a software development technique specifically used in
object-oriented programming (OOP) to hide internal object details
(data members). Data hiding ensures exclusive data access to class
members and protects object integrity by preventing unintended or
intended changes.

Abstraction Def:
Data abstraction is the reduction of a particular body of data to a simplified
representation of the whole. Abstraction, in general, is the process of
taking away or removing characteristics from something in order to
reduce it to a set of essential characteristics.

Inheritance Def:

Inheritance is a mechanism of acquiring the features and behaviors of a


class by another class.

Polymorphism
Polymorphism refers to a programming language's ability to process objects
differently depending on their data type or class. More specifically, it is the
ability to redefine methods for derived classes.

Data hiding:
------------
1)Out side person can't access our internal data directly or our internal data should
not go outside directly.This oops feature is nothing but data hiding.After validation
or authentication out side person can access our internal data.EX:1 after providing
proper username/password we can able to access our gmail inbox information.Ex :2
Even though we are valid customer of the bank we can able to access our account
information and we can't access others account information.
By declaring data member or variable as private we can achive data hiding.
EX:public class account{
private double balance;
public double getBalance(){

//validation required
return balance;
}

}
The main advantage of data hiding is security.
NOTE:It is highly recommended to declare data member or variable as private.

Abstraction:
------------
Hiding internal implementation and just highlight the set of services what we are
offering,is the concept of abstraction.
Ex:through bank atm GUI screen bank people are highlighting the set of services
what they are offering with out highlighting internal implementation.

The main advantages of abstraction are:


1)we can achieve security because we are not highlighting our internal
implementation.
2)with out effecting out side persion we can able to perform any changes in our
internal system and hence enhancement will become easy.
3)It improves maintainability of the application.
4)it improves easiness to use our system.
By using interfaces and abstract classes we can implement abstraction.

Encapsulation:
--------------
The process of binding data and corresponding methods into a single unit is nothing
encapsulation.
ex:class student{

data members + methods

}
If any component follows data hiding and abstraction such type of component is said
to be Encapsulation.
Encapsulation = Data hiding + Abstraction.

Class Account{

private double balance;//data hiding

public double getBalance(){//abstraction

//validate data
return balance;

}
public void setBalance(double balance){//abstraction
//validate data
this.balance = balance;
}

Advantages of encapsulation:
----------------------------
the main advantages of encapsulation are we can achieve security,enhancement will
become easy,it improves maintain ability of the application.
the main advantage of encapsulation is we can achieve security but the main
disadvantage of encapsulation is it increases length of code and slows down
execution.

Tightly Encapsulation:
----------------------
The class is said to be tightly encapsulated if and only if each and every variable
declared as private.weather class contains corresponding getter and setter methods
or not and weather this methods are declared as public or not this things we are not
required to check.
EX:
public class Account{

private double balance;

public double getBalance(){


return balance;
}

EX:
class A{
private int x=10; //correct.
}
class B extends A{
int y = 20; //wrong.
}
class C extends A{
private int z=10; //correct.
}

EX:
class A{
int x = 10; // wrong
}
class B extends A{
private int y = 20; //wrong.
}
class C extends A{
private int z=10; //wrong.
}

Note : If the parent class is not tightly encapsulated then no child class is tightly
encapsulated.

What is the difference between abstraction and encapsulation?

 Abstraction focuses on the outside view of an object (i.e. the


interface) Encapsulation (information hiding) prevents clients from
seeing it’s inside view, where the behavior of the abstraction is
implemented.

 Abstraction solves the problem in the design side
while Encapsulation is the Implementation.
 Encapsulation is the deliverables of Abstraction. Encapsulation barely
talks about grouping up your abstraction to suit the developer needs.

Inheritance:(IS-A)
------------
It is also known as inheritance.The main advantage of is-a relation ship is code
reusability.By using extends keyword we can implement is-a relation ship.
conclusion:
1)what ever methods parent has by default available to the child and hence child
reference we can call both parent and methods.
2)what ever methods child has by default not available to the parent and hence
parent reference we can't call child specific methods.
3)parent reference can be used to hold child object but using that reference we can't
call child specific methods but we can call the methods in parent class.
4)parent reference can be used to hold child object but child reference can't be used
to hold parent object.

With and with out inheritance:


Note:
the most common methods which are applicable for any type of child , we have to
define in parent class.the specific methods which are applicable for a particular child
we have to define in child class.

Total java api is implemented based on inheritance concept.

the most common methods which are applicable for any java object are defined in
object class.and hence every class in java is the child class of the object either
directly or indirectly.so that object class methods by default available to every java
class without rewriting.due to this object class act as root of all java classes.

Throw able class returns the most common methods which are required for
exception and error classes.hence this class act root for java exception hierarchic.

Multiple inhertance:
--------------------
A java class can't extend more than one class at a time hence java wan't provide
support for multiple inheritance in classes.

Ex: Class A extends B,C


Note:If your class doesn't extend any other class then only our class is direct child
class of object.

If your class extend any other class then only our class is indirect child class of object

EX:Class A extends B{

}
NOTE:Either directly or indirectly java won't support for multiple inheritance with
respect to classes.

There may be a chance of ambiguity problem hence java won't provide support for
multiple inheritance.

But interface can extend any no of interfaces simultaneous.Hence java provide


support for multiple inheritance with respect to interfaces.
Why Ambiguous want be there in interfaces:

Overloading:
------------
case 1:Automatic promotion in overloading :

while resolving overloaded methods if exact matched method is not available then
we won't get any compile time error immediatle.First it will promote argument to
the next level and check weather matched method is available or not if the matched
method is available then it will be considered.If the matched method is not available
then compiler promotes argument once again to the next level.This process will be
continued untill all possible promotions.Still if the matched is not available then we
will get compile time error.The following are all possible promotions in overloading.

This process is called automatic promotion in overloading.


Case 2:

Note: While resolving overloaded methods compiler will always give the presidency
for child type argument when compared with parent type argument.

Case 3:
Case 4:

Case 5:
In general var-arg method will get least priority I.e.,if no other method matched then
only var-arg method will get the chance.It is exactly same as default case inside
switch.

Case 5:

Note : In overloading method resolution always takes care by compiler based on


reference type.In overloading runtime object wont play any role

Overriding:
-----------
what ever methods parent has by default available to the child through inhertance.If
child class is not satisfied with parent class implemantation then child is allowed to
redefined that method based on its recuriment.This process is called overriding.the
parent class method which is overriden is called overriden method and the child
class method which is overriding is called overriding method.

EX:

EX:
**In overriding method resolution always takes care by JVM based on run-time
object.And hence overriding is also consider as runtime polymorphism or dynamic or
late binding.

Rules for overriding:

1)In overriding method names and argument types must be matched.I.e., method
signatures must be same.
2)In overriding return types must be same but this rule is applicable untill 1.4V
only.From 1.5V onwards we can take co-variant return types.According to this child
class method return type need not be same as parent method return type.Its child
type also allowed.

EX:
It is invalid in 1.4Version, but from 1.5V on wards it is valid.

Ex:

In co-variant return type concept applicable only for object types but not for
primitive types.
Note:Parent class private methods not available to the child and hence overriding
concept not applicable for private methods.
Based on our requirment we can define exactly private method in child class it is
valid but not overriding.

EX:

We can’t override parent class final methods in child classes if we are trying to
override we will get compile time error.

EX:
Parent class abstract methods we should override in child class to provide
implemantation.

EX:

We can override non abstract as abstract.

EX:
Note:The main advantage of this approch is we can stop the availibility of parent
implemantation to the next level child classes.

In overriding the following modifiers wan’t keep any ristrcition.

1)Synchronized
2)native
3)Stricpfp

While over riding we can’t reduce scope of access modifier but we can increase the
scope.
Exception in inheritance:
-------------------------
If child class method throws any checked exception compulsory parent class method
should throw same checked exception or its parent other wise we will get compile
time error but there are no restrictions for unchecked exceptions.
List of Cases:
Rules For Overriding :
1)Method names must be same and argument types must be same and method
signature must be same.
2)Return type must be same upto 1.4V,but from 1.5V covarient return type is
introduce so we can have different return types also.
3)Private methods are nto visible to the child class overriding concept is not
applicable for overriding.
4)Final methods we can’t override and abstract methods we can override.
5)Syncronized,strictfp,native methods won’t provide any restrictions in overrideing
6)We can’t reduce the scope of modifier from parent to child class but we can
incress.
7)If child class throws any checked exception the super class method should its super
exception or same exception.

Overriding with respect to static methods:

1)We can’t override a static method as non static.Other wise we will get compile
time error.

Ex:
2)Similarly we can’t override a non static method as static

Ex :

3)If both parent and child class are static then we won’t get any compile time error it
seams overriding applicable for static methods but it is not overriding and it is
method hiding.

EX:
Method Hidding:

All rules of method hidding are exactly same as method hiding except the following
differences:

Ex:
Note : If both parent and child class methods are non static then it will become
overriding.In this case o/p is :
Parent , child, child.

Constructors:
-------------
Once we create an object we should perform initialization then only the object in a
position to respond properly.
when ever we are creating an object some piece of code will be executed
automatically to perform initialization of the object.this piece of code is nothing but
constructor.Hence the main puprose of constructor is to perform initialization of the
object.
NOTE:The main purpose of constructor is to perform initialization of an object but
not to create object.

Difference between constructor and instance block:

The main purpose of constructor is to perform inationalization of an object.But other


than initialization if we want to perform any activity for every object creation then
we should go for instance block(updating one entry in the database for every object
creation or increamenting count value for every object creation etc.,).Both
constructor and instace block have there own different purposes and replacing one
concept with another concept will not work always.
Both constructor and instance block will be executed for every object creation.But
instance block first followed by constructor.

Demo program to print no of objects created for a program.


Rules of writing constructor:
1)Name of the class and name of the constructor must be matched.
2)Return type concept not applicable for constructor even void also.
3)By mistake if we are trying to decleare return type for the constructor then we
won’t get any compile time error because compiler treats it as a method.

The only applicable modifiers are public,private,default and protected for


constructor.If we are trying to use any other modifier we will get compile time error.
Compiler is responsible to generate default constructor(but not JVM).
If we are not writing any constructor then only compiler will generate default
constructor I.e., if we are writing atleast one constructor then compiler won’t
generate default constructor.Hence every class in java can contain constructor it may
be default constructor generated by compiler or customized constructor explicitly
provided by programmer but not both simultaniously.

Default Constructor:

Programmers code and compilers code:


The first line inside every constructor should be either super or this and if we are not
writing anything then compiler will always place super()

Case : 1
We can take super() or this() only in first line of constructor.If we are trying to take
any where else we will get compile time error.
Case 2:
With in the constructor we can take super() or this() but not both simultaneously.

Ex:

Case 3:
We can use super() or this() only inside constructor.If we are trying to use outside of
constructor we will get compile time error.
Overloaded Constructors:

With in a class we can declear multiple constructors and all this constructors having
same name but different type of arguments.Hence all these constructors consider as
overloaded constructors.Hence overloading concept applicable for constructors.

Ex:
For constructor inheritance and overriding concepts are not applicable.But
overloading concept is applicable.

Every class in java including abstract class can contain constructor but interface can’t
contain constructor.

Note:Every variable present in interface is always static.


EX:
Case 1:

Recursive method call is a runtime exception saying “StackOverflowError”.But in our


program if there is a chance of recursive constructor invocation then the code wan’t
compile and we will get compile time error.

EX:

Case 2:

Ex:
Note:
1)If parent class contains any argument constructor then while writing child classes
we have to take special care with respect to constructors.
2)** When ever we are writing any argument constructor to write no argument
constructor also.

Case 3:

Ex:
Note:
If parent class constructor throws any checked exception compulsory child class
constructor should throw the same checked exception or its parent.Other wise the
code wan’t compile.

Which are the following is vallid:


1)The main purpose of constructor is to create an object //invalid
2)The main purpose of constructor is to perform initialization of an object //valid
3)The name of the constructor need not be same as class name //invalid
4)Return type concept applicable for constructor but only void //invalid
5)We can apply any modifier for constructor
//invalid(public ,private,protected,default)
6)Default constructor is generate by JVM //invalid
7)Compiler is responsible to generate default constructor.//valid
8)Compiler will always generate constructor //invalid.
9)If we are not writing no arg constructor then compiler will generate default
constructor //invalid
10)Every no arg constructor is always default constor //invalid (compiler generated
constructor is default constructor )
11)Default contructor is always no arg constructor.//true or valid
12)The first line inside every constructor should be either super or this.If we are not
writing any thing then compiler will generates this().//false or invalid
13)For constructor both overloading and constructors are applicable.//false or
invalid
14)For constructors inheritance concept applicable but not overriding.//invalid
15)Only concrete classes can contain constructor but abstract can’t //invalid
(abstract classes can contain constructors)
16)Interface can contain constructors//invalid.
17)Recursive constructor invocation is a runtime exception//invalid
18)If parent class constructor throws some checked exception then compulsory child
class should throw same checked exception or its child class exceptions//invalid(not
child need to throw parent exceptions).

Var arg:

we can override var arg method with another var arg method only.If we are trying to
override with normal method then it will become overloading but not overriding.
In the above program if we replace child method with var arg method then it will
become overriding.In this case o/p: parent,child,child.

overriding with respect to variables:


-------------------------------------
variable resolution always takes care by compiler based on reference type
irrespective of weather the variable is static or non static(overriding concept is
applicable only for methods but not for variables).

Difference between overloading and overriding:


Consider the following methods in parent class:

Which are the following methods we can take in child class


Polymorphism:

One name but multiple forms is the concept of polymorphism.


Ex:method name is same but we can apply different types of arguments is called
overloading
Ex:method signature is same but in parent class one type of implemantation and in
child class another type of implementation.

Ex: use of parent reference to hold child object is the concept of polymorphism.
Parent class reference can be used to hold child object but by using that reference
we can call the methods available in parent class and we can’t call child specific
methods.

Has-A Relation Ship:


--------------------
1)Has-A relation ship is also know as composition/aggrigation.
2)There is no specific key word to implement has a releation.But most of the time we
are depending on new keyword.
3)The main advantage of has-a relation ship is reusability of the code.
Difference between composition and aggrigation:
-----------------------------------------------
With out existing container object if there is no chance of existing contained objects
then container and contained objects are strongly associated and this strong
association is nothing but composition.

Ex:University consist of several departments with out existing university there is no


chance of existing department.Hence university and department are strongly
assoicated and this storng association is nothing but composition.

With out existing container object if there is a chance of existing contained objects
then container and contained objects are weekly associated and this week
association is nothing but aggrigation.

Ex: Department consists of several profesors.with out existing department there may
be a chance of existing profisers object.Hence department and professors objects
are weekly associated and this week assoication is nothing but aggriation.
Note:1) In composition objects are strongly associated where as in aggregation
objects are weekly assoicated.

2)In composition container object holds directly contained objects where as in


aggregation container objects holds just references of contained objects.

Is-A Vs Has-A

If we want total functionality of a class automatically then we should go for is-a


relation ship.
Ex:
If we want part of the functionality then we should go for Has-a relation ship.
Ex:
Difference between instance block and static block

What is cohersion

Higher and Lower cohersion.


In Lower cohersion we will maintain all the logic in one class.Where as in Higher
cohersion we will maintain multiple classes for each and logic like as
DB ,Logger,Bussiness Logic.

What is coupling

Tight coupling and loose coupling

Tight coupling is nothing but we will create the object of other class with new key
word.
Loose coupling is nothing there will be one class which act as container to decide
which class object need to create at run time.And that object will be created.Like as
in spring we are having containers to take care of creating objects.

What is type casting

Assigning a value of one type to a variable of another type is known as Type Casting.

Difference between implicit casting and explicit casting


Implicit Casting
Automatic Type casting take place when,

 the two types are compatible

 the target type is larger than the source type

Explicit Casting
When you are assigning a larger type value to a variable of smaller type, then you
need to perform explicit type casting.
Type casting example in Java

In this Example of type casting in Java, we have two classes, Base,


and Derived. Derived class extends Base i.e. Base is a Super class and
Derived is a Subclass. So their type hierarchy looks like the following tree :

Base
|
Derived

Now look at following code :

Base b = new Derived(); //reference variable of Base class


points object of Derived class
Derived d = b; //compile time error, requires casting
Derived d = (Derived) b; // type casting Base to Derived

Above code type casting object of a Derived class into Base class and it will
throw ClassCastExcepiton if b is not an object of the Derived class.
If Base and Derived class are not related to each other and doesn't part of
the same type hierarchy, the cast will throw compile time error. for example,
you can not cast String and StringBuffer, as they are not from same type
hierarchy.

Read
more: http://javarevisited.blogspot.com/2012/12/what-is-type-casting-in-j
ava-class-interface-example.html#ixzz4wtoZNl4r
Exception:
----------
An unexpected,unwanted event that disturbs normal flow of the program is called
exception.
EX:tired prunchred exception,sleeping exception,FilenotFound Exception.
It is highly recomaded to handle exceptions and the main objective of exception
handling is gracefull termination of the program.

Exception doesn't mean repearing an exception we have to provide alternative way


to continue rest of the program normally is the concept of Exception handling
For EX our programing requirment is to read the data from remote file locating at
london at run time if london file is not avaliable our program should not be
terminated abnormally.we have to provide some local file to continue rest of the
program normally.This way of defining alternative is nothing but exception handling.

Ex:try{
Read the data from remote file located at london.
}catch(FileNotFoundException e){
Use local file & continue rest of the program normally.
}

Runtime Stack Mechanism:


------------------------
For every thread jvm will create a runtime stack.Each and every method call
performed by that thread will be stored in the corresponding stack.Each entry in the
stack is called stack frame or activation record.After completing every method call
the corresponding entry from the stack will be removed.After completing all method
calls the stack will become empty. And that empty stack will be destroyed by JVM
just before terminating the thread.

Ex:class Test{
Psvm(){

Dostuff();
}
P s v doStuff(){
doMoreStuff();
}
P s v doMoreStuff(){
Sop(“hello”);
}
}
Default Exception Handling in java:
-----------------------------------
1)Inside a method if any exception occurs the method in which it is raised is
responsible to create exception object by including the following information.
1)name of exception
2)description of exception
3)location at which exception occurs.(stack trace)
2)After creating exception object method hand over that object to the jvm.
3)JVM will check weather the method contains any exception handling code or not.If
the the method doesn't contain exception handling code jvm terminates the method
abnormally and removes the corresponding entry from the stack.
4)Then JVM identifies caller method and checks weather caller method contains any
handling code or not.If the caller method doesn't contain handling code then jvm
terminates the caller method also abnormally and removes corresponding entry
from stack.This process will be continued until main().And if the main method also
doesn't contian handiling code then JVM terminates main method also abnormally
and removes coresponding entry from the stack.
5)Then JVM hand overs responsibility of exception handling to default exception
handler,which is the part of JVM.Default Exception Handler prints exception
information in the following format and terminates program abnormally.

Ex:Exception in thread xxx Name of exception : description


stack trace.
Ex:1

Ex:2
Note: In a program at-least one method terminates abnormally then the program
termination is abnormal termination.If all methods terminated normally then only
program termination is normal termination.

Throwable class acts as root for java exception hierachy.Throwable call defines two
child classes.
1)Exception :Most of the times exceptions are caused by our program and these are
recoverable for example if our programming requirment is to read data from remote
file locating at london at runtime if remote file is not availble then we will get run
time exception saying filenotfoundexception.If filenotfoundexception occurs we can
provide local file and continue the rest of the program normally
2)Error : Most of the time errors are not caused by our programs and these are due
to lack of system resources.Errors are non recoverable.For example
outofmemoryerror occurs being a programmer we can't do any thing and the
program will be terminated abnoramlly.And system admin are server admin is
responsible to increase heap memory.

Checked vs Unchecked:
---------------------
1)The exceptions which are checked by compiler for smooth execution of the
program at run time are called checked exception.
Ex:HallTicketMissingException,PenNotWorkingException.,etc.,
2)In our program if there is a chance of raising checked exception then compulsory
we should handle that checked exception(either by try catch or throws keyword)
otherwise we will get compile time error.
3)The exceptions which are not checked by compiler weather programmer handling
or not,such type of exceptions are called unchecked exceptions.
EX:ArthmaticException......,
Note:Weather it is checked or unchecked every exception occurs at runtime only
there is no chance of exception at compile time.

Note:Except Runtime and Error remaing all are checked exceptions.

Customized Exception Haning by try-catch:


-----------------------------------------
It is highly recomanded exceptions.The code which may rise an exception is called
risky code and we have to define that code inside try block.And corresponding
handling we have to define inside catch block.
try{

Risky code
}catch(Exception e){
Handling code
}

Control flow in try catch:


--------------------------
If an exception raised at catch block or after catch block then it is always abnormal
termination.
Note:
1)With in the try if any where an exception raised then rest of the try block won't be
excecuted even though we handle that exception.Hence with in the try block we
have to take only risky code and lenght of try block should be as less as possible.
2)In adition to try block there may be a chance of raising an exception inside catch
and finally blocks.
3)If any statement which is not part of try block and raises an exception then it is
always abnormal termination.

Methods to print exception information:


Throwable class defines the following mehtods to print exception information.
Try with multiple catch blocks:
-------------------------------
The way of handling an exception is varied from exception to exception.Hence for
exception type it is highly recomanded to take seperate catch block.Ie try with
multiple catch block is possible and recomanded to use.
Final:
------
1)Final is the modifier applicable for classes,methods and variables.If a class
decleared as final then we can't extend that class.i.e., we can't create child for that
class i.e.,Inheritance not possible for final classes.
2)If a method is final we can't override that method in child class.
3)If a variable decleared as final then we can't perform reassignment for that
variable.
Finally:
--------
Finally is a block always associated with try catch to maintain clean up code.The
speciality of finally block is it will be executed always irrespective of weather
exception is raised or not raised and weather handled or not handled.

Finalize:
---------
Finalize is a method always invoked by GC just before destroying an object to
perform clean up activities.Once finalize method completes immediatly GC destorys
that object.

NOTE:Finally block is responsible to perform clean up activites releated to try block


i.e., wat ever resources we opened as part of try block will be closed inside finally
block.
where as finalize method is responsible to perform clean up activites releated to
object i.e., wat ever resources associated with object will be deallocated before
destorying an object by using finalize method.

1)In try-catch-finally order is important.


2)When ever we are writing try compulsory we should write catch or finally other
wise we will get compile time error i.e., try with out catch or finally is invalid.
3)when ever we are writing catch block compulsory try block must be required i.e.,
catch with out try is invalid.
4)when ever we are writing finally block compulsory we should write try block.i.e.,
finally with out try is invalid.
5)Inside try, catch and finally blocks we can decleare try catch and finally blocks i.e.,
nesting of try catch finally is allowed.
6)for try catch finally blocks curly braces are mandatory.
throw:
------
Some time we can create exception object explicitly and hand over to the JVM
manually.For this we have to use throw key word.

throw new AE("/ by zero");

creation of AE explicitly and handover our created to the JVM manually.


Hence the main objective of throw key word is to hand over our created exception
object to the jvm manully.
NOTE: Best use of throw key word is user defined exception or customized
exceptions.

Unreachable statement.

throws:
-------
In our program if there is a possibility of rising checked exception then compulsory
we should handle that checked exception other wise we will get compile time error
saying "unreported exception xxx ; must be caught or decleared to be thrown".
Ex:1
Ex:2

By using try-catch:

By using throws keyword:


------------------------
We can use throws keyword to deligate responsibility of exception handling to the
caller(it may be another method or JVM) then caller method is responsible that
exception.

EX:
We can use throws keyword for methods and constructors but not for classes.

throws keyword requires only for checked exceptions and usage of throws keyword
for unchecked exceptions there is no use or impact.throws is required only to
convince compiler and usage of throws keyword doesn't prevent abnormal
termination of program.
Custom Exception handling:

Top 10 Exceptions:
------------------
Based on the person who is rising an exception all exceptions are divided into 2
categories:
1)JVM
2)Programatic

1)JVM:
------
The exceptions which are raised automatically by JVM when ever a particular event
occurs are called JVM Exceptions.
EX: AE,NPE,etc.,
2)Programatic:
--------------
The exceptions which are raised explicitly either by programmer or api developer to
indicate some thing goes wrong are called programatic exceptions
EX:TooOldException,IllegalArgumentException,etc.,

ArrayIndexOutofBoundsException:
-------------------------------
ClassCastException:when ever we are trying to cast parent to child class then we will
get ClassCastException.
Ex: String s = new String("durga");
Object o = (Object)s;
Ex: Object o = new Object();
String s = (String)o;
Ex: Object o = new String("durga");
String s = (String)o;

StackOverflowError:
-------------------
It is the child class of error and hence it is unchecked raised automatically by
JVM.When we are trying to perform recursive method call.

NoClassDefFoundError:
---------------------
It is the child class of error and hence it is unchecked.raised automatically by JVM
when ever JVM unable to find required .class file.
Ex: java Test
If Test.class file is not available then we will get Runtimeexception saying
"NoClassDefFoundError:Test"

ExceptionInInitializerError:
----------------------------
It is the child class of error and hence it is unchecked raised automatically by JVM.If
any exception occurs while executing static variables assignments and static blocks.

Java.lang.package:

For writing any java program weather it is simple or complex the most commanly
required class and interfaces are grouped into a package which is nothing but
java.lang package.
We are not required to import java.lang package explicitly because all classes and
interfaces present in lang package by default available to every java program.

The most commonly required methods for every java class(weather it is predefined
or customized class) are defined in a seperate class which is noting but object class.

Every class in java is the child class of object either directly or indirectly.So that
object class methods by default available to every java class.Hence object class is
consider as root of all java classes.

Note :
If our class doesn’t extend any other class then only our class is the direct child class
of object.
Ex:
If our class extends any other class then our class is indirect child class of object.

Conclusion:Either directly or indirectly java wont provide support for multiple


inheritance with respect to classes.

Object class defines the following 11 methods


Note : Strictly speking object class contains 12 methods the extra method is
registernatives.

Private static native void registerNativers();

THis method internally required for object class and not available to the child
classes .Hence we are not required to consider this method.

1)toString():

We can use toString() to get string representation of an object.

Ex: String s = obj.toString();

When ever we are trying to print object reference internally toString() is called.

Ex:

If our class doesn’t contain toString() then object class toString() is executed.

Ex:
Output:

In the above example object class toString() method executed which is implemented
as follows
Based on our requirement we can override toString() to provide our own string
representation.
For example we are trying to print student object reference to print his name and
roll number we have to override toString() as follows

In all wrapper classes , collection classes ,stringbuffer and string classes toString() is
overriden for meaning full string representation.Hence it is highly recomanded to
override toString() in our class also.
2)hashCode()

HashTable,HashMap,HashSet are best sutable for searching.Hashing is one type of


algorithm to perform searching.
1)Linear Search:O(n) search is done with all the elements.
2)Binary Search:0(log 2 pow n) search is done with less than and greater than
elements(starts from middle element/2)
3)Hashing:0(1)=> order of 1 by getting the hashcode it will get the element.

For every object a unique ids generated by JVM which is nothing but Hash code.Hash
code wont represent address of object.JVM will use hash code while saving object
into hashing related data structures like hashtable,hashmap,hashset....The main
advantage of saving object based on hash code is search operation will become very
easy.The most power full search algorithm upto today is hashing.

If we are giving chance to object class hash code() it will generate hashcode() based
on the address of the object.It doesn't mean hashcode() represents address of the
object.
Based on our requirement we can override hashcode() in our class to generate our
own hashcode.

Overriding hashcode() is said to be proper if and only if for every object we have to
generate a unique no as hashcode.

toString() vs hashCode()
------------------------
If we are giving chance to object class toString() it will internally calls hashCode().If
we are overriding toString() then our toString() may not call hashcode().
Ex 1,2,3

equals():

If our class doesn’t contain equals() then object class equals() will be executed.
Ex:
In the above example object class equals() got executed which is ment for reference
comparision(address compariosn) I.e., if two references pointing to the same object
then only .equals() returns true.
Based on our requirment we can override equals() for content comparision.
While overriding equals() for content comparision we have to take care about the
following

1)what is the meaning of equality(weather we have to check only names or roll


numbers or both)
2)If we are passing different type of object our equals() should not rise
ClassCastException I.e., we have to handle cce to return false;
3)If we are passing null argument then our equals() should not rise null pointer
exception.That is we have to handle NPE to return false;
The following is the proper way of overriding equals() for student class content
comparision

EX:
Main Example:

Simplified Version:
Note:To make above equals() more efficient then we have to write the following
code inside equals()

According to this if both references pointing to the same object then with out
performing any comparison .equals() return true directly.

In string class .equals() is overriden for content comparison hence,even though


objects are different if content is same then .equals() returns true.
In String Buffer .equals() is not overrident for content comparison hence,if objects
are different .equals() returns false even though content is same.

getClass():

We can use getClass() to get runtime class definition of an object


public final Class getClass()

By using this class class object we can access class level properties like fully qualified
name of the class and methods information and constructors information etc.,

EX:
Object o = new String("durga");
Class c = o.getClass();
sop(c.getName());
Method[] m = c.getDeclaredMethods();
for(Method m1 :m){
sop(m1.getName());
}

EX:to display database vendor specific connection interface implemented class


name.
Connection con = DriverManager.getConnection(,,,);
sop(con.getClass().getName());
Note:
1)After loading every .class file jvm will create an object of type java.lang.class in the
heap area.Programmer can use this class object to get class level information.
2)we can use getClass() very frequently in reflection.

finalize():
-----------
just before destorying an object gc class finalize() to perform clean up activities.once
finalize() completes automatically gc destroys that object.

wait,notify,notifyall:
----------------------
we can use this methods for inter thread communication.the thread which is
expceting updation,it is responsible to call wait method then immediatly the thread
will enter into waiting state.The thread which is responsible to perform
updation,after performing updation the thread can call notify().The waiting thread
will get that notification and continue its execution with those updates.

String

Case 1:

Once we create string object we can’t perform any changes in the existing object.If
we are trying to perform any changes with those changes a new object will be
created.This non changable behivor is nothing but immutability of string object.

S->durga.
S->durgasoftware. //eligible for GC
Once we create StringBuffer object we can perform any change in the existing
object.This changable behaviour is nothing but mutability of StringBuffer object.

Sb->durgasoftware.

Case 2:

In string class .equals() is overriden for content comparison.Hence even though


objects are different if content is same .equals() returns true.

In StringBuffer class .equals() is not overriden for content comparison.Hence object


class .equals() got executed which is ment for reference comparision.Due to this if
objects are different .equals() returns false even though content is same.

Case 3:
In the following image case two objects will be created 1 in the heap area and other
in scp.And s is always pointing to heap object.
In the following image case only one object will be created in scp and s is always
pointing to that object.

Note:
1)Object creation in scp is optional.First it will check is there any object already
present in scp with required content.If object already present then existing object
will be reused.If object not already available then only a new object will be created.
But this rule applicable for scp but not for the heap
2)GC is not allowed to access scp area hence even though object doesn’t contain
reference variable it is not elegible for gc if it is present in scp area.
All scp objects will be destroyed automatically at the time of jvm shut down.

When ever we are using new operator compulsory a new object will be created in
the heap area.Hence there may be a chance of existing two object with the same in
the heap area but not in scp.I.e.,duplicate objects are possible in the heap area but
not in scp.
Note:
1)For every string constant one object will be placed in scp area.
2)Because of some run time operation if an object is required to create that object
will be placed only in the heap area but not in scp area.
Methods in string class:
How to create our own immutable class

Final vs Immutable
we can use equals() to check equality of two objects.EX:obj1.equals(obj2).If our class
doesn't contains equals() then object class equals() will be executed.
EX:
Student s1 = new Student(10,"raja");
Student s2 = new Student(20,"raja1");
Student s3 = new Student(10,"raja2");
Student s4 = s1;
s1.equals(s2);//false
s2.equals(s3);//false because object class equals method will be executed where it is
reference comparision.
s4.equals(s1);//true

In the above example object class equals() got executed which is ment for reference
comparison(address) ie.,if two reference pointing to the same object then
only .equals() return true.based on our requirement we can override equals() for
content comparision.

While overriding equal() for content comparision we have to take care about the
following.
1)wat is the meaning of equality(weather we have to check only names or
rollnumber or both).
2)if we are passing different type of object our equals should not rise
classcastexception i.e.,we have to handle classcastexception to return false
3)if we are passing null as argument our equals method should not rise
NullPointerException i.e.,we have to handle nullpointerexception to return false.

the following is the proper way of overriding equals() for student class content
comparision.
public boolean equals(Object obj){
try{
String name1 = this.name;
int rollno1 = this.rollno;

Student s = (Student)obj;
String name2 = s.name;
int rollno2 = s.rollno;
if(name1.equals(name2)&& rollno1==rollno2){
return true;
}else{
return false;
}
}catch(ClassCastException c){
return false;
}catch(NullPointerException n){
return false;
}
}

equals() and hashCode()


-----------------------
object class equals() ment for reference comparision.For content comparision we
can override equals().
Relation between == and equals():
---------------------------------
1)if two objects are equal by == then this object are always equal by .equals()(i.e.,
if r1==r2 is true then r1.equals(r2) is always true).
2)if two object are not equal by == then we can't conclude anything about .eqauls() it
may return true or false.i.e., if r1!=r2 is false then r1.equals(r2) may be true or false.
3)If two object are equal by .equals() then we can't conclude about == operator it
may return true or false.i.e.,if r1.equals(r2) then we can't conclude about ==
operator it may return ture or false.
4)if two objects are not equal by .equals() then this objects are always not equal by
== operator.i.e.,if r1.equals(r2) is false then == is always false.

Difference b/w == and equals():


-------------------------------
To use == operator compulsory there should be some relation b/w argument
types(either parent to child or child to parent or same type) other wise we will get
compile time error saying incompatable types.If there is no relation b/w argument
types then .equals() won't rise any compile or run time errors,simply it returns false.

String s1 = new String("sai");


String s2 = new String("sai");
StringBuffer sb1 = new StringBuffer("sai");
StringBuffer sb2 = new StringBuffer("sai");
sop(s1==s2);//false
sop(s1.equals(s2));//true
sop(sb1==sb2);//false
sop(sb1.equals(sb2));//false
sop(s1==sb1);CE:Incompatable types
sop(s1.equals(sb1));//false

== and .equals()
1)== is an operator in java applicable for both primitive and object types.equals() is a
method in java applicable only for object types but not for primitives.
2)in the case of object references == operator ment for reference
comparision(address).by default .equals() present in object class ment for reference
comparision.
3)we can't override == operator for content comparison.we can override .equals()
method for content comparison.
4)to use == operator compulsory there should be some relation b/w argument types
we wil get compile time error saying incompatable types.if there is no releation
arguments types the .equals() wont raise any compile time errors and simple returns
false.

Answer in one line


------------------
In general we can use == for reference comparision and .equals() for content
comparision.

Note: for any object reference


r == null//false
r.equals(null)//false

ex:
Thread t = null;
sop(t == null)//false
sop(t.equals(null));//false

Note:Hashing releated datastructures follow the fundamental rule:two equalant


object should be placed in same bucket but all object present in the same bucket
need not be equal.

contract b/w .equals() and hashcode():47 min


--------------------------------------
1)If two object equal by .equals() then there hashcode() must be equal. ie.,two
equalant object should have same hashCode().If r1.equals(r2) then r1.hashCode()
and r2.hashCode() is always true.
2)Object .equals and hashcode() follow above contract,hence when ever we are
overriding .equals() compulsory we need to override hashcode() to satifiy above
contract.(equalent object should have same hash code).
3)if two object are not equal by .equals() then there is no restriction on hashCodes()
may be equal or may not be equal.
4)if hashcodes of two objects are equal then we can't conclude any thing
about .equals() it may returns ture or false.
5)if hashcodes of two object are not equal then this objects are not equal
by .equals().
***Note: to satisfy contract b/w equals() and hashcode() when ever we are
overriding .equals() compulsory we have to override hashcode() otherwise we won't
get any compile time error.but it is not a best pratice of program.

In string class .equals() is overriden for content comparision.And hence hashcode() is


also overriden to generate hashcode() based on content.

EX:String s1 = new String("durga");


String s2 = new String("durga");
sop(s1.equals(s2));//true
sop(s1.hashcode());//95950491
sop(s2.hashcode());//95950491

In stringbuffer .equals() is not overrident for content comparision.And hence


hashCode() is also not overriden.

EX:StringBuffer s1 = new StringBuffer("durga");


StringBuffer s2 = new StringBuffer("durga");
sop(s1.equals(s2));//false
sop(s1.hashcode());//95944491
sop(s2.hashcode());//95950491

String Class:
-------------
Ex:
String s1 = new String("you cannot change me!");//create object in heap and one
object scp(string constant pool)
String s2 = new String("you cannot change me!");//create object in heap.
sop(s1==s2);//false
String s3 = "you cannot change me!";
sop(s1==s3);//false its is stored in scp
String s4 = "you cannot change me!";
sop(s3==s4);//true its is stored in scp so both are equal
String s5 = "you cannot"+"change me!";
sop(s3==s5);//true at compile time the object is created at scp not in heap.Because
all constants are concatinated at compile time.
String s6 ="you cannot";//Stored at scp as new variable
String s7 = s6 + "change me!";
sop(s3 == s7);//false object is created at heap not in the heap.
final String s8 = "you cannot";
String s9 = s8+"change me!";
sop(s3==s9);//true//stored in scp.
sop(s6==s8);//true//stored in scp.

we can use intern() to get corresponding scp object reference by using heap object
reference.
by using heap object reference if we want to get scp object reference then we
should go for intern()
EX:String s1 = new String("durga");
String s2 = s1.intern();//here by using heap object reference we will get scp object s2
is refering to scp.
sop(s1==s2);//false
String s3 = "durga";
sop(s2==s3);//true both s2 and s3 are in scp so it returns true.

If the corresponding scp is not available then intern() will create the corresponding
scp object.
EX:
String s1 = new String("durga");//object is created in heap and scp
String s2 = s1.concat("software");//object is created in heap not in scp
String s3 = s2.intern();//object will be created in scp.
sop(s2==s3);//false
String s4 = "durgasoftware";//object is created in scp.
sop(s3==s4);//true

Importance of SCP:
------------------
In our program if a string object is repetedly required then is not recomanded to
create seperate for every requirment.because it creates performance and memory
problems.
Instead of creating a seperate object for every requirment we have to create only
one object and we can reuse the same object for every requirment so that
performance and memory utilization will be improved.This thing is possible because
of SCP.Hence the main advantage of SCP are memory utilization and performance
will be improved.
But the main problem with SCP is as several referances pointing to same object,by
using one reference if we are trying to change the content then remaining
references will be effected.To over come this problem Sun people implemented
String objects as immutable.i.e.,Once we create a string object we con't perform any
changes in the exiting object.If we are trying to perform any changes with those
changes a new object will be created.Hence SCP is the only reason for immutable of
String objects.

Wrapper Class:
--------------
The main objective of wrapper classes are
1)to wrap primitive into object from so that we can handle primitives also just like
objects.
2)to define several utility methods which are required for primitives.

Constructors:
------------
Almost all wrapper classes contains two constructors one can take coresponding
primitive as argument and other can take string as argument.
Ex:
Integer i = new Integer(10);
Integer i = new Integer("10");

Ex:
Double d = new Double(10.5);
Double d = new Double("10.5");

If string argument not representing a number then we will get runtime exception
saying numberformatexception
EX:Integer i = new Integer("ten");

Float class contains three constructors with float,double,string arguments.


Ex:
Float f = new Float(10.5f);
Float f = new Float("10.5f");
Float f = new Float(10.5);
Float f = new Float("10.5");

Character class contains only one constructor which can take char argument.
Ex:
Character ch = new Character('a');
Character ch = new Character("a");//CE:

Boolean class contains two constructors one can take primitive as argument and
other can take string argument.If we pass boolean primitive as argument the only
allowed values are true or false.where case is important and content is also
important.
Ex:
Boolean b = new Boolean(true);
Boolean b = new Boolean(false);
Boolean b = new Boolean(True);X
Boolean b = new Boolean(durga);X

Note: In all wrapper classes toString() to return content directly.In all classes .equals()
is overriden for content comparision.

Utility Methods:
----------------
1)valueof()
2)xxxValue()
3)parseXXX()
4)toString()

1)valueOf():
------------
we can use valueOf() methods to create wrapper object for the given string and
primitive.
Every wrapper class except character class contains a static valueOf() to create
wrapper object for the given string

public static wrapper valueOf(String s)

Integer i = Integer.valueOf("10");
Double d = Double.valueOf("10.5");
Boolean b = Boolean.valueOf("sai");

Every wrapper class including character class contains a static valueOf() to create
wrapper object for the given primitive.
public static wrapper valueOf(primitive p)

Ex:
Integer i = Integer.valueof(10);
Character c = Character.valueOf('a');
Boolean b = Boolean.valueOf(true);

Primitive/String => valueOf() => Wrapper object

xxxValue():
-----------
we can use xxxvalue() to get primitive for the given wrapper object.

Every number type wrapper class Integer,Byte,Short,Long,Float,Double contains the


following 6 methods to get primitive for the given wrappper object.
public byte byteValue()
public byte shortValue()
public byte intValue()
public byte longValue()
public byte floatValue()
public byte doubleValue()

EX:
Integer i = new Integer(130);
sop(i.byteValue());
.
.
.
.
.
..

charValue():
character class contains charValue() to get char primitive for the given character.

public char charValue()

Ex:
Character ch = Character.valueOf('a');
char c = ch.charValue();
sysout(c);

booleanValue():
boolean class contains booleanValue() to get boolean primitive for the given boolean
object.

public boolean booleanValue()

Ex:
Boolean B = Boolean.valueOf("durga");
boolean b = B.booleanValue();
sop(b);//false

parseXXX:
---------
we can use parseXXX() to convert string to primitive.
Every wrapper class except character class contains the following parseXXX() to find
primitive for the given string object.
public static primitive parseXXX(String s);

Ex:
int i = Integer.parseInt("10");
double d = Double.parseDouble("10.5");
boolean b = Boolean.parseBoolean("true");

String

String Buffer:

Autoboxing and Auto UnBoxing:


Collections

An array is an indexed collection of fixed no of homogeneous data elements.The


main advantage of array is we can represent multiple value by using single
variable.So that redability of code will be increased.

Limitations of Array:
1)Arrays are fixed in size.I.e., once we create an array there is no chance of
increasing or decreasing the size based on our requirement.Due to this we use array
concept compulsory we should know the type in advance which may not possible
always.
2)Array can hold only Homogeneous data type elements only.
Ex:

We can solve this problem by using object type array.


Ex:

3)Arrays concept is not implemented based on some standard data structure.And


hence redeemed data support is not available.For every requirement we have to
write the code explicitly which increases complexity of the programming.
To over come above problems of array we should go for collections concept.

1)Collections are grow able in nature.I.e.,based on our requirement we can increase


or decrease the size.
2)Collections can hold both homogeneous and hetrogenous objects.
3)Every collection class is implemented based on some standard data
structure.Hence for every requirement redeemed data support is available.Being a
programmer we are responsible to use those methods we are not responsible to
implement those methods.

Difference between Arrays and Collections:

Collection:
If we want to represent a group of individual object as a single entity then we should
go for collection.

Collection Framework:
It contains several classes and interfaces which can be used to represent a group of
individual object as a single entity.

Java and c++

9key interfaces of collection framework

Collection(I):
1)If we want to represent a group of individual objects as a single entity then we
should go for entity.
2)Collection interface defines the most common methods which are applicable for
any collection object.
3)In general collection interface is consider as root interface of collection framework.

There is no concrete class which implements collection interface directly.

Difference between collection and collections


Collection is an interface if we want to represent a group of individual objects as a
single entity then we should go for collection.
Collections is an utility class present in java.util package to define several utility
methods for collection objects like sort(),……..

List(I)
It is the child inteface of collection.If we want to represent a group of individual
objects as a single entity where duplicates are allowed and insertion order must be
preserved then we should go for list.

Note: In 1.2v vector and stack are Re-engineered to implement list interface.

Set(I):
It is the child interface of collection if we want represent a group of individual object
as a single entity where duplicates are not allowed and insertion not required then
we should go for set interface.
Sorted Set:
It is the child interface of set If we want to represent a group of individual object as a
single entity where duplicates are not allowed and all objects should be inserted
according to some sorting order.

Navigable Set:
It is the child interface of sorted set it contains several methods for navigation
purposes.
Difference between list and set:

Queue(I):
It is the child interface of collection.If we want to represent a group of individual
objects prear to processing then we should go for queue.

Usually queue follows FIFO.But based on our requirement we can implement our
own priority order also.

EX:
Before sending a mail all mailids we have to store in some data structure in which
order we added mail ids in the same order only mail should be delivered for this
requirement queue is best choice.

Note :
All the above interfaces (collection,list,set,sorted set,navigable) ment for
representing a group of individual objects.If we want to represent a group of objects
key - value pairs then we should go for map

Map(I):
Map is not child interface of collection.If we want to represent a group of objects as
key value pairs then we should go for map.

Ex
Both key and value are objects only.But duplicate keys are not allowed but values
can be duplicated.

SortedMap:
It is the 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.
In sortedmap the sorting should be based on key but not based on value.

Navigable map:
It is the child interface of sorted map.It defines several methods for navigation
purposes.
Note:The following are legacy characters present in collection framework
Enumaration(I),Dictionay(AC),Vectory(C),Stack(C),Hashtable(C),Properties©.

Collection:
1)If we want to represent a group of individual objects as a single entity then we
should go for collection.
2)Collection interface defines the most common methods which are applicable for
any collection object.
Note: There is no concrete class which implements collection interface directly.

List:
1)List is child interface of collection
2)If we want to represent a group of individual object as a single entity where
duplicates are allowed and insertion order must be preserved then we should go for
list.
3)We can preserve insertion order with index.And we can differentiate duplicate
objects by using index.Hence index will play very important role in list.

List interface defines the following methods:


ArrayList(C):
Note:Except Tree set and Tree map every where heterogenous objects are allowed.

Constructors:

EX:
Usually we can use collections to hold and transfer objects from one location to
another location(container) to provide support for this requirement every collection
class by default implements serialize and clone able interfaces.

Array List and vector class implements Random Access interface.So that any random
element we can access with the same speed.

RandomAccess:
It is present in java.util package and doesn’t contain any methods.It is a marker
interface.where require ability will be provided automatically provided by jvm.

EX:
ArrayList is the best choice if our frequent operation is retrival operation.Because
arraylist implements random access interface.ArrayList is worst choice if our
frequent operation is insertion or deletion in the middle(because of shift operation).

Differences between Arraylist and vector:

How to get Synchronized version of ArrayList:


By default arraylist is non synchronized but we can get synchronized version of
arraylist object by using synchronizedList() of collections class.

Syntax:

EX:
Similarly we can get synchronized version of set and map objects.by using the
following methods of collections class.

Linked List:
1)The underlying data structure is double linked list
2)Insertion order is preserved.
3)Duplicates are allowed.
4)Heterogeneous objects are allowed.
5)Null insertion is possible.
6)Linked List implements serialize and clonable interface not random access.
7)Linked List is the best choice If our frequent operation is insertion or deletion in
the middle.
8)Linked List is the worst choice if our frequent operation is retrival operation

Constructors:
Linked list class specific mehtods:
Usually we can use linked list to develope stack and queues to provide support for
this requirment.Linked list class defines the following specific methods.

Ex:
Difference between ArrayList and LinkedList

2)In insertion/deletion AL is worst choice.And worst in retrival LL.

3)In AL the elements will store in consequtive memory locations and hence retrival
operation will become easy.In LL elements won’t be store in consequitve memory
locations and retrival operation will become difficult or complex.

Vector:
Constructors:
Methods:
EX:

Stack:
It is the child class of vector.It is a specially designed class for LIFO order.

Constructor:
Stack s = new Stack();

Methods:
EX:
The 3 Coursers of java
If we want to get objects one by one from the collection then we should go for
cursor.There are three types of cursors available in java.
1)Enumaration
2)Iterator
3)ListIterator.

Enumaration:
We can use enumaration to get objects one by one from legacy collection object.
We can create enumaration object by using elements method of vector class.

Public Enumeration elements()


Ex:
Enumeration e = v.elements();

Public boolean hasMoreElements()


Public Object nextElement()
Ex:

Limitations of Enumaration:
1)We can apply enumaration concept only for legacy classes.And it is not a universal
cursor.
2)By using enumaration we can get only read access and we can’t perform remove
operation.
To over come above limitations we should go for iterator.

Iterator(I):
1)We can apply iterator concept for any collection object.And hence it is universal
cursor.
2)By using iterator we can perform both read and remove operations.
Ex: on Iterator
Limitations of Iterator:
1)By using enumaration and iterator we can always move only towards forward
direction and we can’t move towards backward direction.These are single directions
cursors but not bi directional cursors.
2)By using iterator we can perform only read and remove operations and we can’t
perform replacement and addition of new objects.
To over come above limitations we should go for list iterator.

ListIterator(I):
1)By using list iterator we can move either to the forward or backward direction.And
hence it is by directional cursor.
2)By using list iterator we can perform replacement and addition of new objects in
addition to read and remove operations.
List iterator is the child interface of iterator.And hence all methods present in
iterator by default available to the list iterator.

List Iterator contains 9 methods:

The most power full cursor is list iterator but its limitation is applicable only for list
objects.

Comparison table of three cursors:


Set:
1)Set is child interface of collection.
2)If we want to represent a group of individual objects as a single entity where
duplicates are not allowed and insertion order not preserved.
3)Set interface any new methods and we have to use only collection interface
methods.

HashSet:
1)The underlying datastructure is hash table
2)Duplicate objects are not allowed.
3)Insertion order is not preserved and it is based on hashcode of objects.
4)Null insertion is possible.
5)Heterogenous objects are allowed.
6)Implements serializable and clonable interfaces but not randomaccess interfaces.
7)HashSet is best choice if our frequent operation is search operation.

Note:In hashset duplicates are not allowed if we are trying to insert duplicates then
we wan’t get any compile time or run time errors.And add() simply returns false.

Ex:
HashSet h = new HashSet();
Sop(h.add(“A”));//true
Sop(h.add(“A”));//false

Constructors:
Fill Ratio/Load Factor:

After filling how much ratio a new hashset object will be created,this ratio is called
load factor.For example fill ratio 0.75 means after filling 75% ratio a new hash set
object will be created.

EX:
LinkedHashSet:
1)It is the child class of hash set.
2)It is exactly same as hashset(Including constructors and methods) except the
following differences.

In the above program if we replace hashset with linkedhashset the o/p:is


In general we can use LinkedHashSet to develope cache based applications where
duplicates are not allowed and insertion order preserved.

SortedSet:
1)Sorted set is the child interface of set.
2)If we want to represent a group of individual objects according to some sorting
order with out duplicates then we should go for shorted set.
3)

Tree Set:
1)Underlying data structure is balanced tree
2)Duplicate objects are not allowed
3)Insertion order not preserved.
4)Heterogenous objects are not allowed.Other wise we will get run time exception
saying class cast exception
5)Null insertion possible only once.
6)Tree set implements serialize and clonable but not random access interface.
7)All objects will be inserted based on some sorting order.it may be default sorting
order or customized sorting order.

Constructors:

Ex:
Null Acceptance:
1)For non empty tree set if we are trying to insert null then we will get null pointer
exception.
2)For empty tree set as a first element null is allowed but after inserting that null if
we are trying to insert any other then we will get run time exception saying null
pointer exception.

**Until 1.6v null is allowed as the first element to the empty tree set,but from 1.7v
onwards null is not allowed even as the first element I.e.,”null” such type of story is
not applicable from 1.7v onwards.
Ex:2

Ex:3
If we are depending on default natural sorting order compulsory the objects should
be homogenous and comparable otherwise we will get run time exception saying
CCE.
An object is said to be comparable if and only if corresponding class implements
comparable interface.String class and all wrapper classes already implement
comparable interface.But stringbuffer class don’t comparable interface.Hence we
got CCE in the above example.

Comparable(I):
1)It is present in java.lang package.And it contains only one method compareTo()

Ex:
If we are depending on natural sorting order then while adding objects in to the tree
set jvm will call compareTo().

If default natural sorting order is not available or if we are not satisfied with default
natural sorting order then we can go for customized sorting by using comparator.
Comparator:
1)Comparator present in java.util package.And it defines to methods compare() and
equals().

When ever we are implementing comparator interface compulsory we should


provide implementation only for compare() and we are not required implementation
for equals() because it is already available to our class from object class through
inhertance.

Write a program to insert integer objects in to the tree set where the sorting order is
descending order

Ans:
At line 1 if we are not passing comparator object then internally jvm will call
compareTo() which is ment for default natural sorting order.In this clase o/p is
0,5,10,15,20

At line 1 if we are passing comparator object then jvm will call compare() which is
ment for customized sorting.In this case o/p is 20,15,10,5,0

Various implementations of compare():


Write a program to insert string objects in the tree set where all elements should be
inserted according to reverse of alphabetical order.
Input:

Write a program to insert stringbuffer object into the tree set where sorting order is
alphabatical order.
Input:

If we are depening on default natural sorting order compulsory objects should be


homogenous and comparable other wise we will get run time exception saying CCE.

If we are defineing our own sorting by comparator then objects need not to be
comparable and homogenous I.e., we can add heterogenous non comparable
objects also.

Write a program to insert string and stringbuffer object in to treeset where sorting
order is increasing length order.If two objects having same length then consider
there alphabatical order.
Comparable vs comparator:

1)For predefined comparable classes default natural sorting order already


available.If we are not satisfied with that default natural sorting order then we can
define our own sorting by using comperetor.
2)For pre defined non comparable classes(like string buffer) default natural sorting
order not already available.we can define our own sorting by using comparator.
3)For our own classes like employee,the person who is writing the class is
responsible to define default natural sorting order by implementing comparable
interface.The person who is using our class,if he is not satisfied with default natural
sorting order then he can define his own sorting by using comparator.

Ex:
Comparison of comparable and comparator:

S-ar putea să vă placă și