“learning starts with viewing the world...

65

Upload: others

Post on 29-Oct-2019

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 2: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

“LEARNINGSTARTSWITHVIEWINGTHEWORLDDIFFERENTLY.”

Knowledgeflow-Amobilelearningplatformprovidesapps,eBooksandvideotutorials

KnowledgeflowbringsyoulearningeBookofJavaforBeginners.ThiseBookisforallinformationtechnologyandcomputersciencestudentsandprofessionalsacrosstheworld.

Followuson

Facebook

Googleplus

Twitter

Formoreinformationvisitusat

Knowledgeflow.in

knowledgeflowapps.blogspot.in

ThankyouforusingKnowledgefloweBooks

Page 3: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 4: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 5: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 6: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 7: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 8: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 9: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

Concurrencyutilities

InJ2SE5,andthedeveloperskitwascalledJDK5.1.5usedasinternalversionnumberandthisisreferredasdeveloperversionnumber.

Javabecamethecenterofinnovationincomputertechnologicalworld.TheexistenceofJVMandbytecodechangedthescenarioofsecurityandportabilityintheprogrammingworld.ThewaythenewideasareputintothelanguagehasbeenredefinedbytheJCPi.e.javacommunityprocess.

Page 10: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 11: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

FeaturesofJavaObject-orientedprogramming

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

ThethreeOOPprinciples

Encapsulation-Itsagendaistomanipulatethedataandkeepthedataisolatedandsafefromtheexternalinterferenceandmisuse.Theencapsulationisdonebytheuseoftheprotectivewrapper.Thispreventstheexternalsourcesfromaccessingthedataorthecode.

EncapsulationinJava

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

Page 12: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

Inheritance

Polymorphism-Itismeansmanywaystocarryoutthemethodbutfromoneinput.

Polymorphism

Bytecode

ThisishighlyoptimizedbysetofinstructionsdesignedwhichisdesignedtobeexecutedbyJavavirtualmachinethatisJVM.

JVM

Itwasdesignedasaninterpreterforthebytecode.Anotherfeatureofjavaprogramisthatitissimple.Thisenablestheprofessionalstolearn.Workinaveryeffectivemannerbutitisalsoveryeasytounderstand.

Robust

TheabilitythatincludescreatingarobustprogramthatcanbeamultiplatformprogramaregivenaveryhighpriorityindesignofJava.

Page 13: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 14: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

thisisasimplejavaprogram.

Callingofthefileinjavacmd

Callingofthefile:“Example.java”.

Page 15: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 16: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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.

Page 17: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

}

Page 18: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

}

Booleans

Itisaprimitivetypeforlogicalvalues.Thistendshaveonlyoneoftwopossiblevalues,trueorfalse.Itisgovernedbyiforforcontrolstatements.

Page 19: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

VariablesItisbasicunitofstorageandvariableshavescope,visibilityandlifetime.

Declarationofvariables

Intx,y,z;

Or

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

Typeconversionandcasting

Ifthereisanycompatibilityexistingbetweentwotypesthenjavawouldautomaticallyperformstheconversion.

Javaautomaticconversion

Itwillbeperformedwhentwoconditionsaremet.Whenthetwotypesarecompatible;Destinationtypeislargerthanthesourcetype.Afterthetwoconditionsarebeensatisfiedawideningconversiontakesplace.

Castingcompatibletypes

Itisasimpleandexplicittypeofconversion.Whenafloatingtypeofconversionisattachedtoanintegertypethistypeofconversioniscalledtruncation.Itisakindofconversionsometimecallednarrowingconversion.

Page 20: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 21: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 22: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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“|“.

Page 23: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 24: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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.

Page 25: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 26: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 27: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 28: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 29: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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;

Page 30: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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.

Page 31: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 32: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

{

Page 33: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

}

Page 34: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

}

}

Return

ItisusedtoreturnfromamethodandItisatransferbackcallingofthemethod.

Forexample

Classreturn{

Publicstaticvoidmain(stringargs[])

{

Booleant=true;

System.out.println(“return”);

If(t)return;

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

}

}

Page 35: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 36: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

ClassesandMethodsClassesmightcontainonlycodeordatabutmayalsocontainboth.Aclassisdeclaredbykeywordclassanditcanbecomplexinnature.

Syntax

Classclassname

{

Typeinstance-variablea;

Typeinstance-variableb;

.

.

.

Typeinstance-variablen;

}

Typemethoda(parameter-list)

{

//bodyofmethod

}

Typemethodnamea(parameter-list)

//bodyofmethod

.

Page 37: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

.

}

}

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;

Page 38: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

}

Intpop()

{if(tos<0){

System.out.println(“stackunderflow”);

Return0;

}else

Returnstk[tos—];

}

}

Page 39: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

OverloadingmethodWhentwoormoremethodsaredefinedinthesameplaceandthenamedefinedissamebuttheparametersaredifferent.Thismethodisanoverloadingmethod.Thisprovidespolymorphisminjava.

Example

Classoverload1

{

Voidtest(){

System.out.println(“noparameter”);

}

Voidtest(inta)

{

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

}

Voidtest(inta,intb)

{

Page 40: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

}

}

Page 41: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

Output

A=10

AandB=1020

Doublea=123.25

Result=15190.5625

Page 42: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 43: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 44: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 45: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

{

Page 46: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

ysubob=newy(1,2,3);

Subob.Show();

}

}

Output

r=3

Typesofinheritance

Therearethreetypesofinheritance.

SingleinheritanceMultipleinheritanceHierarchicalinheritance

Typesofinheritance

Injavamultipleandhybridwillonlysupportedwithuseofinterface.

Multipleandhybridinheritance

Page 47: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 48: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 49: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

Page 50: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

Importpkga[.pkgb].(classnamed*);

Page 51: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

InterfaceItissimilartoclasswhichcontainsconstants,methodsandsignatures.

Javasimplecalculatorinterface

Interfaceforjava

Declaration

Accessinterfacem

{

Returnmethod1(parameterlist);

Returnmethod2(parameterlist);

Typefinalvariablename1=value;

Typefinalvariablename2=value;

//…

Returntypemethodnamen(parameterlist);

Typefinalvarnamen=value;

}

Simpleinterfacecontainsonlyonefunctionormethodknownascallbackfunction.

Forexample

Page 52: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

Interfacecallback

{

Voidcallback(intparm);

}

Implementinginterface

Tocreatinganyinterfaceimplementationofclassisincludedindefinitionofaclass.

Forexample

Classclientcallback

{

Publicvoidcallback(intx)

{

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

}

}

Page 53: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 54: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

ExceptionalHandlingItisadrawbackthataffectstheperformanceofjavaprogrambecauseitcanoccuratanypoint.Itoccurrenceisatexecutionstate.

Reasons

InvaliddataFileabsentLossofnetworkconnectionandtimeoutwhentheJVMisatrun.

Thecommonexceptionsare.

Checked-Theseexceptionscannotbeforecastedbytheprogrammeranditcannotbeevenignoredduring.

Runtime-Thisisadynamicexception,butitcanbeignoredunlikethecheckedone.

Errors-Thesearealsoignoredbecausenothingcanbedonetoovercomeitandthisisnotunderprogrammer’scontrol.

Exceptionhierarchy

Ithastwosubdivisions:Inputoutputexceptionclassesandruntimeexceptionclass.

Throw

TheseareexceptionswhicharethrownbyJVMduringruntime.

Syntax

throwThrowableinstance;

Page 55: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

Throw

Whenthisstatementisusedthereisanimmediatestopintheexecutionofprogram.

Forexample

Classthrowdem

{

Staticvoiddemopro()

{

Try{

ThrownewNullPointerException(“dem“);

}catch(NullPointerExceptione)

{

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

Throwe;

}

}

Publicstaticvoidmain(stringargs[]{

Page 56: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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

}

}

Page 57: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 58: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 59: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

EventhandlingEvent

Itshowsthechangeinstateofasource.

Eventsources

Itisanobjectgeneratinganevent.

Syntax

PublicvoidaddTypeListener(TypeListnerl)

Forexample

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

ActionEventClass

Thishappenswhenbuttonispressed.Doubleclickingoftheitemoranyiteminthemenuisselected.

Eventoccurrenceinjava

Keyeventclass

Thisgeneratedfromthekeyinputofthekeyboardandtherearethreetypesofkeyevents.

1. KEY_PRESSED

Page 60: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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.

Page 61: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-
Page 62: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

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]

Page 63: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-

WIDTH=pixelsHEIGHT=pixels

[ALIGN=alignment]

[VSPACE=pixels][HSPACE=pixels]

>

[PARANAME=attributenameVALUE=attributevalue>]

[HTMLdisplayedinabsenceofjava]

</APPLET>

HTMLApplettag

TheAudioclipinterface

play()-Tobegintheaudio.

stop()-Tostoptheaudio.

loop()-Toplaytheloopwithoutbreak.

TheAppletsubinterface

ItprovidesalinkthroughwhichanAppletandthebrowsercancommunicate.

Page 64: “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.”162.251.163.190/ebook/pdf/Java_for_Beginners.pdf · “LEARNING STARTS WITH VIEWING THE WORLD DIFFERENTLY.” Knowledge flow-