Java for Beginners by Knowledge flow

background image
background image

“LEARNINGSTARTSWITHVIEWINGTHEWORLDDIFFERENTLY.”

Knowledgeflow-Amobilelearningplatformprovidesapps,eBooksandvideotutorials

KnowledgeflowbringsyoulearningeBookofJavaforBeginners.ThiseBookisforall

informationtechnologyandcomputersciencestudentsandprofessionalsacrosstheworld.

Followuson

Facebook

Googleplus

Twitter

Formoreinformationvisitusat

Knowledgeflow.in

knowledgeflowapps.blogspot.in

ThankyouforusingKnowledgefloweBooks

background image

JAVAFORBEGINNERS

1.IntroductiontoJava

2.Featuresofjava

3.DataTypes,VariablesandArrays

4.Operators

5.Controlstatements

6.Classesandmethods

7.Inheritance

8.PackagesandInterface

9.ExceptionHandling

10.EventHandling

11.TheAppletClass

12.MoreeBooksandApps

background image
background image

Disclaimer

ThiseBookcontentsisforinformationalandstudypurposesonly.TheKnowledgeflow

makesnoclaims,promises,orguaranteesabouttheaccuracy,completeness,oradequacy

ofthecontentsofthiseBookandnolegalliabilityorotherresponsibilityisacceptedby

Knowledgeflowforanyerrors,omissions,orstatementsonthiseBook.

background image
background image

IntroductiontoJava

JavawasdesignedandconceivedbyJamesGosling,PatrickNaughton,Chris

Warth,EdFrankandMikeSherdan,whichwasdoneatSunMicrosystemsinyear

1991.

Ittookalmost18monthsforjavatocomeintoexistenceasaworkingversion.

Initiallyjavawasknownas“Oak”,whichwasthenrenamedas“Java”inyear1995.

SincejavahadmuchhadmuchofitscharacterdesignedfromCandC++.

Thischaracterinheritedbythetwowellknownandsimpleprogrammingmakes

javamoreappealingtocomputeranditgiantswhichwouldleadtoalargescale

success.

Butjavaismisunderstoodasthesophisticatedinternetversionrepresentationof

C++.

IthassignificantdifferencepracticallyandphilosophicallywhencomparedtoC++.

IfyouhavegoodknowledgeinC++thenyouwillfindjavaasyourcupofteaand

youwillateaseusingandunderstandingjava.

LogoofJava

Therefore,therearetwomainreasonsfortheevolutionofthecomputerlanguages.

JavahadenhancedandrefinedtheobjectorientedscenarioofC++.Thisgavemore

featurestotheuserswhichareasfollows.

Multithreading.

Librarywhichwouldprovideeasyinternetaccess.

Oneofthejava’smagicwasthebytecode.Bytecodeissetofinstructionwhichis

background image

highlyoptimizedanddesignedtobeexecutedbyJVM(JavaVirtualMachine).Itis

aninterpreterforbytecode.Thisleadtothedesignoftrulyportableprograms.

Javaredesignedtheinternetwithnewfeatureandnetworkedprogramwhichareas

follows.

Applets-Itisakindofjavaprogramthatistobetransmittedoverandexecuted

automaticallybyjavacompatiblewebbrowsers.

Security-Itprovidedthesecurityofdownloadingvariousappletsandprograms

frominternetwithoutcontaininganyvirusorTrojanhorses.

Portability-Sincethereislargeanddifferentkindofoperatingsystemsthereforeit

providesthefreedomofrunninginanyoperatingsystemsoitsprogramcanbeused

indifferentOSwithoutanyissuesofcompatibility.

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

background image

Concurrencyutilities

InJ2SE5,andthedeveloperskitwascalledJDK5.1.5usedasinternalversionnumber

andthisisreferredasdeveloperversionnumber.

Javabecamethecenterofinnovationincomputertechnologicalworld.Theexistenceof

JVMandbytecodechangedthescenarioofsecurityandportabilityintheprogramming

world.ThewaythenewideasareputintothelanguagehasbeenredefinedbytheJCPi.e.

javacommunityprocess.

background image
background image

FeaturesofJava

Object-orientedprogramming

Thisisthecorefeatureofjava.

Thisistomanagetheincreaseinthecomplexity.

Itprovidesaverysophisticatedandwelldefinedinterfaceforthedata.

Itisalsoknownasdatacontrollingaccesscode.

Anotherimportantfeatureofjavabeingobjectorientedisabstraction.

Complexitycanbemanagedusingabstraction.

ThethreeOOPprinciples

Encapsulation-Itsagendaistomanipulatethedataandkeepthedataisolatedand

safefromtheexternalinterferenceandmisuse.Theencapsulationisdonebytheuse

oftheprotectivewrapper.Thispreventstheexternalsourcesfromaccessingthedata

orthecode.

EncapsulationinJava

Inheritance-Inthistheobjectwouldacquirethepropertyofotherobjectpresent.It

justfollowstheconceptofthehierarchicalclassification.Thisconsistsofclasses,

subclasses.Inheritancealsoislinkedorinteractswithencapsulationaswell.

background image

Inheritance

Polymorphism-Itismeansmanywaystocarryoutthemethodbutfromoneinput.

Polymorphism

Bytecode

Thisishighlyoptimizedbysetofinstructionsdesignedwhichisdesignedtobeexecuted

byJavavirtualmachinethatisJVM.

JVM

Itwasdesignedasaninterpreterforthebytecode.

Anotherfeatureofjavaprogramisthatitissimple.

Thisenablestheprofessionalstolearn.

Workinaveryeffectivemannerbutitisalsoveryeasytounderstand.

Robust

Theabilitythatincludescreatingarobustprogramthatcanbeamultiplatformprogram

aregivenaveryhighpriorityindesignofJava.

background image

Multithreading

Therealworldrequirementsaremetbyjavawhichhelpstoachievetherequirementof

creatinginteractiveandnetworkedprograms.

Highperformance

Theadvantageofbeingamultiplatformfunctioningprogramhelpstofindthecross

platformsolution.

Itprovidesbenefitsofbeinganplatformindependentcodewiththehelpofjavarun

timesystem.

Distributed

Thisisbecauseitisbeendesignedfortheinternetwhichhasadistributed

environmentbecauseofthehandlingofTCP/IPprotocols.

Thisallowstheprogramtofindoutmethodsacrossanetwork.

URLisusedinthistoaccessafileoninternet.

ThispropertysupportsRMI(RemoteMethodInvocation).

Dynamic

Thisistheactionthatistakenduringtherun-timesuchastoresolve,verifyandadd

objects.

Itprovidesusthefunctionwhichwillallowustolinkcodedynamicallythatwillbe

safe.

Simpleprogram

/*Callthisfile“Example.java”*/

ClassExample{

Publicstaticvoidmain(stringargs[]){

System.out.println(“thisisasimplejavaprogram.”);

}

}

Commandlineargumenttopasstheclassnameis

C:\>javaExample

Simpleoutputoftheaboveprogram

background image

thisisasimplejavaprogram.

Callingofthefileinjavacmd

Callingofthefile:“Example.java”.

background image
background image

DataTypes

Integers

Itincludeswholevaluedsignednumberswhichareasfollow.

Byte-Whosewidthis8anditrangesfrom-128to127.Itisthesmallestintegertype.Itis

usefulwhenuserisdealingwithstreamorflowingdatafromanetworkorafile.

Declarationoftwobytevariablescalledxandyisasfollow

Bytex,y;

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

theleastcommonlyuseddatatypeinjava.

Declaration

Shorta;

Shortb;

Int-Thewidthofthistypeofintegeris32anditrangesfrom-2,147,483,648to

2,147,483,647.Itismoreefficientascomparedtobyteandshort.Itiscommonlyusedto

controlloopsandindexedarrays.

Declaration

Inta;

Long-Thewidthofthistypeofintegeris64anditrangesfrom

-9,223,372,036,854,775,808to9,223,372,036,854,775,807.Thisisusedforthosevalues

whicharelargeenoughthattheintegercannothandlethem.

Declaration

Intlightspeed;

Longdays;

Longsecond;

Seconds=days*24*60*60;

Floatingpointtype

Thisisforrealnumbersusedforcalculationsuchassquareroots,sineandcosine.These

areoftwotypes.

background image

Float-Widthinbitsis32andrangeisfrom1.4e-045to3.4e+038.Floatisusedasa

variabletypeforthefractionalcomponent,butspecifiessingleprecision.Itcanbeusedin

representingdollarsandcents.

Declaration

Floathightemp;

Double-Widthinbitsis64andrangeisfrom4.9e-324to1.8e+308.itisusedandis

optimizedinsuchawaythatIcanbeusedforhighspeedmathematiccalculation.Ithas

doubleprecisionwhichisfasterthanthesingleprecision.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);

}

background image

}

Booleans

Itisaprimitivetypeforlogicalvalues.

Thistendshaveonlyoneoftwopossiblevalues,trueorfalse.

Itisgovernedbyiforforcontrolstatements.

background image

Variables

Itisbasicunitofstorageandvariableshavescope,visibilityandlifetime.

Declarationofvariables

Intx,y,z;

Or

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

Typeconversionandcasting

Ifthereisanycompatibilityexistingbetweentwotypesthenjavawouldautomatically

performstheconversion.

Javaautomaticconversion

Itwillbeperformedwhentwoconditionsaremet.

Whenthetwotypesarecompatible;

Destinationtypeislargerthanthesourcetype.

Afterthetwoconditionsarebeensatisfiedawideningconversiontakesplace.

Castingcompatibletypes

Itisasimpleandexplicittypeofconversion.

Whenafloatingtypeofconversionisattachedtoanintegertypethistypeof

conversioniscalledtruncation.

Itisakindofconversionsometimecallednarrowingconversion.

background image

Arrays

Itisagroupofsimilarvariablesthatwouldbereferredbyacommonname.

Theelementavailableinthearrayisaccessedthroughindex.

Thiscanbecreatedandmayhaveoneormoredimension.

Typesofarrays

Therearetwomaintypesofarraysare.

1. One-dimensionalarrays

2. Multi-dimensionalarrays

One-dimensionalArrays

It’salistofsimilartypesofdata.Beforeyoucreatearrayyouneedtocreateavariableof

anytype.

Syntax

Typevariable-name[];

Intyear_month[];

Multi-dimensionalArrays

Itisarraysofarraysneedtospecifyeachdimensionalarrayvariables,additionalindex

usingothersquarebracketsrepresentedas.

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

background image
background image

Operators

Therearefourmaintypesofoperator.

Arithmeticoperators

TheBitwiseoperators

Relationaloperators

Booleanlogicaloperators

Arithmeticoperators

Addition-Thisoperatorisusedtoaddthevalues.Itisrepresentedby“+“.For

example

A=a+4.

Subtraction-Thisoperatorisusedtosubtractthevalues.Itisrepresentedby“-“.

Forexample

A=a-4.

Multiplication-Thisoperatorisusedtomultiplythevalues.Itisrepresentedby“*“.

Forexample

A=a*4.

Division-Thisoperatorisusedtodividethevalues.Itisrepresentedby“/“.For

example

A=a/4.

Modulus-Thisoperatorisusedtofindtheremainderofthevalueswhendivided.It

isrepresentedby“%“.Forexample

A=2%4.WhereA=0.

Increment-Thisoperatorisusedtoincreasesitsoperandbyone.Itisrepresentedby

“++“.Forexample

a=a++whichisequaltoa=a+1.

Decrement:Thisoperatorisusedtodecreasesitsoperandsbyone.Itisrepresented

by“—“.Forexample

a=a—whichisequaltoa=a-1.

Bitwiseoperators

UnaryNOT-Thisinvertsallofthebitsofoperandcontainedanditisrepresentedby“~“.

Forexample

~00101010=11010101

And-Itproduces1bitifbothoperandsarealso1anditisrepresentedby“&“.

Forexample

00101010

&00001111

000101010

OR-Ifeitheroftheoperandisoneitproduces1andItisrepresentedby“|“.

background image

Forexample

00101010

|00001111

00101111

XOR-Ifeitherofthebitoperandis1,thenresultisalsooneotherwiseits0anditis

representedby“^”.

Forexample

00101010

^00001111

00100101

Leftshift-Itshiftsormovesallofthebitsintheparticulargivenvaluetotheleftside

numberoftimesthatisbeendeclaredanditisrepresentedby” ≪ ”.

Rightshift-Itshiftsormovesallofthebitsintheparticulargivenvaluetotherightside

numberoftimesthatisbeendeclaredanditisrepresentedby” ≫ ”.

Relationaloperators

Equalto-Thisrelationoperatorshowsthatthevaluesareequaltoeachotheranditis

representedby“==”.

Notequalto-Thisrelationoperatorshowsthatthevaluesarenotequaltoeachotherand

itisrepresentedby“!=”.

Greaterthan-Thisrelationoperatorshowsthatonevalueisgreaterwhencomparedto

otheranditisrepresentedby“>”.

Lessthan-Thisrelationoperatorshowsthatonevalueislesswhencomparedtootherand

itisrepresentedby“<”.

Greaterthanorequalto-Thisrelationoperatorshowsthatonevalueisgreaterorequal

butnotlesswhencomparedtootheranditisrepresentedby“>=”.

Lessthanorequalto-Thisrelationoperatorshowsthatonevalueissmallerorequalbut

notgreaterwhencomparedtootheranditisrepresentedby“<=”.

Booleanlogicaloperators

LogicalAND-Itisrepresentedby“&”.

Forexample

background image

A&B=Ifaisfalseandbistrueitresultsasfalse,butisbotharetrueitresultsas

true.Similarlywhenbotharefalseitresultsasfalse.

LogicalOR-Itissigned|.

Forexample

A|B=Ifaisfalseandbistrueitresultsastrue,butisbotharetrueitresultsas

true.Similarlywhenbotharefalseitresultsasfalse.

LogicalXOR-Itisshownusing“^”.

Forexample

A^B=Ifaisfalseandbistrueitresultsastrue,butisbotharetrueitresultsas

false.Similarlywhenbotharefalseitresultsasfalse.

LogicalUnaryNot-Itisdepictedas“!”.

Forexample

!A=Ifaisfalseitresultsastrue,butifaistrueitresultsasfalse.

Assignmentoperators

Theassignmentisthesingleequalsignthatisrepresentedby“=”.

Thegeneralrepresentation

var=expression;

Inthisthevariable,whichisrepresentedas var shouldbecompatiblewiththetypeof

expression.

Inta,b,c;

a=b=c=100;

The?Operator

Thisisusedforreplacementofifthenelsestatementsanditisrepresentedas“?”.

Forexample

expressiona?expressionb:expressionc

Thisaboveexamplestatesthatiftheexpressionaistruethenexpressionbisevaluated

otherwiseexpressioncisevaluated.

background image
background image
background image

ControlStatements

Therethreetypesofstatementsinjava.

1. Selectionstatements

2. Iterationstatements

3. Jumpstatements

Selectionstatements

Itistomanagetheflowofprogramsthatistobeexecutedbasedonthedynamic

conditionswhichcanbeonlyrealizedduringtheruntime.

Itprovidesflexibility.

Ifstatement-Itprovidesdifferentpathsforexecutionofprogram.

Syntax

If(conditionprovided)statementa;

Else

Statementb;

Thismeansiftheconditionistrue,thenstatementaisexecutedbutiffalsethenstatement

bisexecuted.

Forexample

inta,b;

If(x<y)a=0;

Else

b=0;

Nowthereisonetypeofprocedureusingifstatementi.e.nestedifstatementanditisvery

commonmethodinprogrammingworld.

Forexample

If(a==10){

If(b<15)i=j;

If(c>50)p=q;

Else

background image

i=p;

}

Else

i=q;

Now,thesecondifstatementintheparenthesisisassociatedwithelse.Anothertypeof

procedureisofusingifstatementistheif-else-ifladderstatement.

Forexample

If(condition)

Statement;

Elseif(condition)

Statement;

Elseif(condition)

Statement;

.

.

.

.

.

Else

Statement;

Switchstatements

Itisamultibranchedstatement.

Syntax

Switch(expression)

{

Casevalue1:

Statement

background image

Break;

Casevalue2:

Statement

Break;

.

.

.

Casevalen:

Statement

Break;

Default:

Statement;

}

Thefunctioningoftheswitchstatementiscomparesthegivenvaluewithallthecasesand

whenthematchfoundtheprogramsequenceisexecuted.

Forexample

Classsampswitch{

Publicstaticvoidmain(stringargs[])

{

Switch(i)

{

Case0:

System.out.println(“iiszero.”);

Break;

Case1:

System.out.println(“iisone.”)

Break;

background image

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.

background image

Iterationstatements

Thesestatementsareusedtocreateloop.Therearethreetypesofiterationstatementused

injava.

Whilestatement

Itsfunctionistorepeatorblockstatementwhileitscontrollingexpressionistrue.

Syntax

While(condition){

//bodyofloop

}

Theloopisexecutedwhentheconditionistrue.Whenitisfalsethecontrolwillpassto

thenextlineofthecodefollowingtheloop.

Forexample

Classwhile{

Publicstaticvoidmain(stringargs[])

{

Intn=5;

While(n>0)

{

System.out.println(“tick“+n);

n—;

}

}

}

Output

Itwilltick5times

Tick5

Tick4

background image

Tick3

Tick2

Tick1

Do-whilestatement

Thisloopexecutesitsbodyatleastoncebecauseitcontainsitsconditionexpressionatthe

bottomoftheloop.

Syntax

do

{

System.out.println(“tick”+n);

n—;

}

Whilen>0);

}

}

Forstatement

Itisaverypowerfulaswellasveryversatileconstruct.

Theconditionwhatisprovidedinforstatementuntilandunlesstheconditionisnot

beensatisfieditwon’texecute.

Iftheconditionisevaluatedandthevalueisfalsethenitisterminated.

Syntax

For(initialize;condition;iterate)

{

Body

}

Forexample

Classfortick

{

background image

Publicstaticvoidmain(stringargs[])

{

Intn;

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

}

}

Jumpstatements

Javasupportsthreejumpstatementswhichareasfollows.

1. Break

2. Continue

3. Return

Break

Itisusedtoterminateastatementwhichisinsequenceinaswitchstatementanditcanbe

usedforexitingaloop.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(““);

}

background image

}

}

Return

ItisusedtoreturnfromamethodandItisatransferbackcallingofthemethod.

Forexample

Classreturn{

Publicstaticvoidmain(stringargs[])

{

Booleant=true;

System.out.println(“return”);

If(t)return;

System.out.println(“thiswon’twork”);

}

}

background image
background image

ClassesandMethods

Classesmightcontainonlycodeordatabutmayalsocontainboth.Aclassisdeclaredby

keywordclassanditcanbecomplexinnature.

Syntax

Classclassname

{

Typeinstance-variablea;

Typeinstance-variableb;

.

.

.

Typeinstance-variablen;

}

Typemethoda(parameter-list)

{

//bodyofmethod

}

Typemethodnamea(parameter-list)

//bodyofmethod

.

background image

.

}

}

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;

background image

}

Intpop()

{if(tos<0){

System.out.println(“stackunderflow”);

Return0;

}else

Returnstk[tos—];

}

}

background image

Overloadingmethod

Whentwoormoremethodsaredefinedinthesameplaceandthenamedefinedissame

buttheparametersaredifferent.Thismethodisanoverloadingmethod.Thisprovides

polymorphisminjava.

Example

Classoverload1

{

Voidtest(){

System.out.println(“noparameter”);

}

Voidtest(inta)

{

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

}

Voidtest(inta,intb)

{

background image

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);

}

}

background image

Output

A=10

AandB=1020

Doublea=123.25

Result=15190.5625

background image
background image

Inheritance

Inheritanceisasuperclassfromwhichalltheclassesareinheritedandwhichdoes

inheritingfromasuperclassiscalledthesubclass.

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();

background image

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

Whensubclassesareidenticalofasuperclassthisscenarioiscalledmethod

overriding.

Itprovidesthecharacteristiccalledpolymorphisminjava.

Inheritanceshowingoverriding

background image

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[])

{

background image

ysubob=newy(1,2,3);

Subob.Show();

}

}

Output

r=3

Typesofinheritance

Therearethreetypesofinheritance.

Singleinheritance

Multipleinheritance

Hierarchicalinheritance

Typesofinheritance

Injavamultipleandhybridwillonlysupportedwithuseofinterface.

Multipleandhybridinheritance

background image
background image
background image

Packages

Packagescontainnameswereclassesarestored.

Syntax

Packagepkg;

Torepresentmultipackaging

Packagepkgx[.pkgy[.pkgz]];

Forexample

Packagejava.awt.imagea;

Findingofpackages

Therearethreewaystofindthepackages.Thejavaruntimesystemusestheworking

directory;ifthepackageiscontainedinthesubdirectorythenitwillbediscoveredoryou

cansetthelocationbysettingthelocationofclassasshown.

Packagempack

Itcanuseclasspathwithjavaaswellasjavactospecifythe

locationofclassasshown.

C:\

myprograms\java\mpack

Accessprotection

Fortheprotectionofpackagestherearethreespecifiersinexistenceinjava.

1. Private-cannotbeseenoraccessedfromoutsidetheclass.

2. Public-ithasfeaturetobeaccessedfromanywhere.

3. Protected-thiscanbeaccessedonlybyclasseswhicharesub-classes.

Packagesyntax

Importingapackage

Thestatementthatimportsthepackagecomeimmediatelyafterthepackagingstatement

anditsmainfunctionistoimportthepackagebysavingmoretimetoitslocation.

Syntax

background image

Importpkga[.pkgb].(classnamed*);

background image

Interface

Itissimilartoclasswhichcontainsconstants,methodsandsignatures.

Javasimplecalculatorinterface

Interfaceforjava

Declaration

Accessinterfacem

{

Returnmethod1(parameterlist);

Returnmethod2(parameterlist);

Typefinalvariablename1=value;

Typefinalvariablename2=value;

//…

Returntypemethodnamen(parameterlist);

Typefinalvarnamen=value;

}

Simpleinterfacecontainsonlyonefunctionormethodknownascallbackfunction.

Forexample

background image

Interfacecallback

{

Voidcallback(intparm);

}

Implementinginterface

Tocreatinganyinterfaceimplementationofclassisincludedindefinitionofaclass.

Forexample

Classclientcallback

{

Publicvoidcallback(intx)

{

System.out.println(“callback”+x);

}

}

background image
background image

ExceptionalHandling

Itisadrawbackthataffectstheperformanceofjavaprogrambecauseitcanoccuratany

point.Itoccurrenceisatexecutionstate.

Reasons

Invaliddata

Fileabsent

LossofnetworkconnectionandtimeoutwhentheJVMisatrun.

Thecommonexceptionsare.

Checked-Theseexceptionscannotbeforecastedbytheprogrammeranditcannotbeeven

ignoredduring.

Runtime-Thisisadynamicexception,butitcanbeignoredunlikethecheckedone.

Errors-Thesearealsoignoredbecausenothingcanbedonetoovercomeitandthisisnot

underprogrammer’scontrol.

Exceptionhierarchy

Ithastwosubdivisions:Inputoutputexceptionclassesandruntimeexceptionclass.

Throw

TheseareexceptionswhicharethrownbyJVMduringruntime.

Syntax

throwThrowableinstance;

background image

Throw

Whenthisstatementisusedthereisanimmediatestopintheexecutionofprogram.

Forexample

Classthrowdem

{

Staticvoiddemopro()

{

Try{

ThrownewNullPointerException(“dem“);

}catch(NullPointerExceptione)

{

System.out.println(“caughtinsidedemopro.“);

Throwe;

}

}

Publicstaticvoidmain(stringargs[]{

background image

Try{

Demopro();

}

Catch(NullPointerExceptione){

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

}

}

}

Finally

Itisacodethatisusedinexecutingbeforeorafterthetryandcatchblockisexecutedor

completed.

Syntax

Classfinallydem

{

Staticvoidprox()

{

Try

{

System.out.println(“inprocx”);

ThrownewruntimeException(“demo”);

}

Finally

{

System.out.println(“proxfinally”);

}

}

background image
background image
background image

Eventhandling

Event

Itshowsthechangeinstateofasource.

Eventsources

Itisanobjectgeneratinganevent.

Syntax

PublicvoidaddTypeListener(TypeListnerl)

Forexample

Addkeylistner()-toregisterakeyboardevent.

Addmousemotionlistner()-toregisteramousemotionlistener.

ActionEventClass

Thishappenswhenbuttonispressed.Doubleclickingoftheitemoranyiteminthemenu

isselected.

Eventoccurrenceinjava

Keyeventclass

Thisgeneratedfromthekeyinputofthekeyboardandtherearethreetypesofkeyevents.

1. KEY_PRESSED

background image

2. KEY_RELEASED

3. KEY_TYPED.

Mouseeventclass

Thereareeighttypesofmouseeventclasses.

1. MOUSE_DRAGGED

2. MOUSE_CLICKED

3. MOUSE_ENTERED

4. MOUSE_EXITED

5. MOUSE_MOVED

6. MOUSE_PRESSED

7. MOUSE_RELEASED

8. MOUSE_WHEELED

Actionlistenerinterface

Itisusedtodefinetheactionstheseareallperformedwhichareinvokedatthecallofan

event.Itisusedtoknowthereactionofthemethod.

background image
background image

TheAppletclass

Itcontainsseveralmethodswhichareusefulforjavaexecutionanddetailedcontrol.The

Appletinitializationandterminationareasfollow.

Forstarting

init()-Usedtoinitializemethoditisthefirstmethod.

start()-Afterinitializationmethodthismethodcomesanditsfunctionistorestartor

displayonscreen.

paint()-Inthistheoutputoftheappletisredrawneachtimeitiscalled.

Forstopping

stop()-Itistoleavethebrowserwhichisopenedandcontainsapplet.

destroy()-Itisfortheappletoncewhichhastoremovedfromthememory.

Appletgeneration

HTMLapplettag

<APPLET

[CODEBASE=codebaseurl]

CODE=appletfile

[ALT=alternatetext]

[NAME=appletinstancename]

background image

WIDTH=pixelsHEIGHT=pixels

[ALIGN=alignment]

[VSPACE=pixels][HSPACE=pixels]

>

[PARANAME=attributenameVALUE=attributevalue>]

[HTMLdisplayedinabsenceofjava]

</APPLET>

HTMLApplettag

TheAudioclipinterface

play()-Tobegintheaudio.

stop()-Tostoptheaudio.

loop()-Toplaytheloopwithoutbreak.

TheAppletsubinterface

ItprovidesalinkthroughwhichanAppletandthebrowsercancommunicate.

background image
background image

Knowledgeflow:moreeBooksandApps

GetmorePlayBooks

GetmoreKindleeBooks

GetmoreappsfromGooglePlaystore

GetmoreappsfromAmazonappstore


Wyszukiwarka

Podobne podstrony:
Java for Beginners by Knowledge flow
Arabic Calligraphy Naskh Script for Beginners by Mustafa Ja far (2011)
Boehme for Beginners by Cynthia Bourgeault
WiFi Hacking for Beginners Learn Hacking by Hacking WiFi networks (2017)
ebook Wine For Beginners Quench Your Thirst For More Wine Knowledge
NLP for Beginners An Idiot Proof Guide to Neuro Linguistic Programming
Artificial Neural Networks for Beginners
a practical guide on pharmacovigilance for beginners
06 Bulgarian Greek for beginners
Article for Consideration by Circuit?llar
Cambridge University Press A Guide to MATLAB for Beginners and Experienced Users J5MINFIO6YPPDR6C36
eReport Wine Making For Beginners
Practical Course Spanish Grammar for Beginners (Russian)
Latin for Beginners
Blues For Beginner
Evolution for Beginners[1]
Instructions For Living by Rabbi Noach Weinberg
hypnosis for beginners (1) fvuu Nieznany

więcej podobnych podstron