Documente Academic
Documente Profesional
Documente Cultură
There are four principle concepts upon which object oriented design and
programming rest. They are:
Abstraction
Polymorphism
Inheritance
Encapsulation
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
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:
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.
Encapsulation:
--------------
The process of binding data and corresponding methods into a single unit is nothing
encapsulation.
ex:class student{
}
If any component follows data hiding and abstraction such type of component is said
to be Encapsulation.
Encapsulation = Data hiding + Abstraction.
Class Account{
//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{
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.
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.
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.
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.
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.
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:
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.
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:
EX:
Note:The main advantage of this approch is we can stop the availibility of parent
implemantation to the next level child classes.
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.
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.
Default Constructor:
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.
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.
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.
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.
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.
Is-A Vs Has-A
What is cohersion
What is 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.
Assigning a value of one type to a variable of another type is known as Type Casting.
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
Base
|
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.
Ex:try{
Read the data from remote file located at london.
}catch(FileNotFoundException e){
Use local file & continue rest of the program normally.
}
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: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.
Risky code
}catch(Exception e){
Handling code
}
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.
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:
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.
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():
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()
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
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.
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());
}
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:
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;
}
}
== 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.
ex:
Thread t = null;
sop(t == null)//false
sop(t.equals(null));//false
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");
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
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);
xxxValue():
-----------
we can use xxxvalue() to get primitive for the given wrapper object.
EX:
Integer i = new Integer(130);
sop(i.byteValue());
.
.
.
.
.
..
charValue():
character class contains charValue() to get char primitive for the given character.
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.
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:
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:
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.
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.
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.
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).
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
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.
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.
The most power full cursor is list iterator but its limitation is applicable only for list
objects.
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.
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().
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
Write a program to insert stringbuffer object into the tree set where sorting order is
alphabatical order.
Input:
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:
Ex:
Comparison of comparable and comparator: