java for beginners

65

Upload: romeosanchez

Post on 03-Oct-2015

34 views

Category:

Documents


5 download

DESCRIPTION

Java for beginners

TRANSCRIPT

  • LEARNINGSTARTSWITHVIEWINGTHEWORLDDIFFERENTLY.

    Knowledgeflow-Amobilelearningplatformprovidesapps,eBooksandvideotutorials

    KnowledgeflowbringsyoulearningeBookofJavaforBeginners.ThiseBookisforallinformationtechnologyandcomputersciencestudentsandprofessionalsacrosstheworld.

    Followuson

    Facebook

    Googleplus

    Twitter

    Formoreinformationvisitusat

    Knowledgeflow.in

    knowledgeflowapps.blogspot.inThankyouforusingKnowledgefloweBooks

  • JAVAFORBEGINNERS1.IntroductiontoJava

    2.Featuresofjava

    3.DataTypes,VariablesandArrays

    4.Operators

    5.Controlstatements

    6.Classesandmethods

    7.Inheritance

    8.PackagesandInterface

    9.ExceptionHandling

    10.EventHandling

    11.TheAppletClass

    12.MoreeBooksandApps

  • DisclaimerThiseBookcontentsisforinformationalandstudypurposesonly.TheKnowledgeflowmakesnoclaims,promises,orguaranteesabouttheaccuracy,completeness,oradequacyofthecontentsofthiseBookandnolegalliabilityorotherresponsibilityisacceptedbyKnowledgeflowforanyerrors,omissions,orstatementsonthiseBook.

  • IntroductiontoJavaJavawasdesignedandconceivedbyJamesGosling,PatrickNaughton,ChrisWarth,EdFrankandMikeSherdan,whichwasdoneatSunMicrosystemsinyear1991.

    Ittookalmost18monthsforjavatocomeintoexistenceasaworkingversion.

    InitiallyjavawasknownasOak,whichwasthenrenamedasJavainyear1995.SincejavahadmuchhadmuchofitscharacterdesignedfromCandC++.

    Thischaracterinheritedbythetwowellknownandsimpleprogrammingmakesjavamoreappealingtocomputeranditgiantswhichwouldleadtoalargescalesuccess.

    ButjavaismisunderstoodasthesophisticatedinternetversionrepresentationofC++.

    IthassignificantdifferencepracticallyandphilosophicallywhencomparedtoC++.

    IfyouhavegoodknowledgeinC++thenyouwillfindjavaasyourcupofteaandyouwillateaseusingandunderstandingjava.

    LogoofJava

    Therefore,therearetwomainreasonsfortheevolutionofthecomputerlanguages.

    JavahadenhancedandrefinedtheobjectorientedscenarioofC++.Thisgavemorefeaturestotheuserswhichareasfollows.

    Multithreading.

    Librarywhichwouldprovideeasyinternetaccess.

    Oneofthejavasmagicwasthebytecode.Bytecodeissetofinstructionwhichis

  • highlyoptimizedanddesignedtobeexecutedbyJVM(JavaVirtualMachine).Itisaninterpreterforbytecode.Thisleadtothedesignoftrulyportableprograms.

    Javaredesignedtheinternetwithnewfeatureandnetworkedprogramwhichareasfollows.

    Applets-Itisakindofjavaprogramthatistobetransmittedoverandexecutedautomaticallybyjavacompatiblewebbrowsers.

    Security-ItprovidedthesecurityofdownloadingvariousappletsandprogramsfrominternetwithoutcontaininganyvirusorTrojanhorses.

    Portability-SincethereislargeanddifferentkindofoperatingsystemsthereforeitprovidesthefreedomofrunninginanyoperatingsystemsoitsprogramcanbeusedindifferentOSwithoutanyissuesofcompatibility.

    Theevolutionsinjavaareasfollows.

    Java1.0

    Java1.1

    Java1.2

    J2SE

    J2SE1.2

    J2SE1.3

    J2SE1.4

    J2SE5

    J2SE5madevariouschangestoJava

    Thenewfeaturethatwasaddedisasfollow.

    Generics

    Annotations

    Autoboxingandauto-unboxing

    Enumerations

    Enhanced,for-eachstyleforloop

    Variable-lengtharguments

    Staticimport

    FormattedI/O

  • Concurrencyutilities

    InJ2SE5,andthedeveloperskitwascalledJDK5.1.5usedasinternalversionnumberandthisisreferredasdeveloperversionnumber.

    Javabecamethecenterofinnovationincomputertechnologicalworld.TheexistenceofJVMandbytecodechangedthescenarioofsecurityandportabilityintheprogrammingworld.ThewaythenewideasareputintothelanguagehasbeenredefinedbytheJCPi.e.javacommunityprocess.

  • FeaturesofJavaObject-orientedprogramming

    Thisisthecorefeatureofjava.Thisistomanagetheincreaseinthecomplexity.Itprovidesaverysophisticatedandwelldefinedinterfaceforthedata.Itisalsoknownasdatacontrollingaccesscode.Anotherimportantfeatureofjavabeingobjectorientedisabstraction.Complexitycanbemanagedusingabstraction.

    ThethreeOOPprinciples

    Encapsulation-Itsagendaistomanipulatethedataandkeepthedataisolatedandsafefromtheexternalinterferenceandmisuse.Theencapsulationisdonebytheuseoftheprotectivewrapper.Thispreventstheexternalsourcesfromaccessingthedataorthecode.

    EncapsulationinJava

    Inheritance-Inthistheobjectwouldacquirethepropertyofotherobjectpresent.Itjustfollowstheconceptofthehierarchicalclassification.Thisconsistsofclasses,subclasses.Inheritancealsoislinkedorinteractswithencapsulationaswell.

  • Inheritance

    Polymorphism-Itismeansmanywaystocarryoutthemethodbutfromoneinput.

    Polymorphism

    Bytecode

    ThisishighlyoptimizedbysetofinstructionsdesignedwhichisdesignedtobeexecutedbyJavavirtualmachinethatisJVM.

    JVM

    Itwasdesignedasaninterpreterforthebytecode.Anotherfeatureofjavaprogramisthatitissimple.Thisenablestheprofessionalstolearn.Workinaveryeffectivemannerbutitisalsoveryeasytounderstand.

    Robust

    TheabilitythatincludescreatingarobustprogramthatcanbeamultiplatformprogramaregivenaveryhighpriorityindesignofJava.

  • Multithreading

    Therealworldrequirementsaremetbyjavawhichhelpstoachievetherequirementofcreatinginteractiveandnetworkedprograms.

    Highperformance

    Theadvantageofbeingamultiplatformfunctioningprogramhelpstofindthecrossplatformsolution.Itprovidesbenefitsofbeinganplatformindependentcodewiththehelpofjavaruntimesystem.

    Distributed

    ThisisbecauseitisbeendesignedfortheinternetwhichhasadistributedenvironmentbecauseofthehandlingofTCP/IPprotocols.Thisallowstheprogramtofindoutmethodsacrossanetwork.URLisusedinthistoaccessafileoninternet.ThispropertysupportsRMI(RemoteMethodInvocation).

    Dynamic

    Thisistheactionthatistakenduringtherun-timesuchastoresolve,verifyandaddobjects.Itprovidesusthefunctionwhichwillallowustolinkcodedynamicallythatwillbesafe.

    Simpleprogram

    /*CallthisfileExample.java*/

    ClassExample{

    Publicstaticvoidmain(stringargs[]){

    System.out.println(thisisasimplejavaprogram.);

    }

    }

    Commandlineargumenttopasstheclassnameis

    C:\>javaExample

    Simpleoutputoftheaboveprogram

  • thisisasimplejavaprogram.

    Callingofthefileinjavacmd

    Callingofthefile:Example.java.

  • DataTypesIntegers

    Itincludeswholevaluedsignednumberswhichareasfollow.

    Byte-Whosewidthis8anditrangesfrom-128to127.Itisthesmallestintegertype.Itisusefulwhenuserisdealingwithstreamorflowingdatafromanetworkorafile.

    Declarationoftwobytevariablescalledxandyisasfollow

    Bytex,y;

    Short-Thewidthofthistypeofintegeris16anditrangesfrom-32,768to32,767.Itistheleastcommonlyuseddatatypeinjava.

    Declaration

    Shorta;

    Shortb;

    Int-Thewidthofthistypeofintegeris32anditrangesfrom-2,147,483,648to2,147,483,647.Itismoreefficientascomparedtobyteandshort.Itiscommonlyusedtocontrolloopsandindexedarrays.

    Declaration

    Inta;

    Long-Thewidthofthistypeofintegeris64anditrangesfrom-9,223,372,036,854,775,808to9,223,372,036,854,775,807.Thisisusedforthosevalueswhicharelargeenoughthattheintegercannothandlethem.

    Declaration

    Intlightspeed;

    Longdays;

    Longsecond;

    Seconds=days*24*60*60;

    Floatingpointtype

    Thisisforrealnumbersusedforcalculationsuchassquareroots,sineandcosine.Theseareoftwotypes.

  • Float-Widthinbitsis32andrangeisfrom1.4e-045to3.4e+038.Floatisusedasavariabletypeforthefractionalcomponent,butspecifiessingleprecision.Itcanbeusedinrepresentingdollarsandcents.

    Declaration

    Floathightemp;

    Double-Widthinbitsis64andrangeisfrom4.9e-324to1.8e+308.itisusedandisoptimizedinsuchawaythatIcanbeusedforhighspeedmathematiccalculation.Ithasdoubleprecisionwhichisfasterthanthesingleprecision.Functionsuchassin()andsqrt()etc,returndoublevalues.

    Declaration

    Doublepi,r,a;

    r=10.4;

    pi=3.14;

    a=pi*r*r;

    Characters

    Thedatatypeusedstoreordeclarecharacterinjavaischar.Itis16-bittypeinjava.Rangeofacharis0to65,536.Therearenocharswhicharenegativeinnature.

    Programdemonstrationforchar

    ClasscharExample

    {

    Publicstaticvoidmain(Stringargs[]){

    Chara,b;

    a=88;

    b=y;

    system.out.print(aandb:);

    system.out.println(a++b);

    }

  • }Booleans

    Itisaprimitivetypeforlogicalvalues.Thistendshaveonlyoneoftwopossiblevalues,trueorfalse.Itisgovernedbyiforforcontrolstatements.

  • VariablesItisbasicunitofstorageandvariableshavescope,visibilityandlifetime.

    Declarationofvariables

    Intx,y,z;

    Or

    Intx=1,y=2,z=5;

    Typeconversionandcasting

    Ifthereisanycompatibilityexistingbetweentwotypesthenjavawouldautomaticallyperformstheconversion.

    Javaautomaticconversion

    Itwillbeperformedwhentwoconditionsaremet.Whenthetwotypesarecompatible;Destinationtypeislargerthanthesourcetype.Afterthetwoconditionsarebeensatisfiedawideningconversiontakesplace.

    Castingcompatibletypes

    Itisasimpleandexplicittypeofconversion.Whenafloatingtypeofconversionisattachedtoanintegertypethistypeofconversioniscalledtruncation.Itisakindofconversionsometimecallednarrowingconversion.

  • ArraysItisagroupofsimilarvariablesthatwouldbereferredbyacommonname.Theelementavailableinthearrayisaccessedthroughindex.Thiscanbecreatedandmayhaveoneormoredimension.

    Typesofarrays

    Therearetwomaintypesofarraysare.

    1. One-dimensionalarrays2. Multi-dimensionalarrays

    One-dimensionalArrays

    Itsalistofsimilartypesofdata.Beforeyoucreatearrayyouneedtocreateavariableofanytype.

    Syntax

    Typevariable-name[];

    Intyear_month[];

    Multi-dimensionalArrays

    Itisarraysofarraysneedtospecifyeachdimensionalarrayvariables,additionalindexusingothersquarebracketsrepresentedas.

    InttwoD[][]=newint[6][7];

  • OperatorsTherearefourmaintypesofoperator.

    ArithmeticoperatorsTheBitwiseoperatorsRelationaloperatorsBooleanlogicaloperators

    Arithmeticoperators

    Addition-Thisoperatorisusedtoaddthevalues.Itisrepresentedby+.ForexampleA=a+4.Subtraction-Thisoperatorisusedtosubtractthevalues.Itisrepresentedby-.ForexampleA=a-4.Multiplication-Thisoperatorisusedtomultiplythevalues.Itisrepresentedby*.ForexampleA=a*4.Division-Thisoperatorisusedtodividethevalues.Itisrepresentedby/.ForexampleA=a/4.Modulus-Thisoperatorisusedtofindtheremainderofthevalueswhendivided.Itisrepresentedby%.ForexampleA=2%4.WhereA=0.Increment-Thisoperatorisusedtoincreasesitsoperandbyone.Itisrepresentedby++.Forexamplea=a++whichisequaltoa=a+1.Decrement:Thisoperatorisusedtodecreasesitsoperandsbyone.Itisrepresentedby.Forexamplea=awhichisequaltoa=a-1.

    Bitwiseoperators

    UnaryNOT-Thisinvertsallofthebitsofoperandcontainedanditisrepresentedby~.

    Forexample

    ~00101010=11010101

    And-Itproduces1bitifbothoperandsarealso1anditisrepresentedby&.

    Forexample

    00101010

    &00001111

    000101010

    OR-Ifeitheroftheoperandisoneitproduces1andItisrepresentedby|.

  • Forexample

    00101010

    |00001111

    00101111

    XOR-Ifeitherofthebitoperandis1,thenresultisalsooneotherwiseits0anditisrepresentedby^.

    Forexample

    00101010

    ^00001111

    00100101

    Leftshift-Itshiftsormovesallofthebitsintheparticulargivenvaluetotheleftsidenumberoftimesthatisbeendeclaredanditisrepresentedby .

    Rightshift-Itshiftsormovesallofthebitsintheparticulargivenvaluetotherightsidenumberoftimesthatisbeendeclaredanditisrepresentedby .

    Relationaloperators

    Equalto-Thisrelationoperatorshowsthatthevaluesareequaltoeachotheranditisrepresentedby==.

    Notequalto-Thisrelationoperatorshowsthatthevaluesarenotequaltoeachotheranditisrepresentedby!=.

    Greaterthan-Thisrelationoperatorshowsthatonevalueisgreaterwhencomparedtootheranditisrepresentedby>.

    Lessthan-Thisrelationoperatorshowsthatonevalueislesswhencomparedtootheranditisrepresentedby=.

    Lessthanorequalto-Thisrelationoperatorshowsthatonevalueissmallerorequalbutnotgreaterwhencomparedtootheranditisrepresentedby

  • A&B=Ifaisfalseandbistrueitresultsasfalse,butisbotharetrueitresultsastrue.Similarlywhenbotharefalseitresultsasfalse.

    LogicalOR-Itissigned|.

    Forexample

    A|B=Ifaisfalseandbistrueitresultsastrue,butisbotharetrueitresultsastrue.Similarlywhenbotharefalseitresultsasfalse.

    LogicalXOR-Itisshownusing^.

    Forexample

    A^B=Ifaisfalseandbistrueitresultsastrue,butisbotharetrueitresultsasfalse.Similarlywhenbotharefalseitresultsasfalse.

    LogicalUnaryNot-Itisdepictedas!.

    Forexample

    !A=Ifaisfalseitresultsastrue,butifaistrueitresultsasfalse.

    Assignmentoperators

    Theassignmentisthesingleequalsignthatisrepresentedby=.

    Thegeneralrepresentation

    var=expression;

    Inthisthevariable,whichisrepresentedas var shouldbecompatiblewiththetypeofexpression.

    Inta,b,c;

    a=b=c=100;

    The?Operator

    Thisisusedforreplacementofifthenelsestatementsanditisrepresentedas?.

    Forexample

    expressiona?expressionb:expressionc

    Thisaboveexamplestatesthatiftheexpressionaistruethenexpressionbisevaluatedotherwiseexpressioncisevaluated.

  • ControlStatementsTherethreetypesofstatementsinjava.

    1. Selectionstatements2. Iterationstatements3. Jumpstatements

    Selectionstatements

    Itistomanagetheflowofprogramsthatistobeexecutedbasedonthedynamicconditionswhichcanbeonlyrealizedduringtheruntime.Itprovidesflexibility.

    Ifstatement-Itprovidesdifferentpathsforexecutionofprogram.

    Syntax

    If(conditionprovided)statementa;

    Else

    Statementb;

    Thismeansiftheconditionistrue,thenstatementaisexecutedbutiffalsethenstatementbisexecuted.

    Forexample

    inta,b;

    If(x0)

    {

    System.out.println(tick+n);

    n;

    }

    }

    }

    Output

    Itwilltick5times

    Tick5

    Tick4

  • Tick3

    Tick2

    Tick1

    Do-whilestatement

    Thisloopexecutesitsbodyatleastoncebecauseitcontainsitsconditionexpressionatthebottomoftheloop.

    Syntax

    do

    {

    System.out.println(tick+n);

    n;

    }

    Whilen>0);

    }

    }

    Forstatement

    Itisaverypowerfulaswellasveryversatileconstruct.Theconditionwhatisprovidedinforstatementuntilandunlesstheconditionisnotbeensatisfieditwontexecute.Iftheconditionisevaluatedandthevalueisfalsethenitisterminated.

    Syntax

    For(initialize;condition;iterate)

    {

    Body

    }

    Forexample

    Classfortick

    {

  • Publicstaticvoidmain(stringargs[])

    {

    Intn;

    For(n=11;n>0;n);

    }

    }

    Jumpstatements

    Javasupportsthreejumpstatementswhichareasfollows.

    1. Break2. Continue3. Return

    Break

    Itisusedtoterminateastatementwhichisinsequenceinaswitchstatementanditcanbeusedforexitingaloop.SometimeItcanbeusedinsteadofgoto.

    Continue

    Itprovidesanearlyiterationforaloop.

    Forexample

    Classcontinue

    {

    Publicstaticvoidmain(stringargs[])

    {

    For(inti=0;i

  • }}

    Return

    ItisusedtoreturnfromamethodandItisatransferbackcallingofthemethod.

    Forexample

    Classreturn{

    Publicstaticvoidmain(stringargs[])

    {

    Booleant=true;

    System.out.println(return);

    If(t)return;

    System.out.println(thiswontwork);

    }

    }

  • ClassesandMethodsClassesmightcontainonlycodeordatabutmayalsocontainboth.Aclassisdeclaredbykeywordclassanditcanbecomplexinnature.

    Syntax

    Classclassname

    {

    Typeinstance-variablea;

    Typeinstance-variableb;

    .

    .

    .

    Typeinstance-variablen;

    }

    Typemethoda(parameter-list)

    {

    //bodyofmethod

    }

    Typemethodnamea(parameter-list)

    //bodyofmethod

    .

  • .}

    }

    Classesarealsocalledtheboxwhichdefinesvariable-width,heightanddepth.

    Example

    Classbox

    {

    Doublewidth;

    Doubleheight;

    Doubledepth;

    }

    Classthatimplementsstackofdataandinteger.

    Example

    Classstack

    {

    Intstk[]=newint[10];

    Stack()

    Tos=-1

    }

    Voidpush(intitem){

    If(tos==9)

    System.out.println(itsfull);

    Else

    Stk[++tos]=item;

  • }Intpop()

    {if(tos

  • OverloadingmethodWhentwoormoremethodsaredefinedinthesameplaceandthenamedefinedissamebuttheparametersaredifferent.Thismethodisanoverloadingmethod.Thisprovidespolymorphisminjava.

    Example

    Classoverload1

    {

    Voidtest(){

    System.out.println(noparameter);

    }

    Voidtest(inta)

    {

    System.out.println(a:+a);

    }

    Voidtest(inta,intb)

    {

  • System.out.println(aandb:+a++b);

    }

    Doubletest(doublea)

    {

    System.out.println(doublea:+a);

    Returna*a;

    }

    }

    Classoverload

    {

    Publicstaticvoidmain(stringargs[])

    {

    Overload1ob=newoverload();

    Doubleresult;

    ob.test();

    ob.test(10);

    ob.test(10,20);

    Result=ob.test(123.25);

    System.out.println(result:+result);

    }

    }

  • Output

    A=10

    AandB=1020

    Doublea=123.25

    Result=15190.5625

  • InheritanceInheritanceisasuperclassfromwhichalltheclassesareinheritedandwhichdoesinheritingfromasuperclassiscalledthesubclass.

    Basicprogramofinheritance

    Classx

    {

    inti,j;

    voidshowIj()

    {

    System.out.println(iandj:+i++j);

    }

    }

    Classyextendsx

    Inta;{

    System.out.println(a:+a);

    }

    Voidsum()

    {

    System.out.println(i+j+a:+(i+j+a));

    }

    }

    Classsimpinheritance

    {

    Publicstaticvoidmain(stringargs[])

    {

    qSuperob=newq();

  • psuperob=newp();

    Subob.i=8;

    Subob.j=7;

    Subob.a=9;

    System.out.println(contents);

    Subob.showij();

    Subob.showa();

    System.out.println(sumofi,janda);

    }

    }

    Output

    Contents:Iandj:87

    a:9

    Sumofi,janda:i+j+a:24

    Mainuseofinheritanceinjavaisforoverridingandcodereusability.

    Overriding

    Whensubclassesareidenticalofasuperclassthisscenarioiscalledmethodoverriding.Itprovidesthecharacteristiccalledpolymorphisminjava.

    Inheritanceshowingoverriding

  • Examplecode

    Classx{

    inta,b

    X(intp,intq)

    {

    p=a;

    q=b;

    }

    Voidshow()

    {

    System.out.println(aandb:+i++j);

    }

    }

    Classyextendsx{

    Intr;

    Y(inta,intb,intc)

    {

    Super(a,b);

    r=c;

    }

    Voidshow(){

    System.out.println(r:+r);

    }

    }

    Classoverride{

    Publicstaticvoidmain(stringargs[])

    {

  • ysubob=newy(1,2,3);

    Subob.Show();

    }

    }

    Output

    r=3

    Typesofinheritance

    Therearethreetypesofinheritance.

    SingleinheritanceMultipleinheritanceHierarchicalinheritance

    Typesofinheritance

    Injavamultipleandhybridwillonlysupportedwithuseofinterface.

    Multipleandhybridinheritance

  • PackagesPackagescontainnameswereclassesarestored.

    Syntax

    Packagepkg;

    Torepresentmultipackaging

    Packagepkgx[.pkgy[.pkgz]];

    Forexample

    Packagejava.awt.imagea;

    Findingofpackages

    Therearethreewaystofindthepackages.Thejavaruntimesystemusestheworkingdirectory;ifthepackageiscontainedinthesubdirectorythenitwillbediscoveredoryoucansetthelocationbysettingthelocationofclassasshown.

    Packagempack

    Itcanuseclasspathwithjavaaswellasjavactospecifythelocationofclassasshown.C:\ myprograms\java\mpack

    Accessprotection

    Fortheprotectionofpackagestherearethreespecifiersinexistenceinjava.

    1. Private-cannotbeseenoraccessedfromoutsidetheclass.2. Public-ithasfeaturetobeaccessedfromanywhere.3. Protected-thiscanbeaccessedonlybyclasseswhicharesub-classes.

    Packagesyntax

    Importingapackage

    Thestatementthatimportsthepackagecomeimmediatelyafterthepackagingstatementanditsmainfunctionistoimportthepackagebysavingmoretimetoitslocation.

    Syntax

  • Importpkga[.pkgb].(classnamed*);

  • InterfaceItissimilartoclasswhichcontainsconstants,methodsandsignatures.

    Javasimplecalculatorinterface

    Interfaceforjava

    Declaration

    Accessinterfacem

    {

    Returnmethod1(parameterlist);

    Returnmethod2(parameterlist);

    Typefinalvariablename1=value;

    Typefinalvariablename2=value;

    //

    Returntypemethodnamen(parameterlist);

    Typefinalvarnamen=value;

    }

    Simpleinterfacecontainsonlyonefunctionormethodknownascallbackfunction.

    Forexample

  • Interfacecallback

    {

    Voidcallback(intparm);

    }

    Implementinginterface

    Tocreatinganyinterfaceimplementationofclassisincludedindefinitionofaclass.

    Forexample

    Classclientcallback

    {

    Publicvoidcallback(intx)

    {

    System.out.println(callback+x);

    }

    }

  • ExceptionalHandlingItisadrawbackthataffectstheperformanceofjavaprogrambecauseitcanoccuratanypoint.Itoccurrenceisatexecutionstate.

    Reasons

    InvaliddataFileabsentLossofnetworkconnectionandtimeoutwhentheJVMisatrun.

    Thecommonexceptionsare.

    Checked-Theseexceptionscannotbeforecastedbytheprogrammeranditcannotbeevenignoredduring.

    Runtime-Thisisadynamicexception,butitcanbeignoredunlikethecheckedone.

    Errors-Thesearealsoignoredbecausenothingcanbedonetoovercomeitandthisisnotunderprogrammerscontrol.

    Exceptionhierarchy

    Ithastwosubdivisions:Inputoutputexceptionclassesandruntimeexceptionclass.

    Throw

    TheseareexceptionswhicharethrownbyJVMduringruntime.

    Syntax

    throwThrowableinstance;

  • Throw

    Whenthisstatementisusedthereisanimmediatestopintheexecutionofprogram.

    Forexample

    Classthrowdem

    {

    Staticvoiddemopro()

    {

    Try{

    ThrownewNullPointerException(dem);

    }catch(NullPointerExceptione)

    {

    System.out.println(caughtinsidedemopro.);

    Throwe;

    }

    }

    Publicstaticvoidmain(stringargs[]{

  • Try{

    Demopro();

    }

    Catch(NullPointerExceptione){

    System.out.println(recatch:+e);

    }

    }

    }

    Finally

    Itisacodethatisusedinexecutingbeforeorafterthetryandcatchblockisexecutedorcompleted.

    Syntax

    Classfinallydem

    {

    Staticvoidprox()

    {

    Try

    {

    System.out.println(inprocx);

    ThrownewruntimeException(demo);

    }

    Finally

    {

    System.out.println(proxfinally);

    }

    }

  • EventhandlingEvent

    Itshowsthechangeinstateofasource.

    Eventsources

    Itisanobjectgeneratinganevent.

    Syntax

    PublicvoidaddTypeListener(TypeListnerl)

    Forexample

    Addkeylistner()-toregisterakeyboardevent.Addmousemotionlistner()-toregisteramousemotionlistener.

    ActionEventClass

    Thishappenswhenbuttonispressed.Doubleclickingoftheitemoranyiteminthemenuisselected.

    Eventoccurrenceinjava

    Keyeventclass

    Thisgeneratedfromthekeyinputofthekeyboardandtherearethreetypesofkeyevents.

    1. KEY_PRESSED

  • 2. KEY_RELEASED3. KEY_TYPED.

    Mouseeventclass

    Thereareeighttypesofmouseeventclasses.

    1. MOUSE_DRAGGED2. MOUSE_CLICKED3. MOUSE_ENTERED4. MOUSE_EXITED5. MOUSE_MOVED6. MOUSE_PRESSED7. MOUSE_RELEASED8. MOUSE_WHEELED

    Actionlistenerinterface

    Itisusedtodefinetheactionstheseareallperformedwhichareinvokedatthecallofanevent.Itisusedtoknowthereactionofthemethod.

  • TheAppletclassItcontainsseveralmethodswhichareusefulforjavaexecutionanddetailedcontrol.TheAppletinitializationandterminationareasfollow.

    Forstarting

    init()-Usedtoinitializemethoditisthefirstmethod.

    start()-Afterinitializationmethodthismethodcomesanditsfunctionistorestartordisplayonscreen.

    paint()-Inthistheoutputoftheappletisredrawneachtimeitiscalled.

    Forstopping

    stop()-Itistoleavethebrowserwhichisopenedandcontainsapplet.

    destroy()-Itisfortheappletoncewhichhastoremovedfromthememory.

    Appletgeneration

    HTMLapplettag

  • WIDTH=pixelsHEIGHT=pixels

    [ALIGN=alignment]

    [VSPACE=pixels][HSPACE=pixels]

    >

    [PARANAME=attributenameVALUE=attributevalue>]

    [HTMLdisplayedinabsenceofjava]

    HTMLApplettag

    TheAudioclipinterface

    play()-Tobegintheaudio.

    stop()-Tostoptheaudio.

    loop()-Toplaytheloopwithoutbreak.

    TheAppletsubinterface

    ItprovidesalinkthroughwhichanAppletandthebrowsercancommunicate.

  • Knowledgeflow:moreeBooksandAppsGetmorePlayBooksGetmoreKindleeBooksGetmoreappsfromGooglePlaystoreGetmoreappsfromAmazonappstore