“learning starts with viewing the world...
TRANSCRIPT
“LEARNINGSTARTSWITHVIEWINGTHEWORLDDIFFERENTLY.”
Knowledgeflow-Amobilelearningplatformprovidesapps,eBooksandvideotutorials
KnowledgeflowbringsyoulearningeBookofJavaforBeginners.ThiseBookisforallinformationtechnologyandcomputersciencestudentsandprofessionalsacrosstheworld.
Followuson
Googleplus
Formoreinformationvisitusat
Knowledgeflow.in
knowledgeflowapps.blogspot.in
ThankyouforusingKnowledgefloweBooks
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.
Initiallyjavawasknownas“Oak”,whichwasthenrenamedas“Java”inyear1995.SincejavahadmuchhadmuchofitscharacterdesignedfromCandC++.
Thischaracterinheritedbythetwowellknownandsimpleprogrammingmakesjavamoreappealingtocomputeranditgiantswhichwouldleadtoalargescalesuccess.
ButjavaismisunderstoodasthesophisticatedinternetversionrepresentationofC++.
IthassignificantdifferencepracticallyandphilosophicallywhencomparedtoC++.
IfyouhavegoodknowledgeinC++thenyouwillfindjavaasyourcupofteaandyouwillateaseusingandunderstandingjava.
LogoofJava
Therefore,therearetwomainreasonsfortheevolutionofthecomputerlanguages.
JavahadenhancedandrefinedtheobjectorientedscenarioofC++.Thisgavemorefeaturestotheuserswhichareasfollows.
Multithreading.
Librarywhichwouldprovideeasyinternetaccess.
Oneofthejava’smagicwasthebytecode.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
/*Callthisfile“Example.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
It’salistofsimilartypesofdata.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=a—whichisequaltoa=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“<”.
Greaterthanorequalto-Thisrelationoperatorshowsthatonevalueisgreaterorequalbutnotlesswhencomparedtootheranditisrepresentedby“>=”.
Lessthanorequalto-Thisrelationoperatorshowsthatonevalueissmallerorequalbutnotgreaterwhencomparedtootheranditisrepresentedby“<=”.
Booleanlogicaloperators
LogicalAND-Itisrepresentedby“&”.
Forexample
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(x<y)a=0;
Else
b=0;
Nowthereisonetypeofprocedureusingifstatementi.e.nestedifstatementanditisverycommonmethodinprogrammingworld.
Forexample
If(a==10){
If(b<15)i=j;
If(c>50)p=q;
Else
i=p;
}
Else
i=q;
Now,thesecondifstatementintheparenthesisisassociatedwithelse.Anothertypeofprocedureisofusingifstatementistheif-else-ifladderstatement.
Forexample
If(condition)
Statement;
Elseif(condition)
Statement;
Elseif(condition)
Statement;
.
.
.
.
.
Else
Statement;
Switchstatements
Itisamultibranchedstatement.
Syntax
Switch(expression)
{
Casevalue1:
Statement
Break;
Casevalue2:
Statement
Break;
.
.
.
Casevalen:
Statement
Break;
Default:
Statement;
}
Thefunctioningoftheswitchstatementiscomparesthegivenvaluewithallthecasesandwhenthematchfoundtheprogramsequenceisexecuted.
Forexample
Classsampswitch{
Publicstaticvoidmain(stringargs[])
{
Switch(i)
{
Case0:
System.out.println(“iiszero.”);
Break;
Case1:
System.out.println(“iisone.”)
Break;
Default:
System.out.println(“iisgreaterthan4.”)
}
Output
iiszero.
iisone.
iisgreaterthan4.
iisgreaterthan4.
Exampleofnestedswitchloopprogram
Switch(countfigures)
{
Case1:
Switch(targetvalue)
{//nestedswitch//
Case0:
System.out.println(“targetiszero”;
Break;
Case1:
System.out.println(“targetisone”;
Break;
}
Break;
Case2://…
Importantfeaturesofswitchstatementare.
Switchstatementcanonlycheckforequalityunlikeif.Therecannotbetwocasesconstantinthesameswitchwithidenticalvalues.Itismoreeffectivethanusingthesetofnestedifstatement.
Iterationstatements
Thesestatementsareusedtocreateloop.Therearethreetypesofiterationstatementusedinjava.
Whilestatement
Itsfunctionistorepeatorblockstatementwhileitscontrollingexpressionistrue.
Syntax
While(condition){
//bodyofloop
}
Theloopisexecutedwhentheconditionistrue.Whenitisfalsethecontrolwillpasstothenextlineofthecodefollowingtheloop.
Forexample
Classwhile{
Publicstaticvoidmain(stringargs[])
{
Intn=5;
While(n>0)
{
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.Theconditionwhatisprovidedinforstatementuntilandunlesstheconditionisnotbeensatisfieditwon’texecute.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<5;i++)
{
System.out.print(i+““);
If(i%2==0)continue;
System.out.print(““);
}
}
}
Return
ItisusedtoreturnfromamethodandItisatransferbackcallingofthemethod.
Forexample
Classreturn{
Publicstaticvoidmain(stringargs[])
{
Booleant=true;
System.out.println(“return”);
If(t)return;
System.out.println(“thiswon’twork”);
}
}
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(‘it’sfull”);
Else
Stk[++tos]=item;
}
Intpop()
{if(tos<0){
System.out.println(“stackunderflow”);
Return0;
}else
Returnstk[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-Thesearealsoignoredbecausenothingcanbedonetoovercomeitandthisisnotunderprogrammer’scontrol.
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
<APPLET
[CODEBASE=codebaseurl]
CODE=appletfile
[ALT=alternatetext]
[NAME=appletinstancename]
WIDTH=pixelsHEIGHT=pixels
[ALIGN=alignment]
[VSPACE=pixels][HSPACE=pixels]
>
[PARANAME=attributenameVALUE=attributevalue>]
…
[HTMLdisplayedinabsenceofjava]
</APPLET>
HTMLApplettag
TheAudioclipinterface
play()-Tobegintheaudio.
stop()-Tostoptheaudio.
loop()-Toplaytheloopwithoutbreak.
TheAppletsubinterface
ItprovidesalinkthroughwhichanAppletandthebrowsercancommunicate.
Knowledgeflow:moreeBooksandAppsGetmorePlayBooksGetmoreKindleeBooksGetmoreappsfromGooglePlaystoreGetmoreappsfromAmazonappstore