java notes core

Upload: sharath-mudhigonda

Post on 26-Feb-2018

279 views

Category:

Documents


7 download

TRANSCRIPT

  • 7/25/2019 Java Notes Core

    1/154

    Overview of Java

    Java is one of the world's most importantand widely used computer languages, and ithas held this distinction for many years.Unlike some other computer languageswhose influence has weared with passage oftime, while java's has grown.

    Till today it is the first and best choice fordeveloping console/webbased applications.

    Creation of Java

    Java was developed by James !hosling,"atrick #aughton, $ike %heridan at %un$icrosystems &nc. in ((. &t took )months to develop the first working version.

    The initial name was Oakbut was renamedto Javain ((*.

    Evolution of Java

    Java was initially launched as Java .+ butsoon after its initial release, Java . waslaunched. Java . redefined event handling,new library elements were added.

    &n Java 1.2%wing and ollection

    framework was added and suspend(),resume()and stop()methods were

    deprecated from Threadclass.

    #o major changes were made into Java 1.3but the ne-t release that was Java 1.4contained several important changes.

    eyword assert, chained e-ceptions and

    channel based &/ %ystem was introduced.

    Java 1.5was called J2SE 5, it added

    following major new features 0

    !enerics

    1nnotations

    1utobo-ing and autounbo-ing

    2numerations

    3oreach 4oop

    5arargs

    %tatic &mport

    3ormatted &/

    oncurrency utilities

    #e-t major release was Java SE 7which

    included many new changes like 0

    #ow Stringcan be used to control

    %with statement.

    $ulti atch 2-ception

    try-with-resourcestatement

    6inary &nteger 4iterals

    Underscorein numeric literals.

    Ali!ation of Java

  • 7/25/2019 Java Notes Core

    2/154

    Java is widely used in every corner of worldand of human life. Java is not only used insoftwares but is also widely used indesigning hardware controlling softwarecomponents. There are more than (7+

    million J82 downloads each year and 7billion mobile phones run java.

    3ollowing are some other usage of Java 0

    . 9eveloping 9esktop 1pplication

    :. ;eb 1pplications like 4inkedin

    7. $obile % like 1ndroid

  • 7/25/2019 Java Notes Core

    3/154

    6inary &nteger 4iterals

    Underscorein numeric literals.

    Ali!ation of Java

    Java is widely used in every corner of worldand of human life. Java is not only used insoftwares but is also widely used indesigning hardware controlling softwarecomponents. There are more than (7+million J82 downloads each year and 7billion mobile phones run java.

    3ollowing are some other usage of Java 0

    . 9eveloping 9esktop 1pplication

    :. ;eb 1pplications like 4inkedin

    7. $obile % like 1ndroid

  • 7/25/2019 Java Notes Core

    4/154

    Ste 30 lick on 2nvironment 5ariablesbutton.

    Ste 40 #ow alter the path variable so that italso contains the path to J9 installeddirectory.

  • 7/25/2019 Java Notes Core

    5/154

    3or e.g0 hange C/0window%( %%te$ 32.to C/0window%(%%te$ 32 C/0rogra$file% ( Java( J"#.

    Setting u ath for window 5(-(E

    1ssuming that you have installed Java in0@program files@ java@ J9 directory, do the

    following0

    Ste 10 2dit the C/0autoee!.6atfile andadd the following line at the end.

    SET PATH =% PATH% C:\ PROGRAMFIE!"A#A!"$!&'n

    Setting u ath for inu , 8ni , Solari%,

    free 9S"

    1ssuming that you have installed Java in0@program files@ java@ J9 directory, do thefollowing0

    Ste 10 2nvironment variable path should beset to point where java binaries have beeninstalled. 8efer to your shell if you havetrouble doing this.

    :or Ea$le/&f you use bash as your shell,then you would add following line to the end

    &as m: e*port PATH=! Pat!to!+a,a

    +hat i% J;. 9efault value Dero.e-ample0 &2te &=96

    %hort /&t is E bit integer data type. 5aluerange from 7:>E) to 7:>E>. 9efault valueDero. e-ample0 sort s=996

    int /&t is 7: bit integer data type. 5alue

    range from ::,+7E,)*>*,)+>. 9efault valueDero. e-ample0 -on/ -=99;6

    :loatingB*oint >u$6er

    This group includes 8-oat,dou&-e

    float /&t is 7: bit float data type. 9efaultvalue +.+f. e-ample0 8-oat 88=93

  • 7/25/2019 Java Notes Core

    9/154

    2 >onB*ri$itive&eferen!e "ata te

    1 reference data type is used to refer to an

    object. 1 reference variable is declare to beof specific and that type can never bechange. ;e will talk a lot more aboutreference data type later in lasses andbject lesson.

    ?dentifier

    1ll Java components reBuire name. #ame

    used for classes, methods, interfaces andvariables are called &dentifier. &dentifiermust follow some rule. Aere are the rules0

    1ll identifier must start with either a

    letter= a to D or 1 to F ? or currencycharacter=G? or an underscore.

    1fter the first character,an identifier

    can have any combination ofcharacter

    1 keyword cannot be used as an

    identifier.

    &dentifiers in Java are case sensitive,

    foo and 3oo are two differentidentifier.

    Te Ca%ting

    1ssigning a value of one type to a variableof another type is known as Te Ca%ting.

    Ea$le /

    'nt * = 96&2te 2 = (&2te)*6

    &n Java, type casting is classified into twotypes,

    ;idening asting=&mplicit?

    #arrowing asting=2-plicitly done?

    +idening or Auto$ati! te !onverion

    1utomatic Type casting take place when,

    the two types are compatible

    the target type is larger than the

    source type

    Ea$le /

    pu&-' -ass Test.

    pu&-' stat' ,o'd ma'n(Str'n/01ar/s) . 'nt ' = 96 -on/ - = '6 //no explicittype casting required

    8-oat 8 = -6 //no explicittype casting required

  • 7/25/2019 Java Notes Core

    10/154

    S2stem3out3pr'nt-n(4Int ,a-ue4>')6 S2stem3out3pr'nt-n(4on/ ,a-ue4>-)6 S2stem3out3pr'nt-n(4F-oat,a-ue 4>8)6 7

    7

    utput 0

    Int ,a-ue 9on/ ,a-ue 9F-oat ,a-ue 93

    >arrowing or Eli!it te !onver%ion

    ;hen you are assigning a larger type valueto a variable of smaller type, then you needto perform e-plicit type casting.

    Ea$le /

    pu&-' -ass Test. pu&-' stat' ,o'd ma'n(Str'n/01ar/s) . dou&-e d = 93?6

    -on/ - = (-on/)d6 //explicittype casting required

    'nt ' = ('nt)-6 //explicittype casting required

    S2stem3out3pr'nt-n(4$ou&-e,a-ue 4>d)6 S2stem3out3pr'nt-n(4on/ ,a-ue4>-)6 S2stem3out3pr'nt-n(4Int ,a-ue4>')6

    7

    7

    utput 0

    $ou&-e ,a-ue 93?on/ ,a-ue 9Int ,a-ue 9

    ;aria6le

    Java "rogramming language defines mainly

    three kind of variables.

    . &nstancevariables

    :. %tatic5ariables

    7. 4ocal5ariables

    1 ?n%tan!e varia6le%

    &nstance variables are variables that are

    declare inside a class but outside anymethod,constructor or block. &nstancevariable are also variable of objectcommonly known as field or property.

    -ass Student.Str'n/ name6'nt a/e67

    Aere na$eand ageare instance variable of%tudent class.

    2 Stati! varia6le%

    %tatic are class variables declared with statickeyword. %tatic variables are initialiDed onlyonce. %tatic variables are also used indeclaring constant along with final keyword.

  • 7/25/2019 Java Notes Core

    11/154

    -ass Student.Str'n/ name6'nt a/e6stat' 'nt 'nst'tuteCode=99967

    Aere in%tituteCodeis a static variable. 2achobject of %tudent class will shareinstituteode property.

    3 o!al varia6le%

    4ocal variables are declared in methodconstructor or blocks. 4ocal variables areinitialiDed when method or constructor blockstart and will be destroyed once its end.4ocal variable reside in stack. 1ccessmodifiers are not used for local variable.

    8-oat /et$'sount('nt pr'e).8-oat d'sount6d'sount=pr'e@(;!9)6return d'sount67

    Aere di%!ountis a local variable.

    Arra

    1n array is a collection of similar data types.1rray is a container object that hold valuesof homogenous type. &t is also known asstatic data structure because siDe of an arraymust be specified at the time of itsdeclaration.

    1n array can be either primitive or referencetype. &t gets memory in heap area. &nde- of

    array starts from Dero to siDe.

    Arra "e!laration

    Snta /

    datatype[]identifier;or

    datatypeidentifier[];6oth are valid synta- for array declaration.6ut the former is more readable.

    Example :int[] arr;char[] arr;short[] arr;long[] arr;

    int[][] arr; //twodimensional array.

    ?nitialiDation

    newoperator is used toinitialiDed an array.

    Example :

    int[] arr=newint[10];!!9 's tes'e o8 arra23or

    int[]arr={10!0"0#0$0%;

    A!!e%%ing arra ele$ent

  • 7/25/2019 Java Notes Core

    12/154

    1s mention ealier array inde- starts from +.To access nth element of an array. %ynta-

    arrayname[n&1];

    Example :To access

  • 7/25/2019 Java Notes Core

    13/154

    7 77output'9;

  • 7/25/2019 Java Notes Core

    14/154

    SS right shift

    #ow lets see truth table for bitwise , Dand

    a 9 a 6 a F 6 a G 6+ + + + +

    + +

    + +

    +

    The bitwise shift operators shifts the bitvalue. The left operand specifies the value tobe shifted and the right operand specifies thenumber of positions that the bits in the valueare to be shifted. 6oth operands have the

    same precedence.Ea$le

    a = 9&= ;a &= 9a &= 9

    A%%ign$ent Oerator%

    1ssignment operator supported by Java areas follows

    oerator de%!rition ea$le

    Kassigns values fromright side operands toleft side operand

    aKb

    NKadds right operand tothe left operand andassign the result to left

    aNKb issame asaKaNb

    K

    subtracts right operandfrom the left operand

    and assign the result toleft operand

    aKb issame as

    aKab

    PK

    mutiply left operandwith the right operandand assign the result toleft operand

    aPKb issame asaKaPb

    /K divides left operandwith the right operand

    a/Kb issame as

    and assign the result toleft operand

    aKa/b

    QK

    calculate modulususing two operandsand assign the result to

    left operand

    aQKb issame asaKaQb

    i%! oerator

    There are few other operator supported byjava language.

    Conditional oerator

    &t is also known as ternary operator and used

    to evaluate 6oolean e-pression

    epr1 ( expr! ' expr"&f er1ondition is trueX Then value er20therwise value er3

    in%tan!eOf oerator

    Thi% oerator i% u%ed

    for o6@e!t referen!evaria6le%. The oerator!he!k% whether the

    o6@e!t i% of arti!ular

    te &!la%% te or

    interfa!e te

    O6@e!t and Cla%%e%

    %ince Java is an object oriented language,complete java language is build on classes

    and object. Java is also known as a %trongO6@e!t oriented rogra$$ing

    language=oops?.

  • 7/25/2019 Java Notes Core

    15/154

    "% is a programmingapproach which providessolution to problems with

    the help of algorithmsbased on real world. &tuses real world approachto solve a problem. %o objectoriented techniBue offers better and easyway to write program then proceduralprogramming model such as , 14!4,"1%14.

    ain :eature% of OO*S

    &nheritence

    "olymorphism

    2ncapsulation

    1bstraction

    9atahiding

    1s an object oriented language Javasupports all the features given above. ;ewill discuss all these features in detail later.

    Cla%%

    ?n Java everthing i%

    en!a%ulated under !la%%e%.

    lass is the core of Java language. lasscan be defined as a template/blueprint that describe the

    behaviors /states of aparticular entity. 1 classdefines new data type.ncedefined this new type can be used to create

    object of that type. O6@e!t i% an

    in%tan!e of !la%%. Hou $a

    al%o !all it a% h%i!al

    ei%ten!e of a logi!al

    te$late !la%%.1 class is declared using !la%%keyword. 1class contain both data and code that operateon that data. The data or variables definedwithin a !la%%are called in%tan!e varia6le%and the code that operates on this data isknown as $ethod%.

    ule% for Java Cla%%

    1 class can have only public or

    default=no modifier? access specifier.

    &t can be either abstract, final or

    concrete =normal class?.

    &t must have the class keyword, and

    class must be followed by a legalidentifier.

    &t may optionally e-tend one parent

    class. 6y default, it will e-tendjava.lang.bject.

  • 7/25/2019 Java Notes Core

    16/154

    &t may optionally implement any

    number of commaseparatedinterfaces.

    The class's variables and methods are

    declared within a set of curly braces.7.

    2ach .@avasource file may contain

    only one public class. 1 source filemay contain any number of defaultvisible classes.

    3inally, the source file name must

    match the public class name and itmust have a .java suffi-.

    A %i$le !la%% ea$le

    %uppose, %tudent is a !la%%and student'sname, roll number, age will be its property.4ets see this in Java synta-

    -ass Student3.

    Str'n/ name6'nt ro--no6'nt a/e67

    ;hen a reference is made to a particularstudent with its property then it becomes ano6@e!t, physical e-istence of %tudent class.

    Student std=ne Student()6

    1fter the above statement %tdisinstance/object of %tudent class. Aere the

    newkeyword creates an actual physicalcopy of the object and assign it to the %tdvariable. &t will have physical e-istence andget memory in heap area. The newoerator

    dna$i!all allo!ate% $e$or for an

    o6@e!t

    1 class can contain any of the followingvariable types.

    o!al varia6le% .variables definedinside methods,constructors or blocksare called localvariables. The variable will bedeclared and initialiDed within themethod and the variable will bedestroyed when the method hascompleted.

  • 7/25/2019 Java Notes Core

    17/154

    ?n%tan!e varia6le% .

    &nstance variablesare variables withina class but outsideany method.Thesevariables are instantiated when theclass is loaded. &nstance variablescan be accessed from inside anymethod, constructor or blocks of thatparticular class.

    Cla%% varia6le%.

    lass variables arevariables declaredwith in a class,outside any method,with the statickeyword.

    I. =ow a !la%% i% initialiDed in @avats3*>4 4>ts32)6 &3a--K2Re8erene(ts)6

    S2stem3out3pr'nt-n(4A8ter4>ts3*>4 4>ts32)6 7

    7

    Outut /

    Ke8ore 9 ;A8ter 9 L

    ethod overloading

    ?f two or $ore $ethod%

    in a !la%% have %a$e

    na$e 6ut differentara$eter%, it i% known

    a% $ethod overloading.

    ethod overloading i%

    one of the wa% through

    whi!h @ava %uort%

    ol$orhi%$. ethodoverloading !an 6e done

    6 !hanging nu$6er of

    argu$ent% or 6

    !hanging the data te of

    argu$ent%. &f two or more methodhave same name and same parameter list

    6ut differ% in return te are notsaid to beoverloaded method

    "ifferent wa% of ethod overloading

  • 7/25/2019 Java Notes Core

    20/154

    There are two different ways of methodoverloading

    ethod overloading 6 !hanging data

    te of Argu$ent%

    Example :

    -ass Ca-u-ate.,o'd sum ('nt aB 'nt &). S2stem3out3pr'nt-n(4sum 's4>(a>&))67,o'd sum (8-oat aB 8-oat &). S2stem3out3pr'nt-n(4sum 's4>

    (a>&))67Pu&-' stat' ,o'd ma'n (Str'n/01ar/s). Ca-u-ate a- = ne Ca-u-ate()6 a-3sum (BL)6 //sum+int aint ), is method is called3a-3sum (?3NB (-@&)) 67,o'd 8'nd('nt -B 'nt &B'nt ). S2stem3out3pr'nt-n(4Area 's4>(-@&@))67pu&-' stat' ,o'd ma'n (Str'n/01ar/s). Area ar = ne Area()6 ar38'nd(BL)6 //find+int lint ), is method is called3ar38'nd(?BNB;)6 //find+int l

    int )int h, is called377

    Outut/

    Area 's ?Area 's ?

    &n this e-ample the find=? method isoverloaded twice. The first takes twoarguments to calculate area, and the secondtakes three arguments to calculate area.

    ;hen an overloaded method is called java

    look for match between the arguments tocall the method and the method'sparameters. This match need not always bee-act, sometime when e-act match is notfound, Java automatic type conversion playsa vital role.

    Ea$le of ethod overloading with te

    ro$otion.

    -ass Area.,o'd 8'nd(-on/ -B-on/ &). S2stem3out3pr'nt-n(4Area 's4>(-@&)) 67,o'd 8'nd('nt -B 'nt &B'nt ).

  • 7/25/2019 Java Notes Core

    21/154

    S2stem3out3pr'nt-n(4Area 's4>(-@&@))67pu&-' stat' ,o'd ma'n (Str'n/01ar/s). Area ar = ne Area()6 ar38'nd(BL)6 //automatic typecon*ersion from find+intint, tofind+longlong, 3ar38'nd(;B?BN) //find+int l

    int )int h, is called377

    Outut/

    Area 's ?Area 's ?

    Con%tru!tor% in Java

    A !on%tru!tor i% a %e!ial

    $ethod that i% u%ed to

    initialiDe an o6@e!t.Ever

    !la%% ha% a !on%tru!tor,if we

    dont eli!itl de!lare a!on%tru!tor for an @ava

    !la%% the !o$iler 6uild% a

    default !on%tru!tor for that

    !la%%. A !on%tru!tor doe%

    not have an return te.

    A !on%tru!tor ha% %a$e

    na$e a% the !la%% in whi!hit re%ide%. Con%tru!tor in

    Java !an not 6e a6%tra!t,

    %tati!, final or

    %n!hroniDed.These modifiers arenot allowed for constructor.

    -ass Car.

    Str'n/ name 6Str'n/ mode-6Car( ) //-onstructor. name =446 mode-=44677

    There are two te% of

    Con%tru!tor 9efault onstructor

    "arameteriDed

    constructor

    2ach time a new object is created at leastone constructor will be invoked.

    Car = ne Car() //efaultconstructor in*oedCar = ne Car(name)6//arameteried constructor in*oed

    Con%tru!tor Overloading

    4ike methods, a constructor can also beoverloaded. verloaded constructors aredifferentiated on the basis of their type of

    parameters or number of parameters.onstructor overloading is not muchdifferent than method overloading. &n caseof method overloading you have multiplemethods with same name but differentsignature, whereas in onstructoroverloading you have multiple constructorwith different signature but only difference

  • 7/25/2019 Java Notes Core

    22/154

    is that onstructor doesn't have return typein Java.

    I. +h do we Overload !on%tru!tor% name > 4 o8

    4>team677

    C-ass test:.pu&-' stat' ,o'd ma'n (Str'n/01ar/s). Cr'eter 9 = ne Cr'eter()6

    Cr'eter ; = neCr'eter(4sa'n4B 4Ind'a4B

  • 7/25/2019 Java Notes Core

    23/154

    .S2stem3out3pr'nt-n(4*=4>*)6

    77

    I. "oe% !on%tru!tor% return an valueOTE /$ultipleinheritance is notsupported in java

  • 7/25/2019 Java Notes Core

    33/154

    +h $ultile

    inheritan!e i% not

    %uorted in Java

    To re$ovea$6iguit.

    To rovide $ore

    $aintaina6le and

    !lear de%ign.

    %uer keword

    &n Java, superkeyword is used to refer toimmediate parent class of a class. &n other

    words %uer keword i%

    u%ed 6 a %u6!la%%

    whenever it need% to

    refer to it% i$$ediate

    %uer !la%%.

  • 7/25/2019 Java Notes Core

    34/154

    Ea$le of Child !la%% refering *arent

    !la%%propertyu%ing superkeword

    -ass arent. Str'n/ name6

    7pu&-' -ass -hilde*tends arent. Str'n/ name6 pu&-' ,o'd deta'-s() . super3name = 4Parent46//refers to parent class mem)er name = 4C'-d46

    S2stem3out3pr'nt-n(super3name>4 and4>name)6 7 pu&-' stat' ,o'd ma'n(Str'n/01

    ar/s) . C'-d o&+ = ne C'-d()6 o&+3deta'-s()6 77

    Outut

    Parent and C'-d

    Ea$le of Child !la%% refering *arent

    !la%%methodsu%ing superkeword

    -ass arent. Str'n/ name6 pu&-' ,o'd deta'-s() . name = 4Parent46 S2stem3out3pr'nt-n(name)6 77pu&-' -ass -hilde*tends arent. Str'n/ name6 pu&-' ,o'd deta'-s() .

    super3deta'-s()6//calling arent class

    details+, method name = 4C'-d46 S2stem3out3pr'nt-n(name)6 7 pu&-' stat' ,o'd ma'n(Str'n/01ar/s) . C'-d o&+ = ne C'-d()6 o&+3deta'-s()6 77

    Outut

    ParentC'-d

    Ea$le of Child !la%% !alling *arent

    !la%% constructoru%ing superkeword

    -ass arent.

    Str'n/ name6

    pu&-' Parent(Str'n/ n).

    name = n6 7

    7pu&-' -ass -hilde*tends arent. Str'n/ name6

  • 7/25/2019 Java Notes Core

    35/154

    pu&-' C'-d(Str'n/ n9B Str'n/n;)

    .

    super(n9)6 //passing

    argument to parent class constructor t's3name = n;6 7 pu&-' ,o'd deta'-s() .

    S2stem3out3pr'nt-n(super3name>4 and4>name)6 7 pu&-' stat' ,o'dma'n(Str'n/01 ar/s) . C'-d o&+ = neC'-d(4Parent4B4C'-d4)6

    o&+3deta'-s()6 77

    Outut

    Parent and C'-d

    Suer !la%% referen!e ointing to Su6

    !la%% o6@e!t.

    &n conte-t to above e-ample where lass 6e-tends class 1.

    A a=ne K()6

    is legal synta- because of &%1 relationshipis there between class 1 and lass 6.

    I. Can ou u%e 6oth thi%& and %uer& in

    a Con%tru!toraut3/etAutorame())677

    -ass Test.pu&-' stat' ,o'd ma'n(Str'n/ar/s01). Autor at=neAutor(4Me4B;;B4Ind'a4)6 Koo &=ne Koo(4"a,a4BLLBat)6 &3so$eta'-()6773utput'Koo 's "a,a3pr'e 's LL3Autor 's me3

    I. +hat i% Co$o%ition in @avaarelationship= 'secomposition with

    inter(aces.

    Summary

    I">A relationship ased onInheritance= which can e o( twot,pes Class Inheritance orInter(ace Inheritance.

    Bas>a relationship iscomposition relationship which

    is prod'ctive wa, o( code re'se.

    These terms signify the relationships

    between classes. These are the building

    blocks of object oriented programming and

    very basic stuff. 6ut still for some, these

    terms look like 4atin and !reek. Just wanted

    to refresh these terms and e-plain in simpler

    terms.

    Association

    1ssociation is a relationship between two

    objects. &n other words, association defines

    the multiplicity between objects. Cou may

    be aware of onetoone, onetomany, many

    toone, manytomany all these words define

    an association between objects. 1ggregation

    is a special form of association.

    omposition is a special form of

    aggregation.

    Example:1 %tudent and a 3aculty are

    having an association.

    Aggregation

    1ggregation is a special case of association.

    1 directional association between objects.

    ;hen an object [hasaZ another object, then

    you have got an aggregation between them.

    9irection between them specified which

    object contains the other object. 1ggregation

    is also called a \Aasa] relationship.

    Composition

    omposition is a special case of

    aggregation. &n a more specific manner, a

    restricted aggregation is called composition.

    ;hen an object contains the other object, if

    the contained object cannot e-ist without the

    e-istence of container object, then it is

    called composition.

    Example:1 class contains students. 1

    student cannot e-ist without a class. There

    e-ists composition between class and

    students.

    i

  • 7/25/2019 Java Notes Core

    41/154

    specifies, which object contains the other

    object.

    Example:1 4ibrary contains students and

    books. 8elationship between library and

    student is aggregation. 8elationship between

    library and book is composition. 1 student

    can e-ist without a library and therefore it is

    aggregation. 1 book cannot e-ist without a

    library and therefore its a composition. 3or

    easy understanding & am picking this

    e-ample. 9onZt go deeper into e-ample and

    justify relationshipsR

    Abstraction

    1bstraction is specifying the framework and

    hiding the implementation level information.

    oncreteness will be built on top of the

    abstraction. &t gives you a blueprint to

    follow to while implementing the details.

    1bstraction reduces the comple-ity by

    hiding low level details.

    Example: 1 wire frame model of a car.

    Generaliation

    !eneraliDation uses a \isa] relationship

    from a specialiDation to the generaliDation

    class. ommon structure and behaviour are

    used from the specialiDtion to the

    generaliDed class. 1t a very broader level

    you can understand this as inheritance. ;hy

    & take the term inheritance is, you can relate

    this term very well. !eneraliDation is also

    called a \&sa] relationship.

    Example:onsider there e-ists a class

    named "erson. 1 student is a person. 1

    faculty is a person. Therefore here the

    relationship between student and person,

    similarly faculty and person is

    generaliDation.

    Realiation8ealiDation is a relationship between the

    blueprint class and the object containing its

    respective implementation level details. This

    object is said to realiDe the blueprint class.

    &n other words, you can understand this as

    the relationship between the interface and

    the implementing class.

    Example:1 particular model of a car [!T6

    3ioranoZ that implements the blueprint of a

    car realiDes the abstraction.

    Dependency

    hange in structure or behaviour of a class

    affects the other related class, then there is a

    dependency between those two classes. &tneed not be the same viceversa. ;hen one

    class contains the other class it this happens.

    Example: 8elationship between shape and

    circle is dependency

    ethod Overriding

  • 7/25/2019 Java Notes Core

    42/154

    ;hen a method in a subclass has same name andtype signature as a method

    in its super class, then themethod is known asoverridden method. $ethodoverriding is also referred to as runtimepolymorphism. The key benefit ofoverriding is the abitility to define $ethodthat% %e!ifi! to a arti!ular %u6!la%%

    te.

    Ea$le of ethod Overriding

    -ass An'ma-.pu&-' ,o'd eat(). S2stem3out3pr'nt-n(4Gener' An'ma-eat'n/4)677

    -ass $o/ e*tends An'ma-.pu&-' ,o'd eat() !!eat() metodo,err'den &2 $o/ -ass3. S2stem3out3pr'nt-n(4$o/ eatmeat4)677

    1s you can see here 9og class gives it ownimplementation of eat=? method. $ethodmust have same name and same typesignature.

    >OTE /%tatic methods cannot beoverridden because, a static method isbounded with class where as instancemethod is bounded with object.

    Covariant return te

    %ince Java *, it is possible to override a

    method by changing its return type. ?f

    %u6!la%% override% an$ethod 6 !hanging the

    return te of %uer !la%%

    $ethod, then the return

    te of overriden $ethod

    $u%t 6e %u6te of return

    te de!lared in original

    $ethod in%ide the %uer!la%%. This is the only way by whichmethod can be overriden by changing itsreturn type.

    Example 0

    class 6nimal{6nimal my7ype+,

    { return new 6nimal+,;%%

    class og extends 6nimal{og my7ype+, //8egalo*erride after 9a*a$onward

    { return new og+,;%%

  • 7/25/2019 Java Notes Core

    43/154

    "ifferen!e 6etween Overloading and

    Overriding

    ethod

    Overloadingethod Overriding

    "arameter must bedifferent and namemust be same.

    6oth name andparameter must besame.

    ompile timepolymorphism.

    8untime polymorphism.

    &ncrease readabilityof code.

    &ncrease reusability ofcode.

    1ccess specifiercan be changed.

    1ccess specifier mostnot be more restrictivethan originalmethod=can be less

    restrictive?.

    I. Can we Override %tati! $ethod dened>

    package5> avapackage created ,'ser to categoriEedclasses andinter(ace

    Creating a package

  • 7/25/2019 Java Notes Core

    48/154

    reating a package in java is Buite easy.

    %imply include a package command

    followed by name of the package as the first

    statement in java source file.

    a!kage

    a!kagena$eL.%u6a!kage

    na$eLPP..MM

    paa/e m2pa6pu&-' -ass emp-o2ee.333statement67

    9he aove statement create a

    package called mypac!.

    Java uses file system

    directory to store package. 3or

    e-ample the 3-assfor any classes you todefine to be part of $a!kpackage must

    be stored in a directory called mypack

    $ample o( package creation

    paa/e m2pa-ass Koo.Str'n/ &ooname6

    Str'n/ autor6Koo(Str'n/ &B Str'n/ ). t's3&ooname = &6 t's3autor = 67pu&-' ,o'd so(). S2stem3out3pr'nt-n(&ooname>4 4>autor)6

    77

    -ass test.pu&-' stat' ,o'd ma'n(Str'n/01ar/s). Koo & = neKoo(4+a,a4B4Her&ert4)6 &3so()677

    9o r'n this program 5

    create a director, 'nder ,o'rc'rrent working developmentdirector,)i.e. G director,*=

    name it as mypac!.

    compile the so'rce le

    D't the class le into thedirector, ,o' have created.

    $ec'te the program (romdevelopment director,.

    >OTE /9evelopment directory is the

    directory where your J9 is install.

    ses o( Hava package

    "ackage is a way to organiDe files in java, it

    is used when a project consists of multiple

    modules. &t also helps resolve naming

    conflicts. "ackage's access level also allows

    you to protect data from being used by the

    nonauthoriDed classes.

    import ke,word

  • 7/25/2019 Java Notes Core

    49/154

    i$ortkeyword is used to import builtin

    and userdefined packages into your java

    source file. %o that your class can refer to a

    class that is in another package by directly

    using its name.

    There are 7 different ways

    to refer to class that is

    present in different

    package

    1."sing #ully$uali%ed name)F't this is not agood practice.*

    Example :

    -ass M2$atee*tends

    +a,a3ut'-3$ate.!!statement67

    2. import theonly class you

    &ant to useExample :

    'mport+a,a3ut'-3$ate6-ass M2$ate e*tends $ate.!!statement37

    ( import allthe classes#rom theparticular

    pac!age

    Example :

    importa*a.util.;-ass M2$ate e*tends $ate.!!statement6

    7

    import statement is kept a(ter the

    package statement.

    Example :

    paa/e m2pa6'mport +a,a3ut'-3@6

    6ut if you are not creating any package then

    import statement will be the first statementof your java source file.

    Jar ^cfv hello.jar mypack=folder?

  • 7/25/2019 Java Notes Core

    50/154

    %et classpathK.Md0@java>@hello.jar

    "tatic import

    %tati! i$ortis a feature that e-pands the

    capabilities of i$ortkeyword. &t is used to

    import %tati!member of a class. ;e all

    know that static member are referred in

    association with its class name outside the

    class. Using %tati! i$ort, it is possible to

    refer to the static member directly without

    its class name. There are two general form

    of static import statement.

    )he %rst #orm

    o# static importstatement*import only asingle staticmember o# a

    class

    Snta

    import staticpackage.class-

    name.static-

    member-name;

    Ea$le

    import statica*a.lang.>ath.sqrt; //importing

    static method sqrtof >ath class

    )he second #orm

    o# static importstatement*imports all the staticmember o# aclass

    Snta

    import staticpackage.class-

    type-name.*;

    Ea$le

    import statica*a.lang.>ath.; //importing all

    static mem)er of>ath class

    $ample witho't 'sing static import

    pu&-' -ass Test. pu&-' stat' ,o'd ma'n(Str'n/01ar/s) .

    S2stem3out3pr'nt-n(>ath.sqrt+1##,)6 77

    Outut

    9;

  • 7/25/2019 Java Notes Core

    51/154

    $ample 'sing static import

    import static a*a.lang.>ath.;pu&-' -ass Test. pu&-' stat' ,o'd ma'n(Str'n/01

    ar/s) .S2stem3out3pr'nt-n(sqrt+1##,)6 77

    Outut

    9;

    A6%tra!t !la%%

    &f a class contain anyabstract method then theclass is declared asabstract class. 1nabstract class is never

    instantiated. &t is used toprovide abstraction.1lthough it does not provide ++Qabstraction because it can also have concretemethod.

    Snta /

    a)stract class

    class?name { %

    A6%tra!t $ethod

    ethod that are

    de!lared without an

    6od within an a6%tra!t

    !la%% i% known a%a6%tra!t $ethod.Themethod body will bedefined by its subclass.1bstract method can never

    be final and static. 1ny classthat e-tends an abstract class must

    implement all the abstract methods declaredby the super class.

    Snta /

    a)stract return?typemethod?name+para?list,; // @odefinition

    Ea$le of A6%tra!t !la%%

    a&strat -ass A.a&strat ,o'd a--me()67-ass K e*tends A.,o'd a--me(). S2stem3out3pr'nt-n(4t's 's

    a--me34)67pu&-' stat' ,o'd ma'n(Str'n/01ar/s). K &=ne K()6 &3a--me()677output't's 's a--me3

  • 7/25/2019 Java Notes Core

    52/154

    A6%tra!t !la%% with !on!rete&nor$al

    $ethod.

    1bstract classes can also have normalmethods with definitions, along withabstract methods.

    a&strat -ass A.a&strat ,o'd a--me()6pu&-' ,o'd norma-(). S2stem3out3pr'nt-n(4t's 'sonrete metod4)677

    -ass K e*tends A.,o'd a--me(). S2stem3out3pr'nt-n(4t's 'sa--me34)67pu&-' stat' ,o'd ma'n(Str'n/01ar/s). K &=ne K()6 &3a--me()6 &3norma-()677output't's 's a--me3t's 's onrete metod3

    *oint% to e$e$6er

    . 1bstract classes are not &nterfaces.They are different, we will study thiswhen we will study &nterfaces.

    :. 1n abstract class must have anabstract method.

    7. 1bstract classes can haveonstructors, $ember variables and#ormal methods.

  • 7/25/2019 Java Notes Core

    53/154

    provide the implementation but it will hidethe actual implementation process.

    +hen to u%e A6%tra!t ethod% A6%tra!t Cla%%A#GJSPEE$4)67pu&-' stat' ,o'd ma'n (Str'n/01ar/). #e'-e , = ne #e'-e()6 ,3mo,e()6773utput'A,era/e speed 's ?3

    ?nterfa!e% %uort% ultile ?nheritan!e

    Though classes in java doesn't suppostmultiple inheritance, but a class canimplement more than one interface.

    'nter8ae Mo,ea&-e.&oo-ean 'sMo,ea&-e()67

    'nter8ae Ro--a&-e.&oo-ean 'sRo--a&-e7

    -ass T2re 'mp-ements Mo,ea&-eBRo--a&-e

    .'nt 'dt6

    &oo-ean 'sMo,ea&-e(). return true67

    &oo-ean 'sRo--a&-e(). return true67pu&-' stat' ,o'd ma'n(Str'n/

    ar/s01). T2re tr=ne T2re()6

    S2stem3out3pr'nt-n(tr3'sMo,ea&-e())6

    S2stem3out3pr'nt-n(tr3'sRo--a&-e())6773utput'

  • 7/25/2019 Java Notes Core

    55/154

    truetrue

    ?nterfa!e etend% other ?nterfa!e

    lasses implements interfaces, but aninterface e-tends other interface.

    'nter8ae esPaper.nes()67

    'nter8ae Ma/a'ne e*tends esPaper.o-or8u-()67

    "ifferen!e 6etween an

    interfa!e and an a6%tra!t

    !la%%OTE /&t is necessary for all e-ceptions,e-cept the e-ceptions of type Errorandunti$eE!etion, or any of theirsubclass.

    Ea$le de$on%trating throw% #eword

    -ass Test

    .stat' ,o'd e() trosAr'tmet'E*ept'on. S2stem3out3pr'nt-n(4Ins'de e8unt'on4)6 tro neAr'tmet'E*ept'on(4demo4)67

    pu&-' stat' ,o'd ma'n(Str'n/ar/s01). tr2 . e()6 7 at(Ar'tmet'E*ept'on e) . S2stem3out3pr'nt-n(4au/t4 > e)6 777

    finall !lau%e

    1 finally keyword is used to create a block

    of code that follows a try block. 1 finallyblock of code always e-ecutes whether ornot e-ception has occurred. Using a finallyblock, lets you run any cleanup typestatements that you want to e-ecute, nomatter what happens in the protected code.1 finally block appears at the end of catchblock.

  • 7/25/2019 Java Notes Core

    71/154

    Ea$le de$on%trating finall Clau%e

    C-ass E*ept'onTest.pu&-' stat' ,o'd ma'n(Str'n/01ar/s). 'nt a01= ne 'nt0;16 S2stem3out3pr'nt-n(4out o8 tr24)6 tr2.

    S2stem3out3pr'nt-n(4Aess'n,a-'d e-ement4> a0

  • 7/25/2019 Java Notes Core

    72/154

    overriden method cannot declare checkede-ception but it can declare uncheckede-ceptions.

    Ea$le of Su6!la%% overriden ethod

    de!laring Che!ked E!etion

    'mport +a,a3'o3@6-ass Super.,o'd so(). S2stem3out3pr'nt-n(4parent-ass4)6 77

    pu&-' -ass Su& e*tends Super

    .,o'd so() tros IOE*ept'on!!Comp'-e t'me error . S2stem3out3pr'nt-n(4parent

    -ass4)6 7

    pu&-' stat' ,o'd ma'n( Str'n/01ar/s ). Super s=ne Su&()6 s3so()677

    1s the method %how&doesn't throws anye-ception while in %uper class, hence itsoverriden version can also not throw anychecked e-ception.

    Ea$le of Su6!la%% overriden ethod

    de!laring 8n!he!ked E!etion

    'mport +a,a3'o3@6

    -ass Super.,o'd so(). S2stem3out3pr'nt-n(4parent-ass4)6 77

    pu&-' -ass Su& e*tends Super.

    ,o'd so() trosArra2Inde*OutO8KoundsE*ept'on!!Corret . S2stem3out3pr'nt-n(4'-d-ass4)6 7

    pu&-' stat' ,o'd ma'n(Str'n/01ar/s). Super s=ne Su&()6 s3so()677

    Output : '-d -ass

    6ecause#rray$ndex%ut%f&oundsExceptionis an unchecked e-ception hence, overrided%how&method can throw it.

    ore a6out Overriden ethod% and

    E!etion%

    &f %uper class method throws an e-ception,then %ubclass overriden method can throwthe same e-ception or no e-ception, butmust not throw parent e-ception of thee-ception thrown by %uper class method.

    &t means, if %uper class method throwsobject of >ull*ointerE!etionclass, then%ubclass method can either throw samee-ception, or can throw no e-ception, but itcan never throw object of E!etionclass=parent of #ull"ointer2-ception class?.

    Ea$le of Su6!la%% overriden $ethod

    with %a$e E!etion

    'mport +a,a3'o3@6-ass Super.,o'd so() tros E*ept'on. S2stem3out3pr'nt-n(4parent

    -ass4)6 77

  • 7/25/2019 Java Notes Core

    73/154

    pu&-' -ass Su& e*tends Super .,o'd so() tros E*ept'on!!Corret

    . S2stem3out3pr'nt-n(4'-d-ass4)6 7

    pu&-' stat' ,o'd ma'n(Str'n/01ar/s). tr2 . Super s=ne Su&()6 s3so()6 7 at(E*ept'on e).777

    Output : '-d -ass

    Ea$le of Su6!la%% overriden $ethod

    with no E!etion

    'mport +a,a3'o3@6-ass Super.,o'd so() tros E*ept'on. S2stem3out3pr'nt-n(4parent

    -ass4)6 77

    pu&-' -ass Su& e*tends Super .,o'd so()!!Corret

    . S2stem3out3pr'nt-n(4'-d-ass4)6 7

    pu&-' stat' ,o'd ma'n(Str'n/01ar/s). tr2 . Super s=ne Su&()6 s3so()6 7 at(E*ept'on e).777

    Output : '-d -ass

    Ea$le of Su6!la%% overriden $ethod

    with arent E!etion

    'mport +a,a3'o3@6-ass Super.

    ,o'd so() trosAr'tmet'E*ept'on. S2stem3out3pr'nt-n(4parent

    -ass4)6 77

    pu&-' -ass Su& e*tends Super .,o'd so() tros E*ept'on

    !!Cmp'-e t'me Error

    . S2stem3out3pr'nt-n(4'-d-ass4)6 7

    pu&-' stat' ,o'd ma'n(Str'n/01ar/s). tr2 . Super s=ne Su&()6 s3so()6 7 at(E*ept'on e).777

    O !oogle's 1ndriod perating %ystem isdeveloped on Java platform. O

    Chained E!etion

    hained 2-ception was added to Java inJ9 .

  • 7/25/2019 Java Notes Core

    74/154

    Two new constructors and two methodswere added to Throwa6leclass to supportchained e-ception.

    . Throwa6le= hrowable cause?

    :. Throwa6le= String str, hrowablecause?

    &n the first form, the paramter !au%especifies the actual cause of e-ception. &nthe second form, it allows us to add ane-ception description in string form with theactual cause of e-ception.

    getCau%e&and initCau%e&are the two

    methods added to Throwa6leclass.

    getCau%e&method returns the actual

    cause associated with currente-ception.

    initCau%e&set an underlying

    cause=e-ception? with invokinge-ception.

    Ea$le

    'mport +a,a3'o3IOE*ept'on6pu&-' -ass Ca'nedE*ept'on. pu&-' stat' ,o'd d','de('nt aB'nt &) . '8(&==) . Ar'tmet'E*ept'on ae = neAr'tmet'E*ept'on(4top -a2er4)6

    ae3'n'tCause( neIOE*ept'on(4ause4) )6 tro ae6 7 e-se . S2stem3out3pr'nt-n(a!&)6 7 7

    pu&-' stat' ,o'd ma'n(Str'n/01ar/s). tr2 . d','de(LB )6 7at(Ar'tmet'E*ept'on ae) .

    S2stem3out3pr'nt-n( 4au/t : 4>ae)6 S2stem3out3pr'nt-n(4atua- ause:4>ae3/etCause())6 777outputau/t:+a,a3-an/3Ar'tmet'E*ept'on: top -a2eratua- ause: +a,a3'o3IOE*ept'on:ause

    ?ntrodu!tion to ultithreading

    1 program can be dividedinto a number of small

    processes. 2ach smallprocess can be addressed

    as a single thread =alightweight process?.$ultithreaded programscontain two or morethreads that can runconcurrently. This meansthat a single program can

    perform two or more taskssimultaneously.3or e-ample, onethread is writing content on a file at thesame time another thread is performingspelling check.

  • 7/25/2019 Java Notes Core

    75/154

    &n Java, the word threadmeans twodifferent things.

    1n instance of Threadclass.

    or, 1 thread of e-ecution.

    1n instance of Threadclass is just anobject, like any other object in java. 6ut athread of e-ecution means an individualOlightweightO process that has its own callstack. &n java each thread has its own callstack.

    The mainthread

    2ven if you don't create any thread in yourprogram, a thread called $ainthread is stillcreated. 1lthough the $ainthread isautomatically created, you can control it byobtaining a reference to it by calling!urrentThread&method.

    Two important things to know about $ainthread are,

    &t is the thread from which other

    threads will be produced.

    $ainthread must be always the last

    thread to finish e-ecution.

    -ass Ma'nTread.pu&-' stat' ,o'd ma'n(Str'n/01

    ar/s). Tread t=Tread3urrentTread()6 t3setame(4Ma'nTread4)6 S2stem3out3pr'nt-n(4ame o8 tread's 4>t)677

    Output : ame o8 tread 'sTread0Ma'nTreadBLBma'n1

    ife !!le of a Thread

    . >ew /1 thread begins its life cyclein the new state. &t remains in thisstate until the start=? method is calledon it.

  • 7/25/2019 Java Notes Core

    76/154

    :. una6le /1fter invocation of start=?method on new thread, the threadbecomes runable.

    7. unning /1 method is in running

    thread if the thread scheduler hasselected it.

  • 7/25/2019 Java Notes Core

    77/154

    . ;hen we e-tend Thread class, wecannot override %et>a$e&andget>a$e&functions, because theyare declared final in Thread class.

    :. ;hile using %lee&, always handlethe e-ception it throws.

    static,o'd sleep(-on/milliseconds) trosGnterruptedHxception

    Creating a thread

    Java defines two ways by which a thread canbe created.

    6y implementing the unna6le

    interface.

    6y e-tending the Threadclass.

    ?$le$enting the unna6le ?nterfa!e

    The easiest way to create a thread is tocreate a class that implements the runnableinterface. 1fter implementing runnableinterface , the class needs to implement therun&method, which is of form,

    pu&-' oidrun()

    run=? method introduces a concurrent

    thread into your program. Thisthread will end when run=? returns.

    Cou must specify the code for your

    thread inside run=? method.

    run =? method can call other

    methods, can use other classes anddeclare variables just like any othernormal method.

    -ass M2Tread implements Cunna)le.pu&-' ,o'd run+,. S2stem3out3pr'nt-n(4onurrent

    tread started runn'n/334)677

    -ass M2Tread$emo.pu&-' stat' ,o'd ma'n( Str'n/ar/s01 ). M2Tread mt = ne M2Tread()6 Tread t = ne Tread(mt)6 t.start+,677

    Output : onurrent tread startedrunn'n/33

    To call the run&method, %tart&method isused. n calling start=?, a new stack isprovided to the thread and run=? method iscalled to introduce the new thread into theprogram.

    Etending Thread !la%%

    This is another way to create a thread by anew class that e-tends Threadclass andcreate an instance of that class. Thee-tending class must override run&methodwhich is the entry point of new thread.

    -ass M2Tread extends 7hread.pu&-' ,o'd run+,

    . S2stem3out3pr'nt-n(4Conurrenttread started runn'n/334)677

    -assM2Tread$emo.

  • 7/25/2019 Java Notes Core

    78/154

    pu&-' stat' ,o'd ma'n( Str'n/ar/s01 ). M2Tread mt = ne M2Tread()6mt.start+,;77

    Output : onurrent tread startedrunn'n/33

    &n this case also, as we must override therun&and then use the %tart&method tostart and run the thread. 1lso, when youcreate $yThread class object, Thread classconstructor will also be invoked, as it is thesuper class, hence $yThread class objectacts as Thread class object.

    +hat if we !all run& $ethod dire!tl

    without u%ing %tart& $ethod 4 4>'o&)6

  • 7/25/2019 Java Notes Core

    87/154

    Carater o& = a6!Auto&o*'n/ o8 ar ar = o&6 !!AutoJun&o*'n/ o8 Carater S2stem3out3pr'nt-n(o&>4 4>)6773utput '9 9a a

    Auto6oing ( 8n6oing in Ere%%ion%

    ;henever we use object of ;rapper class inan e-pression, automatic unbo-ing andbo-ing is done by J5$.

    Inte/er 'O&6'O& = 96 !!Auto&o*'n/ o8'nt22i3)6

    ;hen we perform increment operation on&nteger object, it is first unbo-ed, thenincremented and then again rebo-ed into&nteger type object.

    This will happen always, when we will use;rapper class objects in e-pressions or

    conditions etc.

    9enefit% of Auto6oing ( 8n6oing

    . 1utobo-ing / Unbo-ing lets us useprimitive types and ;rapper classobjects interchangeably.

    :. ;e don't have toperform 2-plicitte!a%ting.

    7. &t helps preventerrors, but may lead

    to une-pected resultssometimes. Aencemust be used with

    care.

    ?O Strea$

    Java performs &/ through Strea$%. 1%tream is linked to a

    physical layer by java&/ system to makeinput and outputoperation in java. &ngeneral, a stream meanscontinuous flow of data.%treams are clean way to deal with

    input/output without having every part ofyour code understand the physical.

    Java encapsulates %tream [email protected]. Java defines two types of streams.They are,

    . 9te Strea$ /&t provides aconvenient means for handling inputand output of byte.

    :. Chara!ter Strea$ /&t provides aconvenient means for handling inputand output of characters. haracterstream uses Unicode and thereforecan be internationaliDed.

  • 7/25/2019 Java Notes Core

    88/154

    9te Strea$ Cla%%e%

    6yte stream is defined by using two abstractclass at the top of hierarchy, they are&nput%tream and utput%tream.

    These two abstract classes have severalconcrete classes that handle various devicessuch as disk files, network connection etc.

    So$e i$ortant 9te %trea$ !la%%e%.

    Strea$ !la%% "e%!rition

    9uffered?nutStrea$Used for 6uffered&nput %tream.

    9ufferedOututStrea$Used for 6ufferedutput %tream.

    "ata?nutStrea$

    ontains methodfor reading javastandard datatype

    "ataOututStrea$

    1n output streamthat containmethod for writing

    java standard datatype

    :ile?nutStrea$&nput stream thatreads from a file

    :ileOututStrea$utput stream thatwrite to a file.

    ?nutStrea$ 1bstract class thatdescribe stream

    input.

    OututStrea$

    1bstract class thatdescribe streamoutput.

    *rintStrea$

    utput %tream that

    contain pr'nt()and pr'nt-n()

    method

    These classes define several key methods.Two most important are

    . read()0 reads byte of data.

    :. r'te()0 ;rites byte of data.

    Chara!ter Strea$ Cla%%e%

    haracter stream is also defined by usingtwo abstract class at the top of hierarchy,they are 8eader and ;riter.

    These two abstract classes have several

    concrete classes that handle unicodecharacter.

    So$e i$ortant Char!ter %trea$ !la%%e%.

    Strea$ !la%% "e%!rition

  • 7/25/2019 Java Notes Core

    89/154

    9ufferedeaderAandles bufferedinput stream.

    9uffered+riterAandles bufferedoutput stream.

    :ileeader&nput stream that

    reads from file.

    :ile+riterutput stream thatwrites to file.

    ?nutStrea$eader

    &nput stream thattranslate byte tocharacter

    OututStrea$eader

    utput stream thattranslate character tobyte.

    *rint+riter

    utput %tream thatcontain pr'nt()and

    pr'nt-n()method.

    eader

    1bstract class thatdefine characterstream input

    +riter

    1bstract class thatdefine characterstream output

    eading Con%ole ?nut

    ;e use the object of 6uffered8eader class totake inputs from the keyboard.

    eading Chara!ter%

    read()method is used with 6uffered8eader

    object to read characters. 1s this functionreturns integer type value has we need to use

    typecasting to convert it into !hartype.

    intread+,tros G3Hxception

    6elow is a simple e-ample e-plainingcharacter input.

    -ass CarRead.pu&-' stat' ,o'd ma'n( Str'n/ar/s01). Ku88eredReader &r = neKu88eredreader(neInputstreamReader(S2stem3'n))6 ar = +char,)r.read+,6!!Read'n/ arater77

    eading String%

    To read string we have to use read'ne()

    function with 6uffered8eader class's object.

    Stringread8ine+,tros G3Hxception

    *rogra$ to take String inut fro$

    #e6oard in Java

    'mport +a,a3'o3@6-ass M2Input.pu&-' stat' ,o'd ma'n(Str'n/01ar/s)

    . Str'n/ te*t6 Gnput5treamCeader'sr = neGnput5treamCeader+5ystem.in,6 DufferedCeader&r = neDufferedCeader+isr,6 te*t = &r3read'ne()6!!Read'n/ Str'n/S2stem3out3pr'nt-n(te*t)6

  • 7/25/2019 Java Notes Core

    90/154

    77

    *rogra$ to read fro$ a file u%ing

    9ufferedeader !la%%

    'mport +a,a3 Io @6-ass ReadTest.pu&-' stat' ,o'd ma'n(Str'n/01ar/s). tr2.

    F'-e 8- = neF'-e(4d:!m28'-e3t*t4)6 Ku88eredReader &r = neKu88eredReader(ne F'-eReader(8-)) 6

    Str'n/ str6 '-e ((str=&r3read'ne())V=nu--) . S2stem3out3pr'nt-n(str)6 7 &r3-ose()6 8-3-ose()6 7 at (IOE*ept'on e) . e3pr'ntStaTrae()6 777

    *rogra$ to write to a :ile u%ing

    :ile+riter !la%%

    'mport +a,a3 Io @6-ass 5r'teTest.pu&-' stat' ,o'd ma'n(Str'n/01ar/s). tr2.

    F'-e 8- = ne

    F'-e(4d:!m28'-e3t*t4)6 Str'n/ str=45r'te t's str'n/ tom2 8'-e46 F'-e5r'ter 8 = neF'-e5r'ter(8-) 6 83r'te(str)6 83-ose()6 8-3-ose()6 7 at (IOE*ept'on e)

    . e3pr'ntStaTrae()6 777

    SerialiDation and"e%erialiDation in

    Java

    Serializationi% aro!e%% of !onverting an

    o6@e!t into a %eRuen!e of6te% whi!h !an 6e

    er%i%ted to a di%k or

    data6a%e or !an 6e %ent

    through %trea$%. The

    rever%e ro!e%% of

    !reating o6@e!t fro$

    %eRuen!e of 6te% i%!alled

    deserialization.1 class must implement SerialiDa6leinterface present [email protected] in orderto serialiDe its object successfully.SerialiDa6leis a $arker interfa!ethat addsserialiDable behaviour to the class

    implementing it.

    Java provides SerialiDa6le1"& encapsulatedunder)ava(iopackage for serialiDing anddeserialiDing objects which include,

    )ava(io(serializable

  • 7/25/2019 Java Notes Core

    91/154

    )ava(io(Externalizable

    %b)ect$nputStream

    and %b)ect%utputStreametc.

    arker interfa!e

    $arker &nterface is a special interface inJava without any field and method. $arkerinterface is used to inform compiler that theclass implementing it has some specialbehaviour or meaning. %ome e-ample of$arker interface are,

    java.io.%erialiDable

    java.lang.loneable

    java.rmi.8emote

    java.util.8andom1ccess

    1ll these interfaces does not have any

    method and field. They only add specialbehavior to the classes implementing them.Aowever marker interfaces have beendeprecated since Java *, they were replacedby Annotation%. 1nnotations are used inplace of $arker &nterface that play the e-actsame role as marker interfaces did before.

    Signature of

    write3)ect+,andread3)ect+,

    writeO6@e!t&method of%b)ect%utputStreamclassserialiDes an object and send it to the outputstream.

    pu&-' final,o'dwrite3)ect(object x) trosG3Hxception

    readO6@e!t&methodof %b)ect$nputStreamclass references object out of stream anddeserialiDe it.

    pu&-' 8'na-Object

    read3)ect+,trosG3Hxception-lass@otEoundHxception

    while serialiDing if you do not want any fieldto be part of object state then declare iteither static or transient based on your needand it will not be included during javaserialiDation process.

  • 7/25/2019 Java Notes Core

    92/154

    SerialiDing an O6@e!t

    'mport +a,a3'o3@6-ass student'n8o 'mp-ementsSer'a-'a&-e.Str'n/ name6'nt r'd6stat' Str'n/ ontat6student'n8o(str'n/ nB 'nt rB str'n/). t's3name = n6

    t's3r'd = r6 t's3ontat = 677

    -ass Test.pu&-' stat' ,o'd ma'n(Str'n/01ar/s).tr2. Student'n8o s' = nestudent'n8o(4A&'4B 9?B 499??4)6 F'-eOutputStream 8os = neEile3utput5tream+Astudent.serA,6 O&+etoutputstream oos = neO&+etOutputStream(8os)6 oos3r'teO&+et(s')6 oos3-ose()6 8os3-ose()6 7 at (E*ept'on e)

    . e3 pr'ntStaTrae()6 777

    bject of %tudentinfo class is serialiDedusing r'teO&+et()method and written to

    %tudent.%erfile.

    "e%erialiDation of O6@e!t

    'mport +a,a3'o @ 6-ass $eser'a-'at'onTest.pu&-' stat' ,o'd ma'n(Str'n/01ar/s).

    student'n8o s'=nu-- 6 tr2.

    F'-eInputStream 8's = neF'-eInputStream(4student3ser4)6 O&+etOutputStream o's = neO&+etOutputStream(8's)6 s' =(student'n8o)o's3readO&+et()6 7at (E*ept'on e)

    . e3pr'ntStaTrae()6 7 S2stem3out3pr'nt-n(s'3name)6 S2stem3out3 pr'nt-n(s'3r'd)6 S2stem3out3pr'nt-n(s'3ontat)6773utput 'A&'9?nu--

    ontact field is null because,it was markedas static and as we have discussed earlierstatic fields does not get serialiDed.

    >OTE / %tatic members are never serialiDedbecause they are connected to class notobject of class.

    tran%ient #eword

  • 7/25/2019 Java Notes Core

    93/154

    ;hile serialiDing an object, if we don't wantcertain data member of the object to beserialiDed we can mention it transient.transient keyword will prevent that datamember from being serialiDed.

    -ass student'n8o 'mp-ementsSer'a-'a&-e.Str'n/ name6transient'nt r'd6staticStr'n/ ontat67

    $aking a data member tran%ient

    will prevent its serialiDation.

    &n this e-ample r'dwill not beserialiDed because it is tran%ient, andontatwill also remain

    unserialiDed because it is %tati!.

    >etworking in Java

    Java is a premier language for [email protected] encapsulatelarge number of classes and interface thatprovides an easyto use means to accessnetwork resources. Aere are some importantclasses and interfaces of java.net package.

    So$e ?$ortant Cla%%e%

    CASSES

    ache8eBuest ookieAandler

    ookie$anager 9atagrampacket

    &net 1ddress %erver%ocket

    %ocket 9atagram%ocket

    "ro-y U84

    U84onnection

    So$e ?$ortant ?nterfa!e%

    ?>TE:ACES

    ookie"olicy ookie%tore3ile#ame$ap %ocketption

    &net1ddress %erver%ocket

    %ocket&mpl3actory "rotocol3amily

    ?netAddre%%

    &net 1ddress encapsulates both numerical &"address and the domain name for thataddress. &net address can handle both &"va$e=String hostname? throws8nknown=o%tE!etion

    7. static$net#ddress !getAll9>a$e=String hostname? throws8nknown=o%tE!etion

  • 7/25/2019 Java Notes Core

    94/154

    Ea$le u%ing ?netAddre%% !la%%

    'mport +a,a3net3@6-ass Test.pu&-' stat' ,o'd ma'n(Str'n/01ar/s). Gnet6ddress address =Gnet6ddress.get8ocalBost+,6S2stem3out3pr'nt-n(address)6

    address =Gnet6ddress.getDy@ame(43stud2ton'/t3om4)6

    S2stem3out3pr'nt-n(address)6 InetAddress s01 =Gnet6ddress.get6llDy@ame(43/oo/-e3om4)6 8or('nt '=6 ' s3-en/t6 '>>) . S2stem3out3pr'nt-n(s0'1)6 7773utput'5e-omeJPC!L39N933;;3stud2ton'/t3om!;39393LL3/oo/-e3om!?39;L3;

  • 7/25/2019 Java Notes Core

    95/154

    get*ort& / 8eturns port number of

    U84

    get:ile& / 8eturns filename of U84

    *rogra$ u%ing 8 !la%%

    'mport +a,a3net3@6-ass Test.pu&-' stat' ,o'd ma'n(Str'n/01ar/) tros Ma-FormedURE*ept'on. JC8 hp = @ewJC8+Ahttp'//www.studytonight.com/indexA,;

    s2stem3out3pr'nt-n(p3/etProtoo-01)6S2stem3out3pr'nt-n(p3/etF'-e01)6

    773uput'ttpJ93stud2ton'/t3om!'nde*

    Keneri!%

    1 class or interface thatoperates on

    parameteriDed type iscalled Keneri!. !enerics wasfirst introduced in Java*. #ow it is one of

    the most profound feature of javaprogramming language. &t provides facilityto write algorithm independent of any

    specific type of data. Keneri!%

    al%o rovide te

    %afet.

    8%ing Keneri!%,it 6e!o$e%o%%i6le to !reate a %ingle !la%%

    or $ethod that auto$ati!all

    work% with all te% of

    data&?nteger, String, :loat et!.

    ?t eanded the a6ilit to reu%e

    !ode %afel and ea%il.

    Ea$le of Keneri! !la%%

    -ass Gen.

    7o&6 !!an o&+et o8 t2pe T 'sde-aredGen(T o) !!onstrutor. o& = o67pu&-' 7/etO&(). return o&677

    -ass Test.

    pu&-' stat' ,o'd ma'n (Str'n/01ar/s). GenK GntegerL'o& = ne Gen(9)6!!'nstane o8 Inte/er t2pe GenC-ass3'nt * = 'o&3/etO&()6

    S2stem3out3pr'nt 'n(*)6 GenK 5tringLso& = neGen(4He--o4)6 !!'nstane o8 Str'n/t2pe Gen C-ass3 Str'n/ str = so&3/etO&()67

    73utput '9He--o

    Keneri!% +ork Onl with O6@e!t%

  • 7/25/2019 Java Notes Core

    96/154

    Cou cannot use primitive datatype such asintor !haretc with !enerics type. &t shouldalways be an object.

    GenK intL'O& = ne GenK intL()6!!ErrorB ant use pr'm't',e t2pe

    Keneri!% Te% of different Te

    Argu$ent% are never %a$e

    8eference of one generic type is nevercompatible with other generic type unlesstheir type argument is same. &n the e-ampleabove we created two objects of class Ken,one of type ?nteger, and other of typeString, hence,

    'o& = so&6 !!A&so-ute-2 5ron/

    Keneri! ethod%

    Cou can also create generic methods that canbe called with different types of argumentsbased on the type of arguments passed togeneric method, the compiler handles eachmethod.

    Ea$le of Keneri! $ethod

    -ass GenTest.stat'K 4 7L,o'd d'sp-a2 (# ,B Tt).

    S2stem3out3pr'nt-n(,3/etC-ass()3/etame()>4 = 4 >,)6

    S2stem3out3pr'nt-n(t3/etC-ass()3/etame()>4 = 4 >t)67pu&-' stat' ,o'd ma'n(Str'n/01ar/s). d'sp-a2(B4T's 's str'n/4)67

    73utput '+a,a -an/3Inte/er = "a,a -an/3Str'n/ = t's 's str'n/

    Keneri! Con%tru!tor%

    &t is possible to create a generic constructoreven if the class is not generic.

    Ea$le of Keneri! Con%tru!tor

    -ass Gen.pr',ate dou&-e ,a-6K 7 extends @um)erLGen(T o&).

    ,a-=o&3dou&-e#a-ue()67,o'd so(). S2stem3out3pr'nt-n(,a-)677

    -ass Test.pu&-' stat' ,o'd ma'n(Str'n/01ar/s). Gen / = ne Gen(9)6Gen /9 = ne Gen(9;93L8)6

    /3so()6 /93so()6773utput '939;93L

    Keneri! ?nterfa!e

    4ike classes and methods, you can alsocreate generic interfaces.

    'nter8ae M2Inter8aeK 7 L. 33 7

    Keneri! 9ounded te *ara$eter

  • 7/25/2019 Java Notes Core

    97/154

    Cou can also set restriction on the type thatwill be allowed to pass to a typeparameter.This is done with the help of etend%keyword when specifying the typeparameter.

    T e*tends um&er

    Aere we have taken >u$6erclass, it can beany wrapper class name. This specifies thatT can be only be replaced by >u$6erclassdata itself or any of its subclass.

    Keneri! ethod with 6ounded te

    *ara$eter%.

    -ass Gen.stat'K 7 4 extends num)erL,o'dd'sp-a2(T tB # ,).

    S2stem3out3pr'nt-n(,3/etC-ass()3/etame()>4 = 4 >,)6

    S2stem3out3pr'nt-n(t3/etC-ass()3/etame()>4 = 4 >t)67pu&-' stat' ,o'd ma'n(Str'n/01ar/s).!! d'sp-a2(B4T's 's str'n/4)6 d'sp-a2 (4t's 's str'n/4B)677

    3utput '+a,a3-an/3Str'n/ = T's 's str'n/+a,a3-an/3$ou&-e = 3O

    Type 5 is bounded to #umber type

    and its subclass only.

    &f d'sp-a2(B4T's 's str'n/4)

    is uncommented, it will give an errorof type incompatibility, as %tring isnot a subclass of #umber class.

    Colle!tion :ra$ework

    ollection framework was not part oforiginal Java release. ollections was addedto J:%2 .:. "rior to Java :, Java providedadhoc classes such as 9ictionary, 5ector,%tack and "roperties to store and manipulate

    groups of objects. ollectionframework provides

    many importantclasses and interfacesto collect andorganiDe group ofalike objects.

    ?$ortant ?nterfa!e% of Colle!tion A*?

    ?nterfa!e "e%!rition

    Colle!tion

    2nables you to work with groupsof objectM it is at the top ofcollection hierarchy

    "eRue2-tends Bueue to handle doubleended Bueue.

    i%t2-tends collection to handleseBuences list of object.

    Iueue

    2-tends collection to handlespecial kind of list in whichelement are removed only fromthe head.

    Set

    2-tends collection to handlesets, which must contain uniBueelement.

    SortedSet 2-tends sets to handle sorted set.

  • 7/25/2019 Java Notes Core

    98/154

    1ll these &nterfaces give several methodswhich are defined by collections classeswhich implement these interfaces.

    +h Colle!tion% were $ade Keneri! aviga6leSetinterface.

    :. &t stores elements sorted ascendingorder.

    7. Uses a Tree structure to storeelements.

  • 7/25/2019 Java Notes Core

    104/154

    7.Using foreach loop

    A!!e%%ing ele$ent% u%ing ?terator

    &terator &nterface is used to traverse a list inforward direction, enabling you to removeor modify the elements of the collection.2ach collection classes provide iterator&method to return an iterator.

    'mport +a,a3ut'-3@6-ass TestQIterator.pu&-' stat' ,o'd ma'n(Str'n/01ar/s). Arra2'st Str'n/ ar = neArra2'st Str'n/()6 ar3add(4a&4)6 ar3add(4&4)6 ar3add(4d4)6 ar3add(4de4)6

    Gterator it = ar.iterator+,6!!$e-ar'n/ Iterator '-e('t3ase*t()) .

    S2stem3out3pr'nt('t3ne*t()>4 4)6

    777Output : a& & d de

    A!!e%%ing ele$ent u%ing i%t?terator

    i%t?terator ?nterfa!e i%

    u%ed to traver%e a li%t in

    6oth forward and6a!kward dire!tion. &t isavailable to only those collections thatimplement the i%t&nterface.

    'mport +a,a3ut'-3@6-ass TestQIterator

    .pu&-' stat' ,o'd ma'n(Str'n/01ar/s). Arra2'st Str'n/ ar = neArra2'st Str'n/()6 ar3add(4a&4)6 ar3add(4&4)6 ar3add(4d4)6 ar3add(4de4)6

    8istGterator litr =ar.listGterator+,6 '-e(-'tr3ase*t())!!In 8orard d'ret'on . S2stem3out3pr'nt(-'tr3ne*t()>44)6 7

    '-e(-'tr3asPre,'ous())!!In &aard d'ret'on . S2stem3out3pr'nt(-'tr3ne*t()>44)6 7773utput ' a& & d de de d & a&

    8%ing forBea!h loo

    8orJeaversion of for loop can also be

    used for traversing each element of acollection. 6ut this can only be used if wedon't want to modify the contents of acollection and we don't want any reverseaccess. 8orJealoop can cycle through

    any collection of object that implements&terable interface.

    'mport +a,a3ut'-3@6-ass ForEa$emo.pu&-' stat' ,o'd ma'n(Str'n/01ar/s). 'ned'st Str'n/ -s = ne'ned'st Str'n/()6 -s3add(4a4)6 -s3add(4&4)6

  • 7/25/2019 Java Notes Core

    105/154

    -s3add(44)6 -s3add(4d4)6

    for+5tring str ' ls,

    . S2stem3out3pr'nt(str>4 4)6 777

    Output : a & d

    a ?nterfa!e

    1 $ap stores data in key and valueassociation. 6oth key and values are objects.

    The key must be uniBue but the values canbe duplicate. 1lthough $aps are a part ofollection 3ramework, they can not actuallybe called as collections because of someproperties that they posses. Aowever we canobtain a !olle!tionBviewof maps.

    ?nterfa!e "e%!rition

    a$aps uniBuekey to value.

    a.Entr

    9escribe an

    element inkey andvalue pair ina map. Thisis an innerclass of map.

    >aviga6lea

    2-tends%orted$apto handle theretrienal ofentries based

    on closestmatchsearches

    Sorteda 2-tends $apso that keyaremaintained

    in anascendingorder.

    Co$$onl u%ed ethod% defined 6 a

    boolean !ontain%#e=bject *?0

    returns true if map contain *as key.therwise false.

    bject get=bject *? 0 returns values

    associated with the key *.

    bject ut=bject *, bject v? 0

    stores an entry in map.

    bject utAll=$ap m? 0 put all

    entries from min this map.

    %et keSet=? 0 returns Setthat

    contains the key in a map.

    %et entrSet=? 0 returns Setthat

    contains the entries in a map.

  • 7/25/2019 Java Notes Core

    106/154

    =a%ha !la%%

    . Aash$ap class e-tendsA6%tra!taand implements ainterface.

    :. &t uses a ha%hta6leto store the map.This allows the e-ecution time of/et()and put()to remain same.

    7. Aash$ap has four constructor.

    HasMap()HasMap(Map W e*tends B We*tends # m)HasMap('nt apa't2)HasMap('nt apa't2B 8-oat

    8'--rat'o)

    4:4)6

    S2stem3out3pr'nt-n(me3/et#a-ue())6 7773utput' aviga6leainterface.

    :. &t creates $ap, stored in a treestructure.

    7. 1 Treeaprovides an efficientmeans of storing key/value pair inefficient order.

    4:4)6

    S2stem3out3pr'nt-n(me3/et#a-ue())6 7773utput'a 9& ;

  • 7/25/2019 Java Notes Core

    107/154

    inked=a%ha !la%%

    . inked=a%hae-tends

    =a%haclass.

    :. &t maintains a linked list of entries inmap in order in which they areinserted.

    7. inked=a%hadefines thefollowing constructor

    'nedHasMap()

    'nedHasMap(Map W e*tends

    B W e*tends # m)

    'nedHasMap('nt apa't2)

    'nedHasMap('nt apa't2B8-oat 8'--rat'o)

    'nedHasMap('nt apa't2B8-oat 8'--rat'oB &oo-eanorder)

  • 7/25/2019 Java Notes Core

    108/154

    7 pu&-' Str'n/ toStr'n/() . return ro-->4 4>name6 7

    Co$arator !la%%

    This class defines the comparison logic for%tudent class based on their roll. %tudentobject will be sotred in ascending order oftheir roll.

    -ass M2Comparator 'mp-ementsComparator. pu&-' 'nt ompare(Students9BStudent s;)

    . '8(s93ro-- == s;3ro--)return 6 e-se '8(s93ro-- s;3ro--)return 96 e-se return J96 77pu&-' -ass Test.

    pu&-' stat' ,o'd ma'n(Str'n/01

    ar/s).

    TreeSet Student ts = neTreeSet Student(new

    >y-omparator+,)6 ts3add(ne Student(?LB4Rau-4))6 ts3add(ne Student(99B4Adam4))6 ts3add(ne Student(9B4A-e*4))6 S2stem3out3pr'nt-n(ts)6 7

    7

    3utput0 99 AdamB 9 A-e*B ?L Rau- 1

    1s you can see in the ouput %tudent objectare stored in ascending order of their roll.

    ega! Cla%%e%

    2arly version of java did not include theColle!tionframework. &t only definedseveral classes and interface that provide

    method for storing objects. ;hen Colle!tionframework were added in J:%2 .:, theoriginal classes were reengineered tosupport the collection interface. Theseclasses are also known as 4egacy classes.1ll legacy claases and interface wereredesign by J9 * to support !enerics.

    The following are the legacy classes [email protected]

    . 9ictionary

    :. AashTable

    7. "roperties

    OTE/1ll the legacy classes aresyncroniDed

    Enu$eration interfa!e

    . Enu$erationinterface definesmethod to enumerate through

    collection of object.

    :. This interface is suspended by?teratorinterface.

    7. Aowever some legacy classes suchas ;e!torand *roertie%defines

  • 7/25/2019 Java Notes Core

    109/154

    several method in whichEnu$erationinterface is used.

  • 7/25/2019 Java Notes Core

    110/154

    7. Aashtable has following fourconstructor

    Hasta&-e()Hasta&-e('nt s'e)Hasta&-e('nt s'eB 8-oat

    8'--rat'o)Hasta&-e(Map W e*tends B We*tends # m)

    Ea$le of =a%hta6le

    'mport +a,a3ut'-3@6-ass HasTa&-e$emo.pu&-' stat' ,o'd ma'n(Str'n/ar/s01). Bashta)leK 5tringGntegerL ht =new Bashta)leK 5tringGntegerL+,6 t3put(4a4Bne Inte/er(9))6 t3put(4&4Bne Inte/er(;))6 t3put(44Bne Inte/er(

  • 7/25/2019 Java Notes Core

    111/154

    Set W reator = pr3e2Set()6

    8or(O&+et o&: reator)

    . S2stem3out3pr'nt-n(o&>4 asreated &2 4>pr3/etPropert2((Str'n/)o&) )6 7

    7

    73utput"a,a as reated &2 "ames Gos-'n/C>> as reated &2 K+arne StroustrupC as reated &2 $enn's R't'eCX as reated &2 M'roso8t In

    Alet in Java

    1pplets are small Java applications

    that can be accessed on an &nternetserver, transported over &nternet, andcan be automatically installed andrun as apart of a web document. 1nyapplet in Java is a class that [email protected].

    1n 1pplet class does not have any

    main=? method.

    &t is viewed using J5$. The J5$

    can use either a plugin of the ;ebbrowser or a separate runtimeenvironment to run an appletapplication.

    J5$ creates an instance of the applet

    class and invokes init&method toinitialiDe an 1pplet.

    A Si$le Alet

    'mport +a,a3at3@6'mport +a,a3app-et3@6pu&-' -ass S'mp-e e*tends App-et

    .pu&-' ,o'dpaint(Grap's /). /3draStr'n/(4A s'mp-e App-et4B;B ;)677

    2very Aletapplication must declare apa'nt()method. This method is defined by

    A+Tclass and must be overridden by theapplet. pa'nt()method is called each time

    an applet neede to redisplay its output.1nother important thing to notice aboutapplet application is that, e-ecution of anapplet does not begin at ma'n()method. &n

    fact an applet application does not have any$ain&method.

    Advantage% of Alet%

    . 5ery less response time as it workson the client side.

    :. an be run using any browser, whichhas J5$ running in it.

    Alet !la%%

  • 7/25/2019 Java Notes Core

    112/154

    1pplet class provides all necessary supportfor applet e-ecution, such as initialiDing anddestroying of applet. &t also provide methodsthat load and display images and methodsthat load and play audio clips.

    An Alet Skeleton

    $ost applets override these four methods.These four methods forms 1pplet lifecycle.

    init& /init=? is the first method to be

    called. This is where variable areinitialiDed. This method is calledonly once during the runtime ofapplet.

    %tart& /start=? method is called after

    init=?. This method is called to restartan applet after it has been stopped.

    %to& /stop=? method is called to

    suspend thread that does not need torun when applet is not visible.

    de%tro& /destroy=? method is

    called when your applet needs to be

    removed completely from memory.

    Ea$le of an Alet Skeleton

    'mport +a,a3at3@6'mport +a,a3app-et3@6pu&-' -ass App-etTest e*tendsApp-et.pu&-' ,o'd init+,

    . !!'n't'a-'at'on7pu&-' ,o'd start(). !!start or resume e*eut'on7pu&-' ,o'd stop+,. !!suspend e*eut'on

    .pu&-' ,o'd destroy+,. !!per8orm sutdon at','t27pu&-' ,o'dpaint(Grap's /). !!d'sp-a2 te ontent o8 'ndo77

    Ea$le of an Alet

    'mport +a,a3app-et3@6'mport +a,a3at3@6pu&-' -ass M2App-et e*tends App-et.'nt e'/tB 'dt6

    pu&-' ,o'd 'n't(). e'/t = /etS'e()3e'/t6 'dt = /etS'e()3'dt6 setame(4M2App-et4)67pu&-' ,o'dpaint(Grap's /). g.drawCoundCect(9B

  • 7/25/2019 Java Notes Core

    113/154

    1n 1pplet program is compiled in the sameway as you have been compiling yourconsole programs. Aowever there are twoways to run an applet.

    2-ecuting the 1pplet within Javacompatible web browser.

    Using an 1pplet viewer, such as the

    standard tool, applet viewer. 1napplet viewer e-ecutes your applet ina window

    3or e-ecuting an 1pplet in an web browser,create short =T filein the samedirectory. &nside 6odtag of the file, include

    the following code. =alettag loads the1pplet class?

    app-et ode = 4M2App-et4 'dt=?e'/t=? !app-et

    un the =T file

    unning Alet u%ing Alet ;iewer

    To e-ecute an 1pplet with an applet viewer,write short AT$4 file as discussed above. &fname it as run.ht$, then the followingcommand will run your applet program.

    8:!app-et,'eer run3tm

  • 7/25/2019 Java Notes Core

    114/154

    Event =andling

    1ny program that uses !U& =graphical userinterface? such as Java application writtenfor windows, is event driven. 2ventdescribes the change of state of any object.

    Ea$le /"ressing a button, 2ntering acharacter in Te-tbo-.

    Co$onent% of Event =andling

    2vent handling has three main components,

    Event% /1n event is a change of

    state of an object.

    Event% Sour!e /2vent source is an

    object that generates an event.

    i%tener% /1 listener is an object

    that listens to the event. 1 listenergets notified when an event occurs.

    =ow Event% are handled yIindowA,6!!Creat'n/ a "Frame 't nameM25'ndo3"Kutton &tn = ne "Kutton(4Sa2He--o4)6 !!Creat'n/ a Kutton3+83add(&tn)6!!add'n/ &utton to 8rame3+83seta2out(ne F-oa2out())6!!sett'n/ -a2out us'n/ F-oa2outo&+et3

    +83set$e8au-tC-oseOperat'on("Frame3E

    ITQOQCOSE)6 !!sett'n/ -oseoperat'on3+83setS'e(?B ?)6!!sett'n/ s'e+83set#'s'&-e(true)6!!sett'n/ 8rame ,'s'&'-t27pu&-' stat' ,o'd ma'n(Str'n/01ar/s)

  • 7/25/2019 Java Notes Core

    120/154

    . ne F'rst()677

    Creating J:ra$e window 6 etending

    J:ra$e !la%%

    'mport +a,a*3s'n/3@6'mport +a,a3at3e,ent3@6'mport +a,a3at3@6pu&-' -ass Seond extends"Frame.pu&-' Seond(). setT't-e(4M25'ndo4)6 "a&e- -& = ne "a&e-(45e-ome toM2 Seond 5'ndo4)6 !!Creat'n/ a-a&e-3 add(-&)6

    !!add'n/ -a&e- to 8rame3seta2out(ne F-oa2out())6

    !!sett'n/ -a2out us'n/F-oa2out o&+et3

    set$e8au-tC-oseOperat'on("Frame3EITQOQCOSE)6 !!sett'n/-ose operat'on3

    setS'e(?B ?)6!!sett'n/ s'e

    set#'s'&-e(true)6!!sett'n/ 8rame ,'s'&'-t2

    7pu&-' stat' ,o'd ma'n(Str'n/01ar/s). ne Seond()677

    Swing Co$onent

    %wing 3ramework contains a large set ofcomponents which provide richfunctionalities and allow high level ofcustomiDation. 1ll these components are

    lightweight components. They all arederived from JCo$onentclass. &t supportsthe pluggable look and feel.

    J9utton

  • 7/25/2019 Java Notes Core

    121/154

    J9uttonclass provides functionality of abutton. J6utton class has three constuctors,

    9Dutton(Ion ic)

    9Dutton(Str'n/ str)

    9Dutton(Str'n/ strB Ion ic)

    &t allows a button to be created using icon, astring or both. J6utton supportsA!tionEvent. ;hen a button is pressed anA!tionEventis generated.

    Ea$le u%ing J9utton

    'mport +a,a*3s'n/3@6'mport +a,a3at3e,ent3@6'mport +a,a3at3@6pu&-' -ass tests'n/ extends"Frame.

    tests'n/(). "Kutton &t9 = ne "Kutton(4Yes4)6!!Creat'n/ a Yes Kutton3"Kutton &t; = ne "Kutton(4o4)6

    !!Creat'n/ a o Kutton3

    set$e8au-tC-oseOperat'on("Frame3EITQOQCOSE) !!sett'n/ -oseoperat'on3seta2out(ne F-oa2out())6

    !!sett'n/ -a2out us'n/ F-oa2outo&+etsetS'e(?B ?)6

    !!sett'n/ s'e o8 "8rameadd(&t9)6 !!add'n/ Yes

    &utton to 8rame3add(&t;)6 !!add'n/ o

    &utton to 8rame3

    set#'s'&-e(true)67pu&-' stat' ,o'd ma'n(Str'n/01ar/s). ne tests'n/()677

    JTet:ield

    JTet:ieldis used for taking input of singleline of te-t. &t is most widely used te-t

    component. &t has three constructors,

    97extEield('nt cols)97extEield(Str'n/ strB 'nt cols)97extEield(Str'n/ str)

    colsrepresent the number of columns in te-tfield.

    Ea$le u%ing JTet:ield

    'mport +a,a*3s'n/3@6'mport +a,a3at3e,ent3@6'mport +a,a3at3@6pu&-' -ass M2Te*tF'e-d extends"Frame.pu&-' M2Te*tF'e-d().

  • 7/25/2019 Java Notes Core

    122/154

    97extEield tf = new97extEield+!0,6!!reat'n/"Te*tF'e-d3add(+t8)6

    !!add'n/ "Te*tF'e-d to 8rame3seta2out(ne F-oa2out())6

    set$e8au-tC-oseOperat'on("Frame3EITQOQCOSE)6 setS'e(?B ?)6 set#'s'&-e(true)67pu&-' stat' ,o'd ma'n(Str'n/01ar/s). ne M2Te*tF'e-d()677

    JChe!k9o

    JChe!k9oclass is used to createcheckbo-es in frame. 3ollowing isconstructor for Jheck6o-,

    9-hecDox(Str'n/ str)

    Ea$le u%ing JChe!k9o

    'mport +a,a*3s'n/3@6'mport +a,a3at3e,ent3@6'mport +a,a3at3@6pu&-' -ass Test extends"Frame

    .pu&-' Test(). 9-hecDox c) = new9-hecDox+AyesA,6 !!reat'n/"CeKo*3add(+&)6

    !!add'n/ "CeKo* to 8rame3c) = new 9-hecDox+AnoA,;

    !!reat'n/ "CeKo*3add(+&)6

    !!add'n/ "CeKo* to 8rame3c) = new 9-hecDox+Amay)eA,;

    !!reat'n/ "CeKo*3add(+&)6

    !!add'n/ "CeKo* to 8rame3seta2out(ne F-oa2out())6

    set$e8au-tC-oseOperat'on("Frame3EITQOQCOSE)6 setS'e(?B ?)6 set#'s'&-e(true)67pu&-' stat' ,o'd ma'n(Str'n/01ar/s). ne Test()6

    77

    Jadio9utton

  • 7/25/2019 Java Notes Core

    123/154

    8adio button is a group of related button inwhich only one can be selected.J8adio6utton class is used to create a radiobutton in 3rames. 3ollowing is theconstructor for J8adio6utton,

    9CadioDutton(Str'n/ str)

    Ea$le u%ing Jadio9utton

    'mport +a,a*3s'n/3@6'mport +a,a3at3e,ent3@6'mport +a,a3at3@6pu&-' -ass Test extends"Frame.pu&-' Test().

    9CadioDutton c) = new9CadioDutton+A6A,6 !!reat'n/"Rad'oKutton3add(+&)6

    !!add'n/ "Rad'oKutton to 8rame3c) = new 9CadioDutton+ADA,6

    !!reat'n/ "Rad'oKutton3add(+&)6

    !!add'n/ "Rad'oKutton to 8rame3c) = new 9CadioDutton+A-A,6

    !!reat'n/ "Rad'oKutton3add(+&)6

    !!add'n/ "Rad'oKutton to 8rame3

    c) = new 9CadioDutton+AnoneA,6 add(+&)6 seta2out(ne F-oa2out())6

    set$e8au-tC-oseOperat'on("Frame3EITQOQCOSE)6 setS'e(?B ?)6 set#'s'&-e(true)67pu&-' stat' ,o'd ma'n(Str'n/01ar/s). ne Test()67

    7

    JCo$6o9o

    ombo bo- is a combination of te-t fieldsand dropdown list.JCo$6o9ocomponentis used to create a combo bo- in %wing.3ollowing is the constructor forJombo6o-,

    9-om)oDox(Str'n/ arr*)

    Ea$le u%ing JCo$6o9o

    'mport +a,a*3s'n/3@6

    'mport +a,a3at3e,ent3@6'mport +a,a3at3@6pu&-' -ass Test extends"Frame.Str'n/ name[]=.4A&'4B4Adam4B4A-e*4B4Asa2476 !!-'st o8 name3pu&-' Test(). 9-om)oDox c = new9-om)oDox+name,6 !!'n't'a-'n/om&o &o* 't -'st o8 name3add(+)6

    !!add'n/ "Com&oKo* to 8rame3seta2out(ne F-oa2out())6

    set$e8au-tC-oseOperat'on("Frame3EITQOQCOSE)6 setS'e(?B ?)6 set#'s'&-e(true)67pu&-' stat' ,o'd ma'n(Str'n/01ar/s)

  • 7/25/2019 Java Notes Core

    124/154

    . ne Test()677

    efle!tion A*?

    8eflection means ability of a software toanalyDe itself. &n Java, 8eflection 1"&provides facility to analyDe and changeruntime behaviour of a lass, at runtime.

    3or e-ample, using reflection at the runtimeyou can determine what method, field,constructor or modifers a class supports.

    +hat i% refle!t a!kage >) . S2stem3out3pr'nt-n(t0'1)6 7 Construtor Student01 dt =c.geteclared-onstructors()6 8or('nt '=6' dt3-en/t6'>>) . S2stem3out3pr'nt-n(dt0'1)67

    7 at(E*ept'on e) . e3pr'ntStaTrae()67773utput ' pu&-' Student() pu&-' Student()

    Student(+a,a3-an/3Str'n/)

    getethod%& and get"e!laredethod%&

    /etMetods()method returns array of

    $ethod object that reflect all the publicmethod of invoking object.

  • 7/25/2019 Java Notes Core

    126/154

    /et$e-aredMetods()returns only the

    declared methods of the invoking classobject. %ynta- for both is followwing,

    >ethod W01 get.ethods()6>ethod W01 get'eclared.ethods()6

    Ea$le u%ing get"e!laredethod%&

    $ethod

    'mport +a,a3-an/3re8-et3@6-ass Student.pu&-' ,o'd so().7,o'd d'sp-a2().77

    -ass Test.pu&-' stat' ,o'd ma'n(Str'n/ar/s01). tr2 . -lass c =-lass.for@ame(4Student4)6 >ethodmd01 =c.geteclared>ethods()6 8or('nt '=6 ' md3-en/t6 '>> ) . S2stem3out3pr'nt-n(md0'1)6 7 7 at(E*ept'on e) . e3pr'ntStaTrae()67773utput ' pu&-' ,o'd Student3so() ,o'd Student3d'sp-a2()

    get:ield%& and get"e!lared:ield%&

    /etF'e-ds()returns an array containing

    3ield objects reflecting all the accessiblepublic members of the class or interfacerepresented by this lass object./et$e-aredF'e-ds()returns array of

    3ield objects reflecting all the fieldsdeclared by the class or interface representedby this lass object.

    Eield W01 get!ields()6Eield W01 get'eclared!ields()6

    Ea$le u%ing get:ield%& and

    get"e!lared:ield%& $ethod

    'mport +a,a3-an/3re8-et3@6-ass Student.pu&-' Str'n/ name6'nt ro--67

    -ass Test.pu&-' stat' ,o'd ma'n(Str'n/ar/s01).

    tr2 . C-ass =-lass.for@ame(4Student4)6 Eield8801 = c.getEields()6 8or('nt '=6 ' 883-en/t6 '>>) . S2stem3out3pr'nt-n(880'1)6 7 Eield801 =c.geteclaredEields()6 8or('nt '=6' 83-en/t6 '>>) . S2stem3out3pr'nt-n(80'1)6 7 7 at(E*ept'on e) . e3pr'ntStaTrae()67773utput ' pu&-' +a,a3-an/3Str'n/Student3name pu&-' +a,a3-an/3Str'n/Student3name 'nt Student3ro--

    ?

    8emote method invocation=8$&? allow ajava object to invoke method on an objectrunning on another machine. 8$& provideremote communication between javaprogram. 8$& is used for buildingdistributed application.

  • 7/25/2019 Java Notes Core

    127/154

    Con!et of ? ali!ation

    1 8$& application can be divided into twopart,Clientprogram and Serverprogram. 1Serverprogram creates some remote object,

    make their references available for the clientto invoke method on it. 1 Clientprogrammake reBuest for remote objects on serverand invoke method on them. Stu6andSkeletonare two important object used forcommunication with remote object.

    Stu6 and Skeleton

    Stu6act as a gateway for lient program. &tresides on lient side and communicate withSkeletonobject. &t establish the connectionbetween remote object and transmit reBuestto it.

    %keleton object resides on server program. &tis responsible for passing reBuest from Stu6to remote object.

    Creating a Si$le ? ali!ation

    involve% following %te%

    9efine a remote interface.

    &mplementing remote interface.

    create and start remote application

    create and start client application

    "efine a re$ote interfa!e

    1 remote interface specifies the methods

    that can be invoked remotely by a client.lients program communicate to remoteinterfaces, not to classes implementing it. Tobe a remote interface, a interface muste-tend the e$oteinterface [email protected]$ipackage.

    'mport +a,a3rm'3@6pu&-' 'nter8ae AddSer,erInter8aee*tends Remote.pu&-' 'nt sum('nt aB'nt &)6

    7

    ?$le$entation of re$ote interfa!e

    3or implementation of remote interface, aclass must either e-tend8ni!a%te$oteO6@e!tor usee-portbject=? method of8ni!a%te$oteO6@e!tclass.

    'mport +a,a3rm'3@6'mport +a,a3rm'3ser,er3@6pu&-' -ass Adder e*tendsUn'astRemoteO&+et 'mp-ementsAddSer,erInter8ae.Adder()tros RemoteE*ept'on.super()67pu&-' 'nt sum('nt aB'nt &)

  • 7/25/2019 Java Notes Core

    128/154

    .return a>&677

    Create AddServer and ho%t r$i %ervi!e

    Cou need to create a server application andhost rmi service Adderin it. This is doneusing re&'nd()method of

    @ava.r$i.>a$ingclass. re&'nd()method

    take two arguments, first represent the nameof the object reference and second argumentis reference to instance of Adder

    'mport +a,a3rm'3@6

    'mport +a,a3rm'3re/'str23@6pu&-' -ass AddSer,er.pu&-' stat' ,o'd ma'n(Str'n/ar/s01).tr2.AddSer,erInter8ae addSer,'e=neAdder()6am'n/3re&'nd(4AddSer,'e4BaddSer,'e)6!!addSericeo&+et 's osted 'tname6dd5er*ice3

    7at(E*ept'on e).S2stem3out3pr'nt-n(e)67

    77

    Create !lient ali!ation

    lient application contains a java programthat invokes the -ooup()method of the

    >a$ingclass. This method accepts oneargument, the r$iU84 and returns areference to an object of type

    AddServer?nterfa!e. 1ll remote methodinvocation is done on this object.

    'mport +a,a3rm'3@6pu&-' -ass C-'ent.pu&-' stat' ,o'd ma'n(Str'n/ar/s01).tr2.

    AddSer,erInter8aest=(AddSer,erInter8ae)am'n/3-ooup(4rm':!!4>ar/s01>4!AddSer,'e4)6S2stem3out3pr'nt-n(st3sum(;LB))67at(E*ept'on e).S2stem3out3pr'nt-n(e)6777

    Ste% to run thi% ? ali!ation

    %ave all the above java file into a directoryand name it as OrmiO

    compile all the java files

    +a,a @3+a,a

    %tart 8$& registry

    start rm're/'str2

  • 7/25/2019 Java Notes Core

    129/154

    8un %erver file

    +a,a AddSer,er

    8un lient file in another command

    prompt abd pass local host portnumber at run time

    +a,a C-'ent 9;3339

    ?ntrodu!tion to J"9C

    Java "ata6a%e Conne!tivit&J"9Cis anAli!ation *rogra$$ing ?nterfa!e&A*?

    used to connect Java application with9atabase. J96 is used to interact withvarious type of 9atabase such as racle, $%1ccess, $y %`4 and %`4 %erver. J96can also be defined as the platformindependent interface between a relationaldatabase and Java programming. &t allows

    java program to e-ecute %`4 statement andretrieve result from database.

  • 7/25/2019 Java Notes Core

    130/154

    +hat% new in J"9C 4.'

    J"9C 4.'is new and advance specificationof J96. &t provides the following advancefeatures

    onnection $anagement

    1uto loading of 9river &nterface.

    6etter e-ception handling

    %upport for large object

    1nnotation in %`4 Buery.

    J"9C "river

    J96 9river is reBuired to process %`4

    reBuests and generate result. The followingare the different types of driver available inJ96.

    TeB1 "riveror J"9CBO"9C

    6ridge

    TeB2 "riveror >ative A*? *artl

    Java "river

    TeB3 "riveror >etwork *roto!ol

    "river

    TeB4 "riveror Thin "river

    J"9CBO"9C 6ridge

    TeB1 "riveract as a bridge betweenJ96 and other database connectivitymechanism=96?. This driver converts

    J96 calls into 96 calls and redirectsthe reBuest to the 96 driver.

  • 7/25/2019 Java Notes Core

    131/154

    Advantage

    2asy to use

    1llow easy connectivity to all

    database supported by the 969river.

    "i%advantage

    %low e-ecution time

    9ependent on 96 9river.

    Uses Java #ative &nterface=J#&? to

    make 96 call.

    >ative A*? "river

    This type of driver make use of Java #ative&nterface=J#&? call on database specificnative client 1"&. These native client 1"&are usually written in and NN.

    Advantage

    faster as compared to TeB1 "river

    ontains additional features.

    "i%advantage

    8eBuires native library

    &ncreased cost of 1pplication

    >etwork *roto!ol "river

    This driver translate the J96 calls into adatabase server independent and

    $iddleware serverspecific calls.$iddleware server further translate J96calls into database specific calls.

    Advantage

    9oes not reBuire any native library to

    be installed.

    9atabase &ndependency.

  • 7/25/2019 Java Notes Core

    132/154

    "rovide facility to switch over from

    one database to another database.

    "i%advantage

    %low due to increase number ofnetwork call.

    Thin "river

    This is 9river called "ure Java 9riverbecause. This driver interact directly withdatabase. &t does not reBuire any nativedatabase library, that is why it is also known

    as Thin 9river.

    Advantage

    9oes not reBuire any native library.

    9oes not reBuire any $iddleware

    server.

    6etter "erformance than other driver.

    "i%advantage

    %low due to increase number of

    network call.

    J"9C 4.' A*?

    J96

  • 7/25/2019 Java Notes Core

    133/154

    support for9ate %`4type.

    +a,a3s-3$r',er

    create aninstance of a

    driver with the9river$anager.

    +a,a3s-3$r',erMana/er

    This classmanagesdatabasedrivers.

    +a