Core Java

Add to Favourites
Post to:

WelcometoCore Java CourseComputing platformIncomputing,aplatformdescribessomesortofhardwarearchitectureorsoftwareframeworkthatallowssoftwaretorun.Forexample,theplatformmightbeanIntel80486processorrunningDOSVersion6.0.TheplatformcouldalsobeUNIXmachinesonanEthernetnetwork.Theplatformdefinesastandardaroundwhichasystemcanbedeveloped.Oncetheplatformhasbeendefined,softwaredeveloperscanproduceappropriatesoftwareandmanagerscanpurchaseappropriatehardwareandapplications.Thetermisoftenusedasasynonymofoperatingsystem.Cross-platform(alsoknownasmulti-platform)refertotheideathatagivenpieceofcomputersoftwareisabletoberunonmorethanonecomputerplatform.Therearetwomajortypesofcross-platformsoftwareOnerequiresbuildingforeachplatformthatitsupports(e.g.,iswritteninacompiledlanguage,suchasC)Anothercanbedirectlyrunonanyplatformwhichsupportsit(e.g.,softwarewritteninaninterpretedlanguagesuchasPerl,Python,orshellscript)orsoftwarewritteninalanguagewhichcompilestobytecodeandthebytecodeisredistributed(suchasisthecasewithJavaandlanguagesusedinthe.NETFramework).TheJavaProgrammingLanguageoIntheJavaprogramminglanguage,allsourcecodeisfirstwritteninplaintextfilesendingwiththe.javaextension.oThosesourcefilesarethencompiledinto.classfilesbythejavaccompiler.oA.classfiledoesnotcontaincodethatisnativetoyourprocessor.oItinsteadcontainsbytecodes—themachinelanguageoftheJavaVirtualMachine(JavaVM).oThejavalaunchertoolthenrunsyourapplicationwithaninstanceoftheJavaVirtualMachine.TheJavaPlatformoAplatformisthehardwareorsoftwareenvironmentinwhichaprogramruns.We'vealreadyknowsomeofthemostpopularplatformslikeMicrosoftWindows,Linux,SolarisOS,andMacOS.oMostplatformscanbedescribedasacombinationoftheoperatingsystemandunderlyinghardware.TheJavaplatformdiffersfrommostotherplatformsinthatit'sasoftware-onlyplatformthatrunsontopofotherhardware-basedplatforms.TheJavaplatformhastwocomponents:TheJavaVirtualMachineTheJavaApplicationProgrammingInterface(API)JavaVirtualMachineoBecausetheJavaVMisavailableonmanydifferentoperatingsystems,thesame.classfilesarecapableofrunningonMicrosoftWindows,theSolarisTMOperatingSystem(SolarisOS),Linux,orMacOS.Through the Java VM, the same application is capable of running on multiple platforms.JavaApplicationProgrammingInterface(API)oTheAPIisalargecollectionofready-madesoftwarecomponentsthatprovidemanyusefulcapabilities.Itisgroupedintolibrariesofrelatedclassesandinterfaces;theselibrariesareknownaspackages.The API and Java Virtual Machine insulate the program from the underlying hardware.Create a Source FileFirst,startyoureditor.YoucanlaunchtheNotepadeditorfromtheStartmenubyselectingPrograms>Accessories>Notepad.Inanewdocument,typeinthefollowingcode:/** * The HelloWorldAppclass implements an application that * simply prints "Hello World!" to standard output. */class HelloWorldApp { public static void main(String[] args){System.out.println("Hello World!"); //Display the string. }} Be Careful When You TypeTypeallcode,commands,andfilenamesexactlyasshown.Boththecompiler(javac)andlaunchertool(java)arecase-sensitive,soyoumustcapitalizeconsistently.HelloWorldApp helloworldappSavetheJavaSourceCodeSavethecodeinafilewiththenameHelloWorldApp.java.TodothisinNotepad,firstchoosetheFile>SaveAsmenuitem.Then,intheSaveAsdialogbox:1.UsingtheSaveincombobox,specifythefolder(directory)whereyou'llsaveyourfile.Inthisexample,thedirectoryisjavaontheCdrive.2.IntheFilenametextfield,type"HelloWorldApp.java",includingthequotationmarks.3.FromtheSaveastypecombobox,chooseTextDocuments(*.txt).4.IntheEncodingcombobox,leavetheencodingasANSI.Now click Save, and exit Notepad.Compile the Source File into a .class FileBringupashell,or"command,"window.YoucandothisfromtheStartmenubychoosingCommandPrompt(WindowsXP),orbychoosingRun...andthenenteringcmd.Theshellwindowshouldlooksimilartothefollowingfigure.Thepromptshowsyourcurrentdirectory.Whenyoubringuptheprompt,yourcurrentdirectoryisusuallyyourhomedirectoryforWindowsXPTocompileyoursourcefile,changeyourcurrentdirectorytothedirectorywhereyourfileislocated.Forexample,ifyoursourcedirectoryisjavaontheCdrive,typethefollowingcommandatthepromptandpressEnter:cdD:\javaNowthepromptshouldchangetoD:\java>.Nowyouarereadytocompile.Attheprompt,typethefollowingcommandandpressEnter.javac HelloWorldApp.javaThecompilerhasgeneratedabytecodefile,HelloWorldApp.class.Attheprompt,typedirtoseethenewfilethatwasgenerated,asshowninthefollowingfigure.Run the ProgramIn the same directory, enter the following command at the prompt: java HelloWorldAppThe program prints "Hello World!" to the screen.Congratulations! Your program works! A Closer Look at the "Hello World!" Application SourceCodeCommentsCommentsareignoredbythecompilerbutareusefultootherprogrammers.TheJavaprogramminglanguagesupportsthreekindsofcomments:/*text*/Thecompilerignoreseverythingfrom/*to*/./**documentation*/Thisindicatesadocumentationcomment(doccomment,forshort).Thecompilerignoresthiskindofcomment,justlikeitignorescommentsthatuse/*and*/.//textThecompilerignoreseverythingfrom//totheendoftheline.A Closer Look at the "Hello World!" Application TheHelloWorldAppClassDefinitionAsshownabove,themostbasicformofaclassdefinitionis:classname{...…..}Thekeywordclassbeginstheclassdefinitionforaclassnamedname,andthecodeforeachclassappearsbetweentheopeningandclosingcurlybracesmarkedabove.A Closer Look at the "Hello World!" Application ThemainMethodIntheJavaprogramminglanguage,everyapplicationmustcontainamainmethodwhosesignatureis:public static void main(String[] args) oThemodifierspublicandstaticcanbewrittenineitherorder(publicstaticorstaticpublic),buttheconventionistousepublicstaticasshownabove.oYoucannametheargumentanythingyouwant,butmostprogrammerschoose"args"or"argv".oThemainmethodissimilartothemainfunctioninCandC++;it'stheentrypointforyourapplicationandwillsubsequentlyinvokealltheothermethodsrequiredbyyourprogram.A Closer Look at the "Hello World!" Application ThemainMethodIntheJavaprogramminglanguage,everyapplicationmustcontainamainmethodwhosesignatureis:public static void main(String[] args) oThemodifierspublicandstaticcanbewrittenineitherorder(publicstaticorstaticpublic),buttheconventionistousepublicstaticasshownabove.oYoucannametheargumentanythingyouwant,butmostprogrammerschoose"args"or"argv".oThemainmethodissimilartothemainfunctioninCandC++;it'stheentrypointforyourapplicationandwillsubsequentlyinvokealltheothermethodsrequiredbyyourprogram.A Closer Look at the "Hello World!" Application ThemainMethodThe main method accepts a single argument: an array of elements of type String.public static void main(String[] args) oThisarrayisthemechanismthroughwhichtheruntimesystempassesinformationtoyourapplication.oEachstringinthearrayiscalledacommand-lineargument.oCommand-lineargumentsletusersaffecttheoperationoftheapplicationwithoutrecompilingit.oForexample,asortingprogrammightallowtheusertospecifythatthedatabesortedindescendingorderwiththiscommand-lineargument:-descendingoThe"HelloWorld!"applicationignoresitscommand-linearguments,butyoushouldbeawareofthefactthatsuchargumentsdoexist.A Closer Look at the "Hello World!" Application ThemainMethodFinally,theline:System.out.println("Hello World!"); usestheSystemclassfromthecorelibrarytoprintthe"HelloWorld!"messagetostandardoutput.Portionsofthislibrary(alsoknownasthe"ApplicationProgrammingInterface",or"API").Compiler ProblemsCommon Error Messages on Microsoft Windows Systems'javac'isnotrecognizedasaninternalorexternalcommand,operableprogramorbatchfileoIfyoureceivethiserror,Windowscannotfindthecompiler(javac).oHere'sonewaytotellWindowswheretofindjavac.SupposeyouinstalledtheJDKinC:\jdk6.AtthepromptyouwouldtypethefollowingcommandandpressEnter:C:\jdk6\bin\javacHelloWorldApp.javaIfyouchoosethisoption,you'llhavetoprecedeyourjavacandjavacommandswithC:\jdk6\bin\eachtimeyoucompileorrunaprogram.Toavoidthisextratyping,consultthesectionUpdatethePATHvariableintheJDK6installationinstructions.UpdatethePATHvariableIt'susefultosetthePATHpermanentlysoitwillpersistafterrebooting.TosetthePATHpermanently,addthefullpathofthejdk1.6.0_\bindirectorytothePATHvariable.TypicallythisfullpathlookssomethinglikeC:\ProgramFiles\Java\jdk1.6.0_\bin.SetthePATHasfollowsonMicrosoftWindows:1.ClickStart>ControlPanel>SystemonWindowsXPorStart>Settings>ControlPanel>SystemonWindows2000.2.ClickAdvanced>EnvironmentVariables.3.AddthelocationofbinfolderofJDKinstallationforPATHinUserVariablesandSystemVariables.AtypicalvalueforPATHis:C:\Program Files\Java\jdk1.6.0_\binErrorMessagesonMicrosoftWindowsSystemsExceptioninthread"main"java.lang.NoClassDefFoundError:HelloWorldAppIfyoureceivethiserror,javacannotfindyourbytecodefile,HelloWorldApp.class.Oneoftheplacesjavatriestofindyour.classfileisyourcurrentdirectory.Soifyour.classfileisinC:\java,youshouldchangeyourcurrentdirectorytothat.Tochangeyourdirectory,typethefollowingcommandatthepromptandpressEnter:cdc:\javaThepromptshouldchangetoC:\java>.Ifyouenterdirattheprompt,youshouldseeyour.javaand.classfiles.NowenterjavaHelloWorldAppagain.ErrorMessagesonMicrosoftWindowsSystemsIfyoustillhaveproblems,youmighthavetochangeyourCLASSPATHvariable.Toseeifthisisnecessary,tryclobberingtheclasspathwiththefollowingcommand.setCLASSPATH=NowenterjavaHelloWorldAppagain.Iftheprogramworksnow,you'llhavetochangeyourCLASSPATHvariable.Language Basics oVariablesoOperatorsoExpressions, Statements, and BlocksoControl Flow StatementsVariablesTheJavaprogramminglanguagedefinesthefollowingkindsofvariables:oInstanceVariables(Non-StaticFields)Technicallyspeaking,objectsstoretheirindividualstatesin"non-staticfields",thatis,fieldsdeclaredwithoutthestatickeyword.Non-staticfieldsarealsoknownasinstancevariablesbecausetheirvaluesareuniquetoeachinstanceofaclass.ThecurrentSpeedofonebicycleisindependentfromthecurrentSpeedofanother.VariablesTheJavaprogramminglanguagedefinesthefollowingkindsofvariables:oClassVariables(StaticFields)AclassvariableisanyfielddeclaredwiththestaticmodifierThistellsthecompilerthatthereisexactlyonecopyofthisvariableinexistence,regardlessofhowmanytimestheclasshasbeeninstantiated.ThecodestaticintnumGears=6;wouldcreatesuchastaticfield.Additionally,thekeywordfinalcouldbeaddedtoindicatethatthenumberofgearswillneverchange.VariablesTheJavaprogramminglanguagedefinesthefollowingkindsofvariables:oLocalVariablesSimilartohowanobjectstoresitsstateinfields,amethodwilloftenstoreitstemporarystateinlocalvariables.forexample,intcount=0;Assuch,localvariablesareonlyvisibletothemethodsinwhichtheyaredeclared;theyarenotaccessiblefromtherestoftheclass.oParametersYou'vealreadyseenexamplesofparameters.Recallthatthesignatureforthemainmethodispublic static void main(String[] args).Here,theargsvariableistheparametertothismethod.NamingTherulesandconventionsfornamingyourvariablescanbesummarizedasfollows:oVariablenamesarecase-sensitiveoBeginningwithaletter,thedollarsign"$",ortheunderscorecharacter"_".oWhitespaceisnotpermitted.oSubsequentcharactersmaybeletters,digits,dollarsigns,orunderscorecharacters.PrimitiveDataTypesPrimitivetypesarespecialdatatypesbuiltintothelanguage;theyarenotobjectscreatedfromaclass.TheJavaprogramminglanguageisstrongly-typed,whichmeansthatallvariablesmustfirstbedeclaredbeforetheycanbeused.intgear=1;TheeightprimitivedatatypessupportedbytheJavaprogramminglanguageare:byte:Thebytedatatypeisan8-bitsignedtwo'scomplementinteger.Ithasaminimumvalueof-128andamaximumvalueof127(inclusive).short:Theshortdatatypeisa16-bitsignedtwo'scomplementinteger.Ithasaminimumvalueof-32,768andamaximumvalueof32,767(inclusive).PrimitiveDataTypesTheJavaprogramminglanguageisstrongly-typed,whichmeansthatallvariablesmustfirstbedeclaredbeforetheycanbeused.intgear=1;TheeightprimitivedatatypessupportedbytheJavaprogramminglanguageare:int:Theintdatatypeisa32-bitsignedtwo'scomplementinteger.Ithasaminimumvalueof-2,147,483,648andamaximumvalueof2,147,483,647(inclusive).long:Thelongdatatypeisa64-bitsignedtwo'scomplementinteger.Ithasaminimumvalueof-9,223,372,036,854,775,808andamaximumvalueof9,223,372,036,854,775,807(inclusive).Usethisdatatypewhenyouneedarangeofvalueswiderthanthoseprovidedbyint.PrimitiveDataTypesTheJavaprogramminglanguageisstrongly-typed,whichmeansthatallvariablesmustfirstbedeclaredbeforetheycanbeused.intgear=1;TheeightprimitivedatatypessupportedbytheJavaprogramminglanguageare:float:Thefloatdatatypeisasingle-precision32-bitIEEE754floatingpoint.double:Thedoubledatatypeisadouble-precision64-bitIEEE754floatingpoint.PrimitiveDataTypesTheJavaprogramminglanguageisstrongly-typed,whichmeansthatallvariablesmustfirstbedeclaredbeforetheycanbeused.intgear=1;TheeightprimitivedatatypessupportedbytheJavaprogramminglanguageare:boolean:Thebooleandatatypehasonlytwopossiblevalues:trueandfalse.char:Thechardatatypeisasingle16-bitUnicodecharacter.Ithasaminimumvalueof'\u0000'(or0)andamaximumvalueof'\uffff'(or65,535inclusive).DefaultValuesoIt'snotalwaysnecessarytoassignavaluewhenafieldisdeclared.oFieldsthataredeclaredbutnotinitializedwillbesettoareasonabledefaultbythecompiler.oGenerallyspeaking,thisdefaultwillbezeroornull,dependingonthedatatype.oRelyingonsuchdefaultvalues,however,isgenerallyconsideredbadprogrammingstyle.Data TypeDefault Value (for fields)Byte0Short0Int0Long0LFloat0.0fDouble0.0dChar'\u0000'String (or any object) NullBooleanFalseArraysAnarrayisacontainerobjectthatholdsafixednumberofvaluesofasingletype.Thelengthofanarrayisestablishedwhenthearrayiscreated.An array of ten elementsEachiteminanarrayiscalledanelement,andeachelementisaccessedbyitsnumericalindex./*ARRAY PROGRAMMING. */classArrayDemo{publicstaticvoidmain(String[]args){int[]anArray;//declaresanarrayofintegersanArray=newint[10];//allocatesmemoryfor10integersanArray[0]=100;//initializefirstelementanArray[1]=200;//initializesecondelementanArray[2]=300;//etc.anArray[3]=400;anArray[4]=500;anArray[5]=600;anArray[6]=700;anArray[7]=800;anArray[8]=900;anArray[9]=1000;System.out.println("Elementatindex0:"+anArray[0]);System.out.println("Elementatindex1:"+anArray[1]);System.out.println("Elementatindex2:"+anArray[2]);System.out.println("Elementatindex3:"+anArray[3]);System.out.println("Elementatindex4:"+anArray[4]);System.out.println("Elementatindex5:"+anArray[5]);System.out.println("Elementatindex6:"+anArray[6]);System.out.println("Elementatindex7:"+anArray[7]);System.out.println("Elementatindex8:"+anArray[8]);System.out.println("Elementatindex9:"+anArray[9]);}}Theoutputfromthisprogramis:Elementatindex0:100Elementatindex1:200Elementatindex2:300Elementatindex3:400Elementatindex4:500Elementatindex5:600Elementatindex6:700Elementatindex7:800Elementatindex8:900Elementatindex9:1000DeclaringaVariabletoRefertoanArrayTheaboveprogramdeclaresanArraywiththefollowinglineofcode:int[] anArray; //declares an array of integersAnarray'stypeiswrittenastype[],wheretypeisthedatatypeofthecontainedelements;thesquarebracketsarespecialsymbolsindicatingthatthisvariableholdsanarray.Thesizeofthearrayisnotpartofitstype.Similarly,youcandeclarearraysofothertypes:byte[]anArrayOfBytes;short[]anArrayOfShorts;long[]anArrayOfLongs;float[]anArrayOfFloats;double[]anArrayOfDoubles;boolean[]anArrayOfBooleans;char[]anArrayOfChars;String[]anArrayOfStrings;Youcanalsoplacethesquarebracketsafterthearray'sname:floatanArrayOfFloats[];//thisformisdiscouragedCreating,Initializing,andAccessinganArrayOnewaytocreateanarrayiswiththenewoperator.anArray=newint[10];//createanarrayofintegersIfthisstatementweremissing,thecompilerwouldprintanerrorlikethefollowing,andcompilationwouldfail:ArrayDemo.java:4:VariableanArraymaynothavebeeninitialized.Thenextfewlinesassignvaluestoeachelementofthearray:anArray[0]=100;//initializefirstelementanArray[1]=200;//initializesecondelementanArray[2]=300;//etc.Eacharrayelementisaccessedbyitsnumericalindex:System.out.println("Element1atindex0:"+anArray[0]);System.out.println("Element2atindex1:"+anArray[1]);System.out.println("Element3atindex2:"+anArray[2]);Creating,Initializing,andAccessinganArrayAlternatively,youcanusetheshortcutsyntaxtocreateandinitializeanarray:int[]anArray={100,200,300,400,500,600,700,800,900,1000};Herethelengthofthearrayisdeterminedbythenumberofvaluesprovidedbetween{and}.Youcanalsodeclareanarrayofarrays(alsoknownasamultidimensionalarray)byusingtwoormoresetsofsquarebrackets,suchasString[][]names.Eachelement,therefore,mustbeaccessedbyacorrespondingnumberofindexvalues.classMultiDimArrayDemo{publicstaticvoidmain(String[]args){String[][]names={{"Mr.","Mrs.","Ms."},{"Smith","Jones"}};System.out.println(names[0][0]+names[1][0]);System.out.println(names[0][2]+names[1][1]);}}Creating,Initializing,andAccessinganArrayTheoutputfromthisprogramis:Mr.SmithMs.JonesFinally,youcanusethebuilt-inlengthpropertytodeterminethesizeofanyarray.ThecodeSystem.out.println(anArray.length);willprintthearray'ssizetostandardoutput.CopyingArraysTheSystemclasshasanarraycopymethodthatyoucanusetoefficientlycopydatafromonearrayintoanother:publicstaticvoidarraycopy(Objectsrc,intsrcPos,Objectdest,intdestPos,intlength)ThetwoObjectargumentsspecifythearraytocopyfromandthearraytocopyto.Thethreeintargumentsspecifythestartingpositioninthesourcearray,thestartingpositioninthedestinationarray,andthenumberofarrayelementstocopy.CopyingArrays/*ArrayCopy*/classArrayCopyDemo{publicstaticvoidmain(String[]args){char[]copyFrom={'d','e','c','a','f','f','e','i','n','a','t','e','d'};char[]copyTo=newchar[7];System.arraycopy(copyFrom,2,copyTo,0,7);System.out.println(newString(copyTo));}}Theoutputfromthisprogramis:CopyingArrays/*ArrayCopy*/classArrayCopyDemo{publicstaticvoidmain(String[]args){char[]copyFrom={'d','e','c','a','f','f','e','i','n','a','t','e','d'};char[]copyTo=newchar[7];System.arraycopy(copyFrom,2,copyTo,0,7);System.out.println(newString(copyTo));}}Theoutputfromthisprogramis:caffeinOperatorsoOperatorsarespecialsymbolsthatperformspecificoperationsonone,two,orthreeoperands,andthenreturnaresult.oOperatorswithhigherprecedenceareevaluatedbeforeoperatorswithrelativelylowerprecedence.oWhenoperatorsofequalprecedenceappearinthesameexpression,arulemustgovernwhichisevaluatedfirst.Rule:Allbinaryoperatorsexceptfortheassignmentoperatorsareevaluatedfromlefttoright;assignmentoperatorsareevaluatedrighttoleft.Operator Precedence OperatorsPrecedencepostfixexpr++ expr--unary++expr--expr+expr-expr~ !multiplicative* /%additive+ -shift<< >> >>>relational< > <= >= instanceofequality== !=bitwise AND&bitwise exclusive OR^bitwise inclusive OR|logical AND&&logical OR||ternary? :assignment= += -= *= /= %= &= ^= |= <<= >>= >>>=for example, the assignment operator "=" is far more common than the unsigned right shift operator ">>>". Assignment, Arithmetic, and Unary OperatorsTheSimpleAssignmentOperatorOneofthemostcommonoperatorsthatyou'llencounteristhesimpleassignmentoperator"=".intcadence=0;intspeed=0;intgear=1;TheArithmeticOperatorsTheJavaprogramminglanguageprovidesoperatorsthatperformaddition,subtraction,multiplication,anddivision.+additiveoperator(alsousedforStringconcatenation)-subtractionoperator-*multiplicationoperator-/divisionoperator-%remainderoperatorclassArithmeticDemo{publicstaticvoidmain(String[]args){intresult=1+2;System.out.println(result);result=result-1;System.out.println(result);result=result*2;System.out.println(result);result=result/2;System.out.println(result);result=result+8;result=result%7;System.out.println(result);}}Youcanalsocombinethearithmeticoperatorswiththesimpleassignmentoperatortocreatecompoundassignments.Forexample,x+=1;andx=x+1;bothincrementthevalueofxby1.classArithmeticDemo{publicstaticvoidmain(String[]args){intresult=1+2;//resultisnow3System.out.println(result);result=result-1;//resultisnow2System.out.println(result);result=result*2;//resultisnow4System.out.println(result);result=result/2;//resultisnow2System.out.println(result);result=result+8;//resultisnow10result=result%7;//resultisnow3System.out.println(result);}}Youcanalsocombinethearithmeticoperatorswiththesimpleassignmentoperatortocreatecompoundassignments.Forexample,x+=1;andx=x+1;bothincrementthevalueofxby1.The + operator can also be used for concatenating (joining) two strings together class ConcatDemo { public static void main(String[] args){ String firstString = "This is"; String secondString = " a concatenated string."; String thirdString = firstString+secondString; System.out.println(thirdString); }} By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output. TheUnaryOperatorsTheunaryoperatorsrequireonlyoneoperand;theyperformvariousoperationssuchasincrementing/decrementingavaluebyone,negatinganexpression,orinvertingthevalueofaboolean.+Unaryplusoperator;indicatespositivevalue(numbersarepositivewithoutthis,however)-Unaryminusoperator;negatesanexpression++Incrementoperator;incrementsavalueby1--Decrementoperator;decrementsavalueby1!Logicalcomplementoperator;invertsthevalueofabooleanclass UnaryDemo { public static void main(String[] args){ int result = +1; System.out.println(result); result--; System.out.println(result); result++; System.out.println(result); result = -result; System.out.println(result); boolean success = false; System.out.println(success); System.out.println(!success); }} class UnaryDemo { public static void main(String[] args){ int result = +1; //result is now 1 System.out.println(result); result--; //result is now 0 System.out.println(result); result++; //result is now 1 System.out.println(result); result = -result; //result is now -1 System.out.println(result); boolean success = false; System.out.println(success); //false System.out.println(!success); //true }} Thefollowingprogram,illustratestheprefix/postfixunaryincrementoperatorclassPrePostDemo{publicstaticvoidmain(String[]args){inti=3;i++;System.out.println(i);++i;System.out.println(i);System.out.println(++i);System.out.println(i++);System.out.println(i);}}Thefollowingprogram,illustratestheprefix/postfixunaryincrementoperatorclassPrePostDemo{publicstaticvoidmain(String[]args){inti=3;i++;System.out.println(i);//"4"++i;System.out.println(i);//"5"System.out.println(++i);//"6"System.out.println(i++);//"6"System.out.println(i);//"7"}}Equality, Relational, and Conditional Operators TheEqualityandRelationalOperatorsTheequalityandrelationaloperatorsdetermineifoneoperandisgreaterthan,lessthan,equalto,ornotequaltoanotheroperand.==equalto!=notequalto>greaterthan>=greaterthanorequalto value2) System.out.println("value1 > value2"); if(value1 < value2) System.out.println("value1 < value2"); if(value1 <= value2) System.out.println("value1 <= value2"); } } Output: value1 != value2 value1 < value2 value1 <= value2 TheConditionalOperatorsThe&&and||operatorsperformConditional-ANDandConditional-ORoperationsontwobooleanexpressions.Theseoperatorsexhibit"short-circuiting"behavior,whichmeansthatthesecondoperandisevaluatedonlyifneeded.&&Conditional-AND||Conditional-ORThe following program, tests these operators: class ConditionalDemo1 { public static void main(String[] args){ int value1 = 1;int value2 = 2; if((value1 == 1) && (value2 == 2)) System.out.println("value1 is 1 AND value2 is 2"); if((value1 == 1) || (value2 == 1)) System.out.println("value1 is 1 OR value2 is 1"); }} Another conditional operator is ?:Which can be thought of as shorthand for an if-then-else statement. This operator is also known as the ternary operatorbecause it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result." The following program, tests the ?:operator: class ConditionalDemo2 { public static void main(String[] args){ int value1 = 1; int value2 = 2; int result; boolean someCondition = true; result = someCondition ? value1 : value2; System.out.println(result); }} Because someConditionis true, this program prints "1" to the screen. ExpressionsAnexpressionisacollectionofvariables,operators,andmethodinvocations,whichareconstructedaccordingtothesyntaxofthelanguage,thatevaluatestoasinglevalue.You'vealreadyseenexamplesofexpressions,illustratedinboldbelow:intcadence=0;anArray[0]=100;System.out.println("Element1atindex0:"+anArray[0]);intresult=1+2;//resultisnow3if(value1==value2)System.out.println("value1==value2");Thedatatypeofthevaluereturnedbyanexpressiondependsontheelementsusedintheexpression.Theexpressioncadence=0returnsanintbecausetheassignmentoperatorreturnsavalueofthesamedatatypeasitsleft-handoperand.Asyoucanseefromtheotherexpressions,anexpressioncanreturnothertypesofvaluesaswell,suchasbooleanorString.ExpressionsHere'sanexampleofacompoundexpression:1*2*3Inthisparticularexample,theorderinwhichtheexpressionisevaluatedisunimportantbecausetheresultofmultiplicationisindependentoforder.Theoutcomeisalwaysthesame,nomatterinwhichorderyouapplythemultiplications.However,thisisnottrueofallexpressions.Forexample,thefollowingexpressiongivesdifferentresults,dependingonwhetheryouperformtheadditionorthedivisionoperationfirst:x+y/100//ambiguousYoucanspecifyexactlyhowanexpressionwillbeevaluatedusingbalancedparenthesis:(and).ExpressionsForexample,tomakethepreviousexpressionunambiguous,youcouldwritethefollowing:(x+y)/100//unambiguous,recommendedNote:Ifyoudon'texplicitlyindicatetheorderfortheoperationstobeperformed,theorderisdeterminedbytheprecedenceassignedtotheoperatorsinusewithintheexpression.Operatorsthathaveahigherprecedencegetevaluatedfirst.Forexample,thedivisionoperatorhasahigherprecedencethandoestheadditionoperator.Therefore,thefollowingtwostatementsareequivalent:x+y/100x+(y/100)//unambiguous,recommendedWhenwritingcompoundexpressions,beexplicitandindicatewithparentheseswhichoperatorsshouldbeevaluatedfirst.Thispracticemakescodeeasiertoreadandtomaintain.StatementsStatementsareroughlyequivalenttosentencesinnaturallanguages.Astatementformsacompleteunitofexecution.Thefollowingtypesofexpressionscanbemadeintoastatementbyterminatingtheexpressionwithasemicolon(;).AssignmentexpressionsAnyuseof++or--MethodinvocationsObjectcreationexpressionsSuchstatementsarecalledexpressionstatements.Herearesomeexamplesofexpressionstatements.aValue=8933.234;//assignmentstatementaValue++;//incrementstatementSystem.out.println("HelloWorld!");//methodinvocationstatementBicyclemyBike=newBicycle();//objectcreationstatementStatementsInadditiontoexpressionstatements,therearetwootherkindsofstatements:declaration statementsand control flow statements.Adeclarationstatementdeclaresavariable.You'veseenmanyexamplesofdeclarationstatementsalready:doubleaValue=8933.234;//declarationstatementcontrolflowstatementsregulatetheorderinwhichstatementsgetexecuted.BlocksAblockisagroupofzeroormorestatementsbetweenbalancedbracesandcanbeusedanywhereasinglestatementisallowed.Thefollowingexample,illustratestheuseofblocks:classBlockDemo{publicstaticvoidmain(String[]args){booleancondition=true;if(condition){//beginblock1System.out.println("Conditionistrue.");}//endblockoneelse{//beginblock2System.out.println("Conditionisfalse.");}//endblock2}}ControlFlowStatementsThissectiondescribesthedecision-makingstatements(if-then,if-then-else,switch),theloopingstatements(for,while,do-while),andthebranchingstatements(break,continue,return)supportedbytheJavaprogramminglanguage.Theif-thenStatementTheif-thenstatementisthemostbasicofallthecontrolflowstatements.Ittellsyourprogramtoexecuteacertainsectionofcodeonlyifaparticulartestevaluatestotrue.Forexample,theBicycleclasscouldallowthebrakestodecreasethebicycle'sspeedonlyifthebicycleisalreadyinmotion.OnepossibleimplementationoftheapplyBrakesmethodcouldbeasfollows:voidapplyBrakes(){if(isMoving){//the"if"clause:bicyclemustmovingcurrentSpeed--;//the"then"clause:decreasecurrentspeed}}Ifthistestevaluatestofalse(meaningthatthebicycleisnotinmotion),controljumpstotheendoftheif-thenstatement.Theif-thenStatementInaddition,theopeningandclosingbracesareoptional,providedthatthe"then"clausecontainsonlyonestatement:voidapplyBrakes(){if(isMoving)currentSpeed--;//sameasabove,butwithoutbraces}Note:Decidingwhentoomitthebracesisamatterofpersonaltaste.Omittingthemcanmakethecodemorebrittle.Ifasecondstatementislateraddedtothe"then"clause,acommonmistakewouldbeforgettingtoaddthenewlyrequiredbraces.Thecompilercannotcatchthissortoferror;you'lljustgetthewrongresults.Theif-then-elseStatementTheif-then-elsestatementprovidesasecondarypathofexecutionwhenan"if"clauseevaluatestofalse.Youcoulduseanif-then-elsestatementintheapplyBrakesmethodtotakesomeactionifthebrakesareappliedwhenthebicycleisnotinmotion.Inthiscase,theactionistosimplyprintanerrormessagestatingthatthebicyclehasalreadystopped.voidapplyBrakes(){if(isMoving){currentSpeed--;}else{System.err.println("Thebicyclehasalreadystopped!");}}The Next program, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on. class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; }else if (testscore >= 70) { grade = 'C'; }else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } }The output from the program is: Grade = C Note:Youmayhavenoticedthatthevalueoftestscorecansatisfymorethanoneexpressioninthecompoundstatement:76>=70and76>=60.However,onceaconditionissatisfied,theappropriatestatementsareexecuted(grade='C';)andtheremainingconditionsarenotevaluated.TheswitchStatementUnlikeif-thenandif-then-else,theswitchstatementallowsforanynumberofpossibleexecutionpaths.Aswitchworkswiththebyte,short,char,andintprimitivedatatypes.Italsoworkswithenumeratedtypes(discussedinClassesandInheritance)TheNextprogram,SwitchDemo,declaresanintnamedmonthwhosevaluerepresentsamonthoutoftheyear.Theprogramdisplaysthenameofthemonth,basedonthevalueofmonth,usingtheswitchstatement.classSwitchDemo{publicstaticvoidmain(String[]args){intmonth=8;switch(month){case1:System.out.println("January");break;case2:System.out.println("February");break;case3:System.out.println("March");break;case4:System.out.println("April");break;case5:System.out.println("May");break;case6:System.out.println("June");break;case7:System.out.println("July");break;case8:System.out.println("August");break;case9:System.out.println("September");break;case10:System.out.println("October");break;case11:System.out.println("November");break;case12:System.out.println("December");break;default:System.out.println("Invalidmonth.");break;}}}Inthiscase,"August"isprintedtostandardoutput.Thewhileanddo-whileStatementsThewhilestatementcontinuallyexecutesablockofstatementswhileaparticularconditionistrue.Itssyntaxcanbeexpressedas:while(expression){statement(s)}Thewhilestatementevaluatesexpression,whichmustreturnabooleanvalue.Iftheexpressionevaluatestotrue,thewhilestatementexecutesthestatement(s)inthewhileblock.Thewhilestatementcontinuestestingtheexpressionandexecutingitsblockuntiltheexpressionevaluatestofalse.classWhileDemo{publicstaticvoidmain(String[]args){intcount=1;while(count<11){System.out.println("Countis:"+count);count++;}}}Youcanimplementaninfiniteloopusingthewhilestatementasfollows:while(true){//yourcodegoeshere}TheJavaprogramminglanguagealsoprovidesado-whilestatement,whichcanbeexpressedasfollows:do{statement(s)}while(expression);Thedifferencebetweendo-whileandwhileisthatdo-whileevaluatesitsexpressionatthebottomoftheloopinsteadofthetop.class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 11); } } TheforStatementTheforstatementprovidesacompactwaytoiterateoverarangeofvalues.Programmersoftenrefertoitasthe"forloop"becauseofthewayinwhichitrepeatedlyloopsuntilaparticularconditionissatisfied.Thegeneralformoftheforstatementcanbeexpressedasfollows:for(initialization;termination;increment){statement(s)}Whenusingthisversionoftheforstatement,keepinmindthat:Theinitializationexpressioninitializestheloop;it'sexecutedonce,astheloopbegins.Whentheterminationexpressionevaluatestofalse,theloopterminates.Theincrementexpressionisinvokedaftereachiterationthroughtheloop;itisperfectlyacceptableforthisexpressiontoincrementordecrementavalue.class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } } The output of this program is: Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10 Thethreeexpressionsoftheforloopareoptional;aninfiniteloopcanbecreatedasfollows:for(;;){//infiniteloop//yourcodegoeshere}Theforstatementalsohasanotherformdesignedforiterationthrougharrays.Thisformissometimesreferredtoastheenhancedforstatement,andcanbeusedtomakeyourloopsmorecompactandeasytoread.Todemonstrate,considerthefollowingarray,whichholdsthenumbers1through10:int[]numbers={1,2,3,4,5,6,7,8,9,10};classEnhancedForDemo{publicstaticvoidmain(String[]args){int[]numbers={1,2,3,4,5,6,7,8,9,10};for(intitem:numbers){System.out.println("Countis:"+item);}}}BranchingStatementsThebreakStatementThebreakstatementhastwoforms:labeledandunlabeled.Yousawtheunlabeledforminthepreviousdiscussionoftheswitchstatement.Youcanalsouseanunlabeledbreaktoterminateafor,while,ordo-whileloopclass BreakDemoUnlabel { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; int searchfor = 12; int i; boolean foundIt = false; for (i = 0; i < arrayOfInts.length; i++) { if (arrayOfInts[i] == searchfor) { foundIt = true; break;} } if (foundIt) { System.out.println("Found " + searchfor + " at index " + i);}else { System.out.println(searchfor + " not in the array"); } } } An unlabeled break statement terminates the innermost switch, for, while, or do-while statement.But a labeled break terminates an outer statement. The next program, BreakWithLabelDemo, is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search"): class BreakWithLabelDemo { public static void main(String[] args) { int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i; int j = 0; boolean foundIt = false; search: for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } }if (foundIt) { System.out.println("Found " + searchfor + " at " + i + ", " + j); } else { System.out.println(searchfor + " not in the array"); } }} ThecontinueStatementThecontinuestatementskipsthecurrentiterationofafor,while,ordo-whileloop.Theunlabeledformskipstotheendoftheinnermostloop'sbodyandevaluatesthebooleanexpressionthatcontrolstheloop.Thenextprogram,ContinueDemo,stepsthroughaString,countingtheoccurrencesoftheletter"p".Ifthecurrentcharacterisnotap,thecontinuestatementskipstherestoftheloopandproceedstothenextcharacter.Ifitisa"p",theprogramincrementsthelettercount.class ContinueDemo { public static void main(String[] args){String searchMe = "peter piper picked a peck of pickled peppers";int max = searchMe.length(); int numPs = 0;for (int i = 0; i < max; i++) { //interested only in p's if (searchMe.charAt(i) != 'p') continue; //process p's numPs++; } System.out.println("Found " + numPs + " p's in the string."); } } Here is the output of this program: Found 9 p's in the string. A labeled continue statement skips the current iteration of an outer loop marked with the given label. The next example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. class ContinueWithLabelDemo { public static void main(String[] args) { String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() -substring.length(); test: for (int i = 0; i <= max; i++) { int n = substring.length(); int j = i; int k = 0; while (n--!= 0) { if (searchMe.charAt(j++) != substring.charAt(k++)){ continue test; } } foundIt = true; break test; } System.out.println(foundIt ? "Found it" : "Didn't find it"); } } ThereturnStatementThelastofthebranchingstatementsisthereturnstatement.Thereturnstatementexitsfromthecurrentmethod,andcontrolflowreturnstowherethemethodwasinvoked.Thereturnstatementhastwoforms:onethatreturnsavalue,andonethatdoesn't.Toreturnavalue,simplyputthevalue(oranexpressionthatcalculatesthevalue)afterthereturnkeyword.return++count;Thedatatypeofthereturnedvaluemustmatchthetypeofthemethod'sdeclaredreturnvalue.Whenamethodisdeclaredvoid,usetheformofreturnthatdoesn'treturnavalue.return;WhatIsanObject?Objectsarekeytounderstandingobject-orientedtechnology.You'llfindmanyexamplesofreal-worldobjects:yourdog,yourdesk,yourtelevisionset,yourbicycle.Real-worldobjectssharetwocharacteristics:Theyallhavestateandbehavior.Dogshavestate(name,color,breed,hungry)andbehavior(barking,fetching).Bicyclesalsohavestate(currentgear,currentpedalcadence,currentspeed)andbehavior(changinggear,changingpedalcadence,applyingbrakes).Identifyingthestateandbehaviorforreal-worldobjectsisagreatwaytobeginthinkingintermsofobject-orientedprogramming.Takeaminuterightnowtoobservethereal-worldobjectsthatareinyourimmediatearea.Foreachobjectthatyousee,askyourselftwoquestions:"Whatpossiblestatescanthisobjectbein?"and"Whatpossiblebehaviorcanthisobjectperform?".Yourdesktoplampmayhaveonlytwopossiblestates(onandoff)andtwopossiblebehaviors(turnon,turnoff),Butyourdesktopradiomighthaveadditionalstates(on,off,currentvolume,currentstation)andbehavior(turnon,turnoff,increasevolume,decreasevolume,seek,scan,andtune).Youmayalsonoticethatsomeobjects,inturn,willalsocontainotherobjects.Thesereal-worldobservationsalltranslateintotheworldofobject-orientedprogramming.Softwareobjectsareconceptuallysimilartoreal-worldobjects:theytooconsistofstateandrelatedbehavior.Anobjectstoresitsstateinfields(variablesinsomeprogramminglanguages)Exposesitsbehaviorthroughmethods(functionsinsomeprogramminglanguages)WhatIsaClass?Intherealworld,you'lloftenfindmanyindividualobjectsallofthesamekind.Theremaybethousandsofotherbicyclesinexistence,allofthesamemakeandmodel.Eachbicyclewasbuiltfromthesamesetofblueprintsandthereforecontainsthesamecomponents.Inobject-orientedterms,wesaythatyourbicycleisaninstanceoftheclassofobjectsknownasbicycles.Aclassistheblueprintfromwhichindividualobjectsarecreated.ThefollowingBicycleclassisonepossibleimplementationofabicycle:classBicycle{intcadence=0;intspeed=0;intgear=1;voidchangeCadence(intnewValue){cadence=newValue;}voidchangeGear(intnewValue){gear=newValue;}voidspeedUp(intincrement){speed=speed+increment;}voidapplyBrakes(intdecrement){speed=speed-decrement;}voidprintStates(){System.out.println("cadence:"+cadence+"speed:"+speed+"gear:"+gear);}}oThefieldscadence,speed,andgearrepresenttheobject'sstate,andoThemethods(changeCadence,changeGear,speedUpetc.)defineitsinteractionwiththeoutsideworld.oYoumayhavenoticedthattheBicycleclassdoesnotcontainamainmethod.That'sbecauseit'snotacompleteapplication;oIt'sjusttheblueprintforbicyclesthatmightbeusedinanapplication.oTheresponsibilityofcreatingandusingnewBicycleobjectsbelongstosomeotherclassinyourapplication.Here'saBicycleDemoclassthatcreatestwoseparateBicycleobjectsandinvokestheirmethods:classBicycleDemo{publicstaticvoidmain(String[]args){//CreatetwodifferentBicycleobjectsBicyclebike1=newBicycle();Bicyclebike2=newBicycle();//Invokemethodsonthoseobjectsbike1.changeCadence(50);bike1.speedUp(10);bike1.changeGear(2);bike1.printStates();bike2.changeCadence(50);bike2.speedUp(10);bike2.changeGear(2);bike2.changeCadence(40);bike2.speedUp(10);bike2.changeGear(3);bike2.printStates();}}Theoutputofthistestprintstheendingpedalcadence,speed,andgearforthetwobicycles:cadence:50speed:10gear:2cadence:40speed:20gear:3WhatIsInheritance?Differentkindsofobjectsoftenhaveacertainamountincommonwitheachother.Mountainbikes,roadbikes,andtandembikes,forexample,allsharethecharacteristicsofbicycles(currentspeed,currentpedalcadence,currentgear).Yeteachalsodefinesadditionalfeaturesthatmakethemdifferent:tandembicycleshavetwoseatsandtwosetsofhandlebars;roadbikeshavedrophandlebars;somemountainbikeshaveanadditionalchainring,givingthemalowergearratio.Object-orientedprogrammingallowsclassestoinheritcommonlyusedstateandbehaviorfromotherclasses.Inthisexample,BicyclenowbecomesthesuperclassofMountainBike,RoadBike,andTandemBike.IntheJavaprogramminglanguage,eachclassisallowedtohaveonedirectsuperclass,andeachsuperclasshasthepotentialforanunlimitednumberofsubclasses:Thesyntaxforcreatingasubclassissimple.Atthebeginningofyourclassdeclaration,usetheextendskeyword,followedbythenameoftheclasstoinheritfrom:classMountainBikeextendsBicycle{//newfieldsandmethodsdefiningamountainbikewouldgohere}ThisgivesMountainBikeallthesamefieldsandmethodsasBicycle,yetallowsitscodetofocusexclusivelyonthefeaturesthatmakeitunique.Thismakescodeforyoursubclasseseasytoread.However,youmusttakecaretoproperlydocumentthestateandbehaviorthateachsuperclassdefines,sincethatcodewillnotappearinthesourcefileofeachsubclass.WhatIsanInterface?Asyou'vealreadylearned,objectsdefinetheirinteractionwiththeoutsideworldthroughthemethodsthattheyexpose.Methodsformtheobject'sinterfacewiththeoutsideworld;thebuttonsonthefrontofyourtelevisionset,forexample,aretheinterfacebetweenyouandtheelectricalwiringontheothersideofitsplasticcasing.Youpressthe"power"buttontoturnthetelevisiononandoff.Initsmostcommonform,aninterfaceisagroupofrelatedmethodswithemptybodies.Abicycle'sbehavior,ifspecifiedasaninterface,mightappearasfollows:interfaceBicycle{voidchangeCadence(intnewValue);voidchangeGear(intnewValue);voidspeedUp(intincrement);voidapplyBrakes(intdecrement);}Toimplementthisinterface,thenameofyourclasswouldchange(toACMEBicycle,forexample),andyou'dusetheimplementskeywordintheclassdeclaration:classACMEBicycleimplementsBicycle{//remainderofthisclassimplementedasbefore}Implementinganinterfaceallowsaclasstobecomemoreformalaboutthebehavioritpromisestoprovide.Interfacesformacontractbetweentheclassandtheoutsideworld,andthiscontractisenforcedatbuildtimebythecompiler.Ifyourclassclaimstoimplementaninterface,allmethodsdefinedbythatinterfacemustappearinitssourcecodebeforetheclasswillsuccessfullycompile.Note:ToactuallycompiletheACMEBicycleclass,you'llneedtoaddthepublickeywordtothebeginningoftheimplementedinterfacemethods.WhatIsaPackage?Apackageisanamespacethatorganizesasetofrelatedclassesandinterfaces.Conceptuallyyoucanthinkofpackagesasbeingsimilartodifferentfoldersonyourcomputer.YoumightkeepHTMLpagesinonefolder,imagesinanother,andscriptsorapplicationsinyetanother.BecausesoftwarewrittenintheJavaprogramminglanguagecanbecomposedofhundredsorthousandsofindividualclasses,itmakessensetokeepthingsorganizedbyplacingrelatedclassesandinterfacesintopackages.TheJavaplatformprovidesanenormousclasslibrary(asetofpackages)suitableforuseinyourownapplications.Thislibraryisknownasthe"ApplicationProgrammingInterface",or"API"forshort.WhatIsaPackage?Itspackagesrepresentthetasksmostcommonlyassociatedwithgeneral-purposeprogramming.Forexample,aStringobjectcontainsstateandbehaviorforcharacterstrings;aFileobjectallowsaprogrammertoeasilycreate,delete,inspect,compare,ormodifyafileonthefilesystem;aSocketobjectallowsforthecreationanduseofnetworksockets;variousGUIobjectscontrolbuttonsandcheckboxesandanythingelserelatedtographicaluserinterfaces.ClassespublicclassBicycle{//theBicycleclasshasthreefieldspublicintcadence;publicintgear;publicintspeed;//theBicycleclasshasoneconstructorpublicBicycle(intstartCadence,intstartSpeed,intstartGear){gear=startGear;cadence=startCadence;speed=startSpeed;}//theBicycleclasshasfourmethodspublicvoidsetCadence(intnewValue){cadence=newValue;}publicvoidsetGear(intnewValue){gear=newValue;}publicvoidapplyBrake(intdecrement){speed-=decrement;}publicvoidspeedUp(intincrement){speed+=increment;}}AclassdeclarationforaMountainBikeclassthatisasubclassofBicyclemightlooklikethis:publicclassMountainBikeextendsBicycle{//theMountainBikesubclasshasonefieldpublicintseatHeight;//theMountainBikesubclasshasoneconstructorpublicMountainBike(intsHeight,intstartCadence,intstartSpeed,intstartGear){super(startCadence,startSpeed,startGear);seatHeight=sHeight;}//theMountainBikesubclasshasonemethodpublicvoidsetHeight(intnewValue){seatHeight=newValue;}}MountainBikeinheritsallthefieldsandmethodsofBicycleandaddsthefieldseatHeightandamethodtosetit(mountainbikeshaveseatsthatcanbemovedupanddownastheterraindemands).DeclaringClassesYou'veseenclassesdefinedinthefollowingway:classMyClass{//field,constructor,andmethoddeclarations}Youcanprovidemoreinformationabouttheclass,suchasthenameofitssuperclass,whetheritimplementsanyinterfaces,andsoon,atthestartoftheclassdeclaration.Forexample,classMyClassextendsMySuperClassimplementsYourInterface{//field,constructor,andmethoddeclarations}meansthatMyClassisasubclassofMySuperClassandthatitimplementstheYourInterfaceinterface.Youcanalsoaddmodifierslikepublicorprivateattheverybeginning.Ingeneral,classdeclarationscanincludethesecomponents,inorder:1.Modifierssuchaspublic,private,andanumberofothersthatyouwillencounterlater.2.Theclassname,withtheinitiallettercapitalizedbyconvention.3.Thenameoftheclass'sparent(superclass),ifany,precededbythekeywordextends.Aclasscanonlyextend(subclass)oneparent.4.Acomma-separatedlistofinterfacesimplementedbytheclass,ifany,precededbythekeywordimplements.Aclasscanimplementmorethanoneinterface.5.Theclassbody,surroundedbybraces,{}.DeclaringMemberVariablesThereareseveralkindsofvariables:oMembervariablesinaclass—thesearecalledfields.oVariablesinamethodorblockofcode—thesearecalledlocalvariables.oVariablesinmethoddeclarations—thesearecalledparameters.TheBicycleclassusesthefollowinglinesofcodetodefineitsfields:publicintcadence;publicintgear;publicintspeed;Fielddeclarationsarecomposedofthreecomponents,inorder:oZeroormoremodifiers,suchaspublicorprivate.oThefield'stype.oThefield'sname.ThefieldsofBicyclearenamedcadence,gear,andspeedandareallofdatatypeinteger(int).Thepublickeywordidentifiesthesefieldsaspublicmembers,accessiblebyanyobjectthatcanaccesstheclass.AccessModifierspublicmodifier—thefieldisaccessiblefromallclasses.privatemodifier—thefieldisaccessibleonlywithinitsownclass.DefiningMethodsHereisanexampleofatypicalmethoddeclaration:publicdoublecalculateAnswer(doublewingSpan,intnumberOfEngines,doublelength,doublegrossTons){//dothecalculationhere}Theonlyrequiredelementsofamethoddeclarationarethemethod'sreturntype,name,apairofparentheses,(),andabodybetweenbraces,{}.DefiningMethodsMoregenerally,methoddeclarationshavesixcomponents,inorder:1.Modifiers—suchaspublic,private,andothersyouwilllearnaboutlater.2.Thereturntype—thedatatypeofthevaluereturnedbythemethod,orvoidifthemethoddoesnotreturnavalue.3.Themethodname—therulesforfieldnamesapplytomethodnamesaswell,buttheconventionisalittledifferent.4.Theparameterlistinparenthesis—acomma-delimitedlistofinputparameters,precededbytheirdatatypes,enclosedbyparentheses,().Iftherearenoparameters,youmustuseemptyparentheses.5.Anexceptionlist—tobediscussedlater.6.Themethodbody,enclosedbetweenbraces—themethod'scode,includingthedeclarationoflocalvariables,goeshere.OverloadingMethodsTheJavaprogramminglanguagesupportsoverloadingmethods,andJavacandistinguishbetweenmethodswithdifferentmethodsignatures.publicclassDataArtist{...publicvoiddraw(Strings){...}publicvoiddraw(inti){...}publicvoiddraw(doublef){...}publicvoiddraw(inti,doublef){...}}OverloadingMethodsOverloadedmethodsaredifferentiatedbythenumberandthetypeoftheargumentspassedintothemethod.Youcannotdeclaremorethanonemethodwiththesamenameandthesamenumberandtypeofarguments,becausethecompilercannottellthemapart.Thecompilerdoesnotconsiderreturntypewhendifferentiatingmethods,soyoucannotdeclaretwomethodswiththesamesignatureeveniftheyhaveadifferentreturntype.ProvidingConstructorsforYourClassesAclasscontainsconstructorsthatareinvokedtocreateobjectsfromtheclassblueprint.Constructordeclarationslooklikemethoddeclarations—exceptthattheyusethenameoftheclassandhavenoreturntype.Forexample,Bicyclehasoneconstructor:publicBicycle(intstartCadence,intstartSpeed,intstartGear){gear=startGear;cadence=startCadence;speed=startSpeed;}TocreateanewBicycleobjectcalledmyBike,aconstructoriscalledbythenewoperator:BicyclemyBike=newBicycle(30,0,8);newBicycle(30,0,8)createsspaceinmemoryfortheobjectandinitializesitsfields.AlthoughBicycleonlyhasoneconstructor,itcouldhaveothers,includingano-argumentconstructor:publicBicycle(){gear=1;cadence=10;speed=0;}BicycleyourBike=newBicycle();invokestheno-argumentconstructortocreateanewBicycleobjectcalledyourBike.BothconstructorscouldhavebeendeclaredinBicyclebecausetheyhavedifferentargumentlists.Aswithmethods,theJavaplatformdifferentiatesconstructorsonthebasisofthenumberofargumentsinthelistandtheirtypes.Youcannotwritetwoconstructorsthathavethesamenumberandtypeofargumentsforthesameclass,becausetheplatformwouldnotbeabletotellthemapart.Doingsocausesacompile-timeerror.Thecompilerautomaticallyprovidesano-argument,defaultconstructorforanyclasswithoutconstructors.Thisdefaultconstructorwillcalltheno-argumentconstructorofthesuperclass.Inthissituation,thecompilerwillcomplainifthesuperclassdoesn'thaveano-argumentconstructorsoyoumustverifythatitdoes.Ifyourclasshasnoexplicitsuperclass,thenithasanimplicitsuperclassofObject,whichdoeshaveano-argumentconstructor.Youcanuseasuperclassconstructoryourself.TheMountainBikeclassatthebeginningofthislessondidjustthat.Youcanuseaccessmodifiersinaconstructor'sdeclarationtocontrolwhichotherclassescancalltheconstructor.Note:IfanotherclasscannotcallaMyClassconstructor,itcannotdirectlycreateMyClassobjects.PassingInformationtoaMethodoraConstructorpublic double computePayment (double loanAmt, double rate, double futureValue, int numPeriods ){doubleinterest=rate/100.0;doublepartial1=Math.pow((1+interest),-numPeriods);doubledenominator=(1-partial1)/interest;doubleanswer=(-loanAmt/denominator)-((futureValue*partial1)/denominator);returnanswer;}Note:Parametersreferstothelistofvariablesinamethoddeclaration.Argumentsaretheactualvaluesthatarepassedinwhenthemethodisinvoked.Whenyouinvokeamethod,theargumentsusedmustmatchthedeclaration'sparametersintypeandorder.PassingPrimitiveDataTypeArgumentspublicclassPassPrimitiveByValue{publicstaticvoidmain(String[]args){intx=3;//invokepassMethod()withxasargumentpassMethod(x);//printxtoseeifitsvaluehaschangedSystem.out.println("AfterinvokingpassMethod,x="+x);}//changeparameterinpassMethod()publicstaticvoidpassMethod(intp){p=10;}}Whenyourunthisprogram,theoutputis:AfterinvokingpassMethod,x=3PassingReferenceDataTypeArgumentsReferencedatatypeparameters,suchasobjects,arealsopassedintomethodsbyvalue.Thismeansthatwhenthemethodreturns,thepassed-inreferencestillreferencesthesameobjectasbefore.However,thevaluesoftheobject'sfieldscanbechangedinthemethod,iftheyhavetheproperaccesslevel.Forexample,consideramethodinanarbitraryclassthatmovesCircleobjects:publicvoidmoveCircle(Circlecircle,intdeltaX,intdeltaY){//codetomoveoriginofcircletox+deltaX,y+deltaYcircle.setX(circle.getX()+deltaX);circle.setY(circle.getY()+deltaY);//codetoassignanewreferencetocirclecircle=newCircle(0,0);}Letthemethodbeinvokedwiththesearguments:moveCircle(myCircle,23,56)ObjectspublicclassPoint{publicintx=0;publicinty=0;//aconstructor!publicPoint(inta,intb){x=a;y=b;}}publicclassRectangle{publicintwidth=0;publicintheight=0;publicPointorigin;//fourconstructorspublicRectangle(){origin=newPoint(0,0);}publicRectangle(Pointp){origin=p;}publicRectangle(intw,inth){origin=newPoint(0,0);width=w;height=h;}publicRectangle(Pointp,intw,inth){origin=p;width=w;height=h;}//amethodformovingtherectanglepublicvoidmove(intx,inty){origin.x=x;origin.y=y;}//amethodforcomputingtheareaoftherectanglepublicintgetArea(){returnwidth*height;}}publicclassCreateObjectDemo{publicstaticvoidmain(String[]args){//Declareandcreateapointobject//andtworectangleobjects.PointoriginOne=newPoint(23,94);RectanglerectOne=newRectangle(originOne,100,200);RectanglerectTwo=newRectangle(50,100);//displayrectOne'swidth,height,andareaSystem.out.println("WidthofrectOne:"+rectOne.width);System.out.println("HeightofrectOne:"+rectOne.height);System.out.println("AreaofrectOne:"+rectOne.getArea());//setrectTwo'spositionrectTwo.origin=originOne;//displayrectTwo'spositionSystem.out.println("XPositionofrectTwo:"+rectTwo.origin.x);System.out.println("YPositionofrectTwo:"+rectTwo.origin.y);//moverectTwoanddisplayitsnewpositionrectTwo.move(40,72);System.out.println("XPositionofrectTwo:"+rectTwo.origin.x);System.out.println("YPositionofrectTwo:"+rectTwo.origin.y);}}Thisprogramcreates,manipulates,anddisplaysinformationaboutvariousobjects.Here'stheoutput:WidthofrectOne:100HeightofrectOne:200AreaofrectOne:20000XPositionofrectTwo:23YPositionofrectTwo:94XPositionofrectTwo:40YPositionofrectTwo:72InitializinganObjectHere'sthecodeforthePointclass:publicclassPoint{publicintx=0;publicinty=0;//constructorpublicPoint(inta,intb){x=a;y=b;}}PointoriginOne=newPoint(23,94);Theresultofexecutingthisstatementcanbeillustratedinthenextfigure:Here'sthecodefortheRectangleclass,whichcontainsfourconstructors:publicclassRectangle{publicintwidth=0;publicintheight=0;publicPointorigin;//fourconstructorspublicRectangle(){origin=newPoint(0,0);}publicRectangle(Pointp){origin=p;}publicRectangle(intw,inth){origin=newPoint(0,0);width=w;height=h;}publicRectangle(Pointp,intw,inth){origin=p;width=w;height=h;}//amethodformovingtherectanglepublicvoidmove(intx,inty){origin.x=x;origin.y=y;}//amethodforcomputingtheareaoftherectanglepublicintgetArea(){returnwidth*height;}}Rectangle rectOne = new Rectangle(originOne, 100, 200); CallinganObject'sMethodsnewRectangle(100,50).getArea()TheexpressionnewRectangle(100,50)returnsanobjectreferencethatreferstoaRectangleobject.Asshown,youcanusethedotnotationtoinvokethenewRectangle'sgetArea()methodtocomputetheareaofthenewrectangle.intareaOfRectangle=newRectangle(100,50).getArea();intheight=newRectangle().height;Notethatafterthisstatementhasbeenexecuted,theprogramnolongerhasareferencetothecreatedRectangle,becausetheprogramneverstoredthereferenceanywhere.Theobjectisunreferenced,anditsresourcesarefreetoberecycledbytheJavaVirtualMachine.TheGarbageCollectorTheJavaruntimeenvironmentdeletesobjectswhenitdeterminesthattheyarenolongerbeingused.Thisprocessiscalledgarbagecollection.Anobjectiseligibleforgarbagecollectionwhentherearenomorereferencestothatobject.Referencesthatareheldinavariableareusuallydroppedwhenthevariablegoesoutofscope.Oryoucanexplicitlydropanobjectreferencebysettingthevariabletothespecialvaluenull.Rememberthataprogramcanhavemultiplereferencestothesameobject;allreferencestoanobjectmustbedroppedbeforetheobjectiseligibleforgarbagecollection.TheJavaruntimeenvironmenthasagarbagecollectorthatperiodicallyfreesthememoryusedbyobjectsthatarenolongerreferenced.Thegarbagecollectordoesitsjobautomaticallywhenitdeterminesthatthetimeisright.ReturningaValuefromaMethodAmethodreturnstothecodethatinvokeditwhenitcompletesallthestatementsinthemethod,reachesareturnstatement,orthrowsanexception(coveredlater),Youdeclareamethod'sreturntypeinitsmethoddeclaration.Withinthebodyofthemethod,youusethereturnstatementtoreturnthevalue.Ifyoutrytoreturnavaluefromamethodthatisdeclaredvoid,youwillgetacompilererror.Anymethodthatisnotdeclaredvoidmustcontainareturnstatementwithacorrespondingreturnvalue,likethis:returnreturnValue;ThegetArea()methodintheRectangleRectangleclassthatwasdiscussedinthesectionsonobjectsreturnsaninteger://amethodforcomputingtheareaoftherectanglepublicintgetArea(){returnwidth*height;}ReturningaValuefromaMethodThismethodreturnstheintegerthattheexpressionwidth*heightevaluatesto.Theareamethodreturnsaprimitivetype.Amethodcanalsoreturnareferencetype.Forexample,inaprogramtomanipulateBicycleobjects,wemighthaveamethodlikethis:publicBicycleseeWhosFastest(BicyclemyBike,BicycleyourBike,Environmentenv){Bicyclefastest;//codetocalculatewhichbikeisfaster,given//eachbike'sgearandcadenceandgiven//theenvironment(terrainandwind)returnfastest;}UsingthethisKeywordWithinaninstancemethodoraconstructor,thisisareferencetothecurrentobject—theobjectwhosemethodorconstructorisbeingcalled.Youcanrefertoanymemberofthecurrentobjectfromwithinaninstancemethodoraconstructorbyusingthis.UsingthiswithaFieldThemostcommonreasonforusingthethiskeywordisbecauseafieldisshadowedbyamethodorconstructorparameter.Forexample,thePointclasswaswrittenlikethispublicclassPoint{publicintx=0;publicinty=0;//constructorpublicPoint(inta,intb){x=a;y=b;}}UsingthiswithaFieldbutitcouldhavebeenwrittenlikethis:publicclassPoint{publicintx=0;publicinty=0;//constructorpublicPoint(intx,inty){this.x=x;this.y=y;}}Eachargumenttothesecondconstructorshadowsoneoftheobject'sfields—insidetheconstructorxisalocalcopyoftheconstructor'sfirstargument.TorefertothePointfieldx,theconstructormustusethis.x.UsingthiswithaConstructorFromwithinaconstructor,youcanalsousethethiskeywordtocallanotherconstructorinthesameclass.Doingsoiscalledanexplicitconstructorinvocation.Here'sanotherRectangleclass,withadifferentimplementationfromtheoneintheObjectssection.UsingthiswithaConstructorpublicclassRectangle{privateintx,y;privateintwidth,height;publicRectangle(){this(0,0,0,0);}publicRectangle(intwidth,intheight){this(0,0,width,height);}publicRectangle(intx,inty,intwidth,intheight){this.x=x;this.y=y;this.width=width;this.height=height;}...}UsingthiswithaConstructorThisclasscontainsasetofconstructors.Eachconstructorinitializessomeoralloftherectangle'smembervariables.Theconstructorsprovideadefaultvalueforanymembervariablewhoseinitialvalueisnotprovidedbyanargument.Forexample,theno-argumentconstructorcallsthefour-argumentconstructorwithfour0valuesandthetwo-argumentconstructorcallsthefour-argumentconstructorwithtwo0values.Asbefore,thecompilerdetermineswhichconstructortocall,basedonthenumberandthetypeofarguments.Ifpresent,theinvocationofanotherconstructormustbethefirstlineintheconstructor.ControllingAccesstoMembersofaClassAccesslevelmodifiersdeterminewhetherotherclassescanuseaparticularfieldorinvokeaparticularmethd.Therearetwolevelsofaccesscontrol:Atthetoplevel—public,orpackage-private(noexplicitmodifier).Atthememberlevel—public,private,protected,orpackage-private(noexplicitmodifier).Aclassmaybedeclaredwiththemodifierpublic,inwhichcasethatclassisvisibletoallclasseseverywhere.Ifaclasshasnomodifier(thedefault,alsoknownaspackage-private),itisvisibleonlywithinitsownpackage(packagesarenamedgroupsofrelatedclasses.)Atthememberlevel,youcanalsousethepublicmodifierornomodifier(package-private)justaswithtop-levelclasses,andwiththesamemeaning.Formembers,therearetwoadditionalaccessmodifiers:privateandprotected.Theprivatemodifierspecifiesthatthemembercanonlybeaccessedinitsownclass.Theprotectedmodifierspecifiesthatthemembercanonlybeaccessedwithinitsownpackage(aswithpackage-private)and,inaddition,byasubclassofitsclassinanotherpackage.The following table shows the access to members permitted by each modifier. Access LevelsModifierClassPackageSubclassWorldPublicYYYYprotectedYYYNno modifierYYNNPrivateYNNNUnderstandingInstanceandClassMembersInthissection,wediscusstheuseofthestatickeywordtocreatefieldsandmethodsthatbelongtotheclass,ratherthantoaninstanceoftheclass.ClassMethodsTheJavaprogramminglanguagesupportsstaticmethodsaswellasstaticvariables.Staticmethods,whichhavethestaticmodifierintheirdeclarations,shouldbeinvokedwiththeclassname,withouttheneedforcreatinganinstanceoftheclass,asinClassName.methodName(args)Note:YoucanalsorefertostaticmethodswithanobjectreferencelikeinstanceName.methodName(args)butthisisdiscouragedbecauseitdoesnotmakeitclearthattheyareclassmethods.Acommonuseforstaticmethodsistoaccessstaticfields.UnderstandingInstanceandClassMembersForexample,wecouldaddastaticmethodtotheBicycleclasstoaccessthenumberOfBicyclesstaticfield:publicstaticintgetNumberOfBicycles(){returnnumberOfBicycles;}Notallcombinationsofinstanceandclassvariablesandmethodsareallowed:Instancemethodscanaccessinstancevariablesandinstancemethodsdirectly.Instancemethodscanaccessclassvariablesandclassmethodsdirectly.Classmethodscanaccessclassvariablesandclassmethodsdirectly.Classmethodscannotaccessinstancevariablesorinstancemethodsdirectly—theymustuseanobjectreference.Also,classmethodscannotusethethiskeywordasthereisnoinstanceforthistoreferto.ConstantsThestaticmodifier,incombinationwiththefinalmodifier,isalsousedtodefineconstants.Thefinalmodifierindicatesthatthevalueofthisfieldcannotchange.Forexample,thefollowingvariabledeclarationdefinesaconstantnamedPI,whosevalueisanapproximationofpi(theratioofthecircumferenceofacircletoitsdiameter):staticfinaldoublePI=3.141592653589793;Constantsdefinedinthiswaycannotbereassigned,anditisacompile-timeerrorifyourprogramtriestodoso.Byconvention,thenamesofconstantvaluesarespelledinuppercaseletters.Ifthenameiscomposedofmorethanoneword,thewordsareseparatedbyanunderscore(_).Note:Ifaprimitivetypeorastringisdefinedasaconstantandthevalueisknownatcompiletime,thecompilerreplacestheconstantnameeverywhereinthecodewithitsvalue.Thisiscalledacompile-timeconstant.Ifthevalueoftheconstantintheoutsideworldchanges(forexample,ifitislegislatedthatpiactuallyshouldbe3.975),youwillneedtorecompileanyclassesthatusethisconstanttogetthecurrentvalue.InterfacesThereareanumberofsituationsinsoftwareengineeringwhenitisimportantfordisparategroupsofprogrammerstoagreetoa"contract"thatspellsouthowtheirsoftwareinteracts.Eachgroupshouldbeabletowritetheircodewithoutanyknowledgeofhowtheothergroup'scodeiswritten.Generallyspeaking,interfacesaresuchcontracts.InterfacesinJavaIntheJavaprogramminglanguage,aninterfaceisareferencetype,similartoaclass,thatcancontainonlyconstants,methodsignatures.Therearenomethodbodies.Interfacescannotbeinstantiated—theycanonlybeimplementedbyclassesorextendedbyotherinterfaces.Defininganinterfaceissimilartocreatinganewclass:publicinterfaceOperateCar{//constantdeclarations,ifany//methodsignaturesintturn(Directiondirection,//AnenumwithvaluesRIGHT,LEFTdoubleradius,doublestartSpeed,doubleendSpeed);intchangeLanes(Directiondirection,doublestartSpeed,doubleendSpeed);intsignalTurn(Directiondirection,booleansignalOn);intgetRadarFront(doubledistanceToCar,doublespeedOfCar);intgetRadarRear(doubledistanceToCar,doublespeedOfCar);......//moremethodsignatures}Notethatthemethodsignatureshavenobracesandareterminatedwithasemicolon.Touseaninterface,youwriteaclassthatimplementstheinterface.Whenaninstantiableclassimplementsaninterface,itprovidesamethodbodyforeachofthemethodsdeclaredintheinterface.Forexample,publicclassOperateBMW760iimplementsOperateCar{//theOperateCarmethodsignatures,withimplementation--//forexample:intsignalTurn(Directiondirection,booleansignalOn){//codetoturnBMW'sLEFTturnindicatorlightson//codetoturnBMW'sLEFTturnindicatorlightsoff//codetoturnBMW'sRIGHTturnindicatorlightson//codetoturnBMW'sRIGHTturnindicatorlightsoff}//othermembers,asneeded--forexample,helperclasses//notvisibletoclientsoftheinterface}Intheroboticcarexampleabove,itistheautomobilemanufacturerswhowillimplementtheinterface.InterfacesasAPIsTheroboticcarexampleshowsaninterfacebeingusedasanindustrystandardApplicationProgrammingInterface(API).APIsarealsocommonincommercialsoftwareproducts.Typically,acompanysellsasoftwarepackagethatcontainscomplexmethodsthatanothercompanywantstouseinitsownsoftwareproduct.Anexamplewouldbeapackageofdigitalimageprocessingmethodsthataresoldtocompaniesmakingend-usergraphicsprograms.Theimageprocessingcompanywritesitsclassestoimplementaninterface,whichitmakespublictoitscustomers.Thegraphicscompanytheninvokestheimageprocessingmethodsusingthesignaturesandreturntypesdefinedintheinterface.InterfacesandMultipleInheritanceInterfaceshaveanotherveryimportantroleintheJavaprogramminglanguage.Interfacesarenotpartoftheclasshierarchy,althoughtheyworkincombinationwithclasses.TheJavaprogramminglanguagedoesnotpermitmultipleinheritances,butinterfacesprovideanalternative.InJava,aclasscaninheritfromonlyoneclassbutitcanimplementmorethanoneinterface.DefininganInterfaceAninterfaceusesthekeywordinterface,theinterfacename,acomma-separatedlistofparentinterfaces(ifany),andtheinterfacebody.Forexample:publicinterfaceGroupedInterfaceextendsInterface1,Interface2,Interface3{//constantdeclarationsdoubleE=2.718282;//baseofnaturallogarithms//methodsignaturesvoiddoSomething(inti,doublex);intdoSomethingElse(Strings);}Thepublicaccessspecifierindicatesthattheinterfacecanbeusedbyanyclassinanypackage.Ifyoudonotspecifythattheinterfaceispublic,yourinterfacewillbeaccessibleonlytoclassesdefinedinthesamepackageastheinterface.DefininganInterfaceAninterfacecanextendotherinterfaces,justasaclasscanextendorsubclassanotherclass.However,whereasaclasscanextendonlyoneotherclass,aninterfacecanextendanynumberofinterfaces.Theinterfacedeclarationincludesacomma-separatedlistofalltheinterfacesthatitextends.Allconstantvaluesdefinedinaninterfaceareimplicitlypublic,static,andfinal.Onceagain,thesemodifierscanbeomitted.publicinterfacearea{finalstaticfloatpi=3.14F;floatcompute(floatx,floaty);}DefininganInterfaceclassrectangleimplementsarea{publicfloatcompute(floatx,floaty){return(x*y);}}classcircleimplementsarea{publicfloatcompute(floatx,floaty){return(pi*x*x);}}classinterfacetest{publicstaticvoidmain(Stringargs[]){rectanglerect=newrectangle();circlecir=newcircle();System.out.println("areaofrectangle"+rect.compute(10,20));System.out.println("areaofcircle"+cir.compute(10,20));}}RewritingInterfacesConsideraninterfacethatyouhavedevelopedcalledDoIt:publicinterfaceDoIt{voiddoSomething(inti,doublex);intdoSomethingElse(Strings);}Supposethat,atalatertime,youwanttoaddathirdmethodtoDoIt,sothattheinterfacenowbecomes:publicinterfaceDoIt{voiddoSomething(inti,doublex);intdoSomethingElse(Strings);booleandidItWork(inti,doublex,Strings);}Ifyoumakethischange,allclassesthatimplementtheoldDoItinterfacewillbreakbecausetheydon'timplementtheinterfaceanymore.Programmersrelyingonthisinterfacewillprotestloudly.RewritingInterfacesTrytoanticipateallusesforyourinterfaceandtospecifyitcompletelyfromthebeginning.Giventhatthisisoftenimpossible,youmayneedtocreatemoreinterfaceslater.Forexample,youcouldcreateaDoItPlusinterfacethatextendsDoIt:publicinterfaceDoItPlusextendsDoIt{booleandidItWork(inti,doublex,Strings);}Nowusersofyourcodecanchoosetocontinuetousetheoldinterfaceortoupgradetothenewinterface.InheritanceIntheJavalanguage,classescanbederivedfromotherclasses,therebyinheritingfieldsandmethodsfromthoseclasses.Aclassthatisderivedfromanotherclassiscalledasubclass(alsoaderivedclass,extendedclass,orchildclass).Theclassfromwhichthesubclassisderivediscalledasuperclass(alsoabaseclassoraparentclass).Asubclassinheritsallthemembers(fields,methods,andnestedclasses)fromitssuperclass.Constructorsarenotmembers,sotheyarenotinheritedbysubclasses,buttheconstructorofthesuperclasscanbeinvokedfromthesubclass.AnExampleofInheritanceHereisthesamplecodeforapossibleimplementationofaBicycleclassthatwaspresentedintheClassesandObjectslesson:publicclassBicycle{//theBicycleclasshasthreefieldspublicintcadence;publicintgear;publicintspeed;//theBicycleclasshasoneconstructorpublicBicycle(intstartCadence,intstartSpeed,intstartGear){gear=startGear;cadence=startCadence;speed=startSpeed;}//theBicycleclasshasfourmethodspublicvoidsetCadence(intnewValue){cadence=newValue;}AnExampleofInheritancepublicvoidsetGear(intnewValue){gear=newValue;}publicvoidapplyBrake(intdecrement){speed-=decrement;}publicvoidspeedUp(intincrement){speed+=increment;}}AnExampleofInheritanceAclassdeclarationforaMountainBikeclassthatisasubclassofBicyclemightlooklikethis:publicclassMountainBikeextendsBicycle{//theMountainBikesubclassaddsonefieldpublicintseatHeight;//theMountainBikesubclasshasoneconstructorpublicMountainBike(intstartHeight,intstartCadence,intstartSpeed,intstartGear){super(startCadence,startSpeed,startGear);seatHeight=startHeight;}//theMountainBikesubclassaddsonemethodpublicvoidsetHeight(intnewValue){seatHeight=newValue;}}AnExampleofInheritanceMountainBikeinheritsallthefieldsandmethodsofBicycleandaddsthefieldseatHeightandamethodtosetit.Exceptfortheconstructor,itisasifyouhadwrittenanewMountainBikeclassentirelyfromscratch,withfourfieldsandfivemethods.However,youdidn'thavetodoallthework.WhatYouCanDoinaSubclassAsubclassinheritsallofthepublicandprotectedmembersofitsparent,nomatterwhatpackagethesubclassisin.Ifthesubclassisinthesamepackageasitsparent,italsoinheritsthepackage-privatemembersoftheparent.WhatYouCanDoinaSubclassYoucanusetheinheritedmembersasis,replacethem,hidethem,orsupplementthemwithnewmembers:Theinheritedfieldscanbeuseddirectly,justlikeanyotherfields.Youcandeclareafieldinthesubclasswiththesamenameastheoneinthesuperclass,thushidingit(notrecommended).Youcandeclarenewfieldsinthesubclassthatarenotinthesuperclass.Theinheritedmethodscanbeuseddirectlyastheyare.Youcanwriteanewinstancemethodinthesubclassthathasthesamesignatureastheoneinthesuperclass,thusoverridingit.Youcanwriteanewstaticmethodinthesubclassthathasthesamesignatureastheoneinthesuperclass,thushidingit.Youcandeclarenewmethodsinthesubclassthatarenotinthesuperclass.Youcanwriteasubclassconstructorthatinvokestheconstructorofthesuperclass,eitherimplicitlyorbyusingthekeywordsuper.OverridingandHidingMethodsInstanceMethodsAninstancemethodinasubclasswiththesamesignature(name,plusthenumberandthetypeofitsparameters)andreturntypeasaninstancemethodinthesuperclassoverridesthesuperclass'smethod.Theabilityofasubclasstooverrideamethodallowsaclasstoinheritfromasuperclasswhosebehavioris"closeenough"andthentomodifybehaviorasneeded.Theoverridingmethodhasthesamename,numberandtypeofparameters,andreturntypeasthemethoditoverrides.ClassMethodsIfasubclassdefinesaclassmethodwiththesamesignatureasaclassmethodinthesuperclass,themethodinthesubclasshidestheoneinthesuperclass.Thedistinctionbetweenhidingandoverridinghasimportantimplications.Theversionoftheoverriddenmethodthatgetsinvokedistheoneinthesubclass.Theversionofthehiddenmethodthatgetsinvokeddependsonwhetheritisinvokedfromthesuperclassorthesubclass.Let'slookatanexamplethatcontainstwoclasses.ThefirstisAnimal,whichcontainsoneinstancemethodandoneclassmethod:publicclassAnimal{publicstaticvoidtestClassMethod(){System.out.println("TheclassmethodinAnimal.");}publicvoidtestInstanceMethod(){System.out.println("TheinstancemethodinAnimal.");}}ClassMethodsIfasubclassdefinesaclassmethodwiththesamesignatureasaclassmethodinthesuperclass,themethodinthesubclasshidestheoneinthesuperclass.Thedistinctionbetweenhidingandoverridinghasimportantimplications.Theversionoftheoverriddenmethodthatgetsinvokedistheoneinthesubclass.Theversionofthehiddenmethodthatgetsinvokeddependsonwhetheritisinvokedfromthesuperclassorthesubclass.Let'slookatanexamplethatcontainstwoclasses.ThefirstisAnimal,whichcontainsoneinstancemethodandoneclassmethod:publicclassAnimal{publicstaticvoidtestClassMethod(){System.out.println("TheclassmethodinAnimal.");}publicvoidtestInstanceMethod(){System.out.println("TheinstancemethodinAnimal.");}}ClassMethodsThesecondclass,asubclassofAnimal,iscalledCat:publicclassCatextendsAnimal{publicstaticvoidtestClassMethod(){System.out.println("TheclassmethodinCat.");}publicvoidtestInstanceMethod(){System.out.println("TheinstancemethodinCat.");}publicstaticvoidmain(String[]args){CatmyCat=newCat();AnimalmyAnimal=myCat;Animal.testClassMethod();myAnimal.testInstanceMethod();}}TheCatclassoverridestheinstancemethodinAnimalandhidestheclassmethodinAnimal.ClassMethodsThemainmethodinthisclasscreatesaninstanceofCatandcallstestClassMethod()ontheclassandtestInstanceMethod()ontheinstance.Theoutputfromthisprogramisasfollows:TheclassmethodinAnimal.TheinstancemethodinCat.ModifiersTheaccessspecifierforanoverridingmethodcanallowmore,butnotless,accessthantheoverriddenmethod.Forexample,aprotectedinstancemethodinthesuperclasscanbemadepublic,butnotprivate,inthesubclass.Youwillgetacompile-timeerrorifyouattempttochangeaninstancemethodinthesuperclasstoaclassmethodinthesubclass,andviceversa.SummaryThe following table summarizes what happens when you define a method with the same signature as a method in a superclass. Defining a Method with the Same Signature as a Superclass's MethodSuperclass Instance Method Superclass Static Method Subclass Instance Method Overrides Generates a compile-time error Subclass Static Method Generates a compile-time error Hides UsingtheKeywordsuperAccessingSuperclassMembersIfyourmethodoverridesoneofitssuperclass'smethods,youcaninvoketheoverriddenmethodthroughtheuseofthekeywordsuper.Youcanalsousesupertorefertoahiddenfield(althoughhidingfieldsisdiscouraged).Considerthisclass,Superclass:publicclassSuperclass{publicvoidprintMethod(){System.out.println("PrintedinSuperclass.");}}AccessingSuperclassMembersHereisasubclass,calledSubclass,thatoverridesprintMethod():publicclassSubclassextendsSuperclass{publicvoidprintMethod(){//overridesprintMethodinSuperclasssuper.printMethod();System.out.println("PrintedinSubclass");}publicstaticvoidmain(String[]args){Subclasss=newSubclass();s.printMethod();}}WithinSubclass,thesimplenameprintMethod()referstotheonedeclaredinSubclass,whichoverridestheoneinSuperclass.So,torefertoprintMethod()inheritedfromSuperclass,Subclassmustuseaqualifiedname,usingsuperasshown.CompilingandexecutingSubclassprintsthefollowing:PrintedinSuperclass.PrintedinSubclassSubclassConstructorsThefollowingexampleillustrateshowtousethesuperkeywordtoinvokeasuperclass'sconstructor.publicMountainBike(intstartHeight,intstartCadence,intstartSpeed,intstartGear){super(startCadence,startSpeed,startGear);seatHeight=startHeight;}Invocationofasuperclassconstructormustbethefirstlineinthesubclassconstructor.Thesyntaxforcallingasuperclassconstructorissuper();--or--super(parameterlist);Withsuper(),thesuperclassno-argumentconstructoriscalled.Withsuper(parameterlist),thesuperclassconstructorwithamatchingparameterlistiscalled.CreatingaPackageTocreateapackage,youchooseanameforthepackageandputapackagestatementwiththatnameatthetopofeverysourcefilethatcontainsthetypes(classes,interfaces)thatyouwanttoincludeinthepackage.Thepackagestatement(forexample,packagegraphics;)mustbethefirstlineinthesourcefile.Therecanbeonlyonepackagestatementineachsourcefile,anditappliestoalltypesinthefile.Ifyouputthegraphicsinterfaceandclasseslistedintheprecedingsectioninapackagecalledgraphics,youwouldneedsixsourcefiles,likethis:CreatingaPackage//intheDraggable.javafilepackagegraphics;publicinterfaceDraggable{...}//intheGraphic.javafilepackagegraphics;publicabstractclassGraphic{...}//intheCircle.javafilepackagegraphics;publicclassCircleextendsGraphicimplementsDraggable{...}//intheRectangle.javafilepackagegraphics;publicclassRectangleextendsGraphicimplementsDraggable{...}//inthePoint.javafilepackagegraphics;publicclassPointextendsGraphicimplementsDraggable{...}//intheLine.javafilepackagegraphics;publicclassLineextendsGraphicimplementsDraggable{...}Ifyoudonotuseapackagestatement,yourtypeendsupinanunnamedpackage.Generallyspeaking,anunnamedpackageisonlyforsmallortemporaryapplicationsorwhenyouarejustbeginningthedevelopmentprocess.NamingConventionsPackagenamesarewritteninalllowercasetoavoidconflictwiththenamesofclassesorinterfaces.PackagesintheJavalanguageitselfbeginwithjava.orjavax.ImportingaPackageMemberToimportaspecificmemberintothecurrentfile,putanimportstatementatthebeginningofthefilebeforeanytypedefinitionsbutafterthepackagestatement,ifthereisone.Here'showyouwouldimporttheRectangleclassfromthegraphicspackagecreated.importgraphics.Rectangle;NowyoucanrefertotheRectangleclassbyitssimplename.RectanglemyRectangle=newRectangle();Thisapproachworkswellifyouusejustafewmembersfromthegraphicspackage.Butifyouusemanytypesfromapackage,youshouldimporttheentirepackage.ImportinganEntirePackageToimportallthetypescontainedinaparticularpackage,usetheimportstatementwiththeasterisk(*)wildcardcharacter.importgraphics.*;Nowyoucanrefertoanyclassorinterfaceinthegraphicspackagebyitssimplename.Theasteriskintheimportstatementcanbeusedonlytospecifyalltheclasseswithinapackage,asshownhere.Forexample,thefollowingdoesnotmatchalltheclassesinthegraphicspackagethatbeginwithA.importgraphics.A*;//doesnotworkInstead,itgeneratesacompilererror.Withtheimportstatement,yougenerallyimportonlyasinglepackagememberoranentirepackage.NameAmbiguitiesIfamemberinonepackagesharesitsnamewithamemberinanotherpackageandbothpackagesareimported,youmustrefertoeachmemberbyitsqualifiedname.Forexample,thegraphicspackagedefinedaclassnamedRectangle.Thejava.awtpackagealsocontainsaRectangleclass.Ifbothgraphicsandjava.awthavebeenimported,thefollowingisambiguous.Rectanglerect;Insuchasituation,youhavetousethemember'sfullyqualifiednametoindicateexactlywhichRectangleclassyouwant.Forexample,graphics.Rectanglerect;TheStaticImportStatementTherearesituationswhereyouneedfrequentaccesstostaticfinalfields(constants)andstaticmethodsfromoneortwoclasses.Prefixingthenameoftheseclassesoverandovercanresultinclutteredcode.Thestaticimportstatementgivesyouawaytoimporttheconstantsandstaticmethodsthatyouwanttousesothatyoudonotneedtoprefixthenameoftheiclass.Thejava.lang.MathclassdefinesthePIconstantandmanystaticmethods,includingmethodsforcalculatingsines,cosines,tangents,squareroots,maxima,minima,exponents,andmanymore.Forexample,publicstaticfinaldoublePI3.141592653589793publicstaticdoublecos(doublea)Ordinarily,tousetheseobjectsfromanotherclass,youprefixtheclassname,asfollows.doubler=Math.cos(Math.PI*theta);Youcanusethestaticimportstatementtoimportthestaticmembersofjava.lang.Mathsothatyoudon'tneedtoprefixtheclassname,Math.ThestaticmembersofMathcanbeimportedeitherindividually:importstaticjava.lang.Math.PI;orasagroup:importstaticjava.lang.Math.*;Oncetheyhavebeenimported,thestaticmemberscanbeusedwithoutqualification.Forexample,thepreviouscodesnippetwouldbecome:doubler=cos(PI*theta);Obviously,youcanwriteyourownclassesthatcontainconstantsandstaticmethodsthatyouusefrequently,andthenusethestaticimportstatement.Forexample,importstaticmypackage.MyConstants.*;Note:Usestaticimportverysparingly.Overusingstaticimportcanresultincodethatisdifficulttoreadandmaintain,becausereadersofthecodewon'tknowwhichclassdefinesaparticularstaticobject.Usedproperly,staticimportmakescodemorereadablebyremovingclassnamerepetition.SettingtheCLASSPATHSystemVariableTodisplaythecurrentCLASSPATHvariable,usethesecommandsinWindowsInWindows:C:\>setCLASSPATHTodeletethecurrentcontentsoftheCLASSPATHvariable,usethesecommands:InWindows:C:\>setCLASSPATH=TosettheCLASSPATHvariable,usethesecommands(forexample):InWindows:C:\>setCLASSPATH=C:\users\george\java\classesI/OStreamsAnI/OStreamrepresentsaninputsourceoranoutputdestination.Astreamcanrepresentmanydifferentkindsofsourcesanddestinations,includingdiskfiles,devices,otherprograms,andmemoryarrays.Streamssupportmanydifferentkindsofdata,includingsimplebytes,primitivedatatypes,localizedcharacters,andobjects.Somestreamssimplypassondata;othersmanipulateandtransformthedatainusefulways.Astreamisasequenceofdata.Reading information into a program.A program uses an output streamto write data to a destination, one item at time: A program uses an input streamto read data from a source, one item at a time: Writinginformationfromaprogram.Forsampleinput,we'llusetheexamplefileinput.txt,whichcontainsthefollowingverse:Astatelypleasure-domedecree:WhereAlph,thesacredriver,ranThroughcavernsmeasurelesstomanDowntoasunlesssea.ByteStreamsProgramsusebytestreamstoperforminputandoutputof8-bitbytes.AllbytestreamclassesaredescendedfromInputStreamandOutputStream.Therearemanybytestreamclasses.Todemonstratehowbytestreamswork,we'llfocusonthefileI/Obytestreams,FileInputStreamandFileOutputStream.Otherkindsofbytestreamsareusedinmuchthesameway;theydiffermainlyinthewaytheyareconstructed.UsingByteStreamsWe'llexploreFileInputStreamandFileOutputStreambyexamininganexampleprogramnamedCopyBytes,whichusesbytestreamstocopyinput.txt,onebyteatatime.importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;UsingByteStreamspublicclassCopyBytes{publicstaticvoidmain(String[]args)throwsIOException{FileInputStreamin=null;FileOutputStreamout=null;try{in=newFileInputStream("input.txt");out=newFileOutputStream("output.txt");intc;while((c=in.read())!=-1){out.write(c);}}UsingByteStreamsfinally{if(in!=null){in.close();}if(out!=null){out.close();}}}}CopyBytesspendsmostofitstimeinasimpleloopthatreadstheinputstreamandwritestheoutputstream,onebyteatatime,asshowninthefigure.Simple byte stream input and output.Notice that read()returns an intvalue. Using a intas a return type allows read()to use -1 to indicate that it has reached the end of the stream. AlwaysCloseStreamsClosingastreamwhenit'snolongerneededisveryimportant—soimportantthatCopyBytesusesafinallyblocktoguaranteethatbothstreamswillbeclosedevenifanerroroccurs.Thispracticehelpsavoidseriousresourceleaks.OnepossibleerroristhatCopyByteswasunabletoopenoneorbothfiles.Whenthathappens,thestreamvariablecorrespondingtothefileneverchangesfromitsinitialnullvalue.That'swhyCopyBytesmakessurethateachstreamvariablecontainsanobjectreferencebeforeinvokingclose.WhenNottoUseByteStreamsCopyBytesseemslikeanormalprogram,butitactuallyrepresentsakindoflow-levelI/Othatyoushouldavoid.Sinceinput.txtcontainscharacterdata,thebestapproachistousecharacterstreams.Therearealsostreamsformorecomplicateddatatypes.CharacterStreamsTheJavaplatformstorescharactervaluesusingUnicodeconventions.CharacterstreamI/Oautomaticallytranslatesthisinternalformattoandfromthelocalcharacterset.Formostapplications,I/OwithcharacterstreamsisnomorecomplicatedthanI/Owithbytestreams.Inputandoutputdonewithstreamclassesautomaticallytranslatestoandfromthelocalcharacterset.UsingCharacterStreamsAllcharacterstreamclassesaredescendedfromReaderandWriter.Aswithbytestreams,therearecharacterstreamclassesthatspecializeinfileI/O:FileReaderandFileWriter.TheCopyCharactersexampleillustratestheseclasses.importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;publicclassCopyCharacters{publicstaticvoidmain(String[]args)throwsIOException{FileReaderinputStream=null;FileWriteroutputStream=null;UsingCharacterStreamstry{inputStream=newFileReader("xanadu.txt");outputStream=newFileWriter("characteroutput.txt");intc;while((c=inputStream.read())!=-1){outputStream.write(c);}}finally{if(inputStream!=null){inputStream.close();}if(outputStream!=null){outputStream.close();}}}}UsingCharacterStreamsCopyCharactersisverysimilartoCopyBytes.ThemostimportantdifferenceisthatCopyCharactersusesFileReaderandFileWriterforinputandoutputinplaceofFileInputStreamandFileOutputtream.NoticethatbothCopyBytesandCopyCharactersuseanintvariabletoreadtoandwritefrom.However,inCopyCharacters,theintvariableholdsacharactervalueinitslast16bits;inCopyBytes,theintvariableholdsabytevalueinitslast8bits.I/OfromtheCommandLineAprogramisoftenrunfromthecommandlineandinteractswiththeuserinthecommandlineenvironment.TheJavaplatformsupportsthiskindofinteractionintwoways:•StandardStreamsand•Console.StandardStreamsStandardStreamsareafeatureofmanyoperatingsystems.Bydefault,theyreadinputfromthekeyboardandwriteoutputtothedisplay.TheyalsosupportI/Oonfilesandbetweenprograms,butthatfeatureiscontrolledbythecommandlineinterpreter,nottheprogram.TheJavaplatformsupportsthreeStandardStreams:StandardInput,accessedthroughSystem.in;StandardOutput,accessedthroughSystem.out;andStandardError,accessedthroughSystem.err.Theseobjectsaredefinedautomaticallyanddonotneedtobeopened.StandardOutputandStandardErrorarebothforoutput;Bycontrast,System.inisabytestreamwithnocharacterstreamfeatures.TouseStandardInputasacharacterstream,wrapSystem.ininInputStreamReader.InputStreamReadercin=newInputStreamReader(System.in);The ConsoleAmoreadvancedalternativetotheStandardStreamsistheConsole.Thisisasingle,predefinedobjectoftypeConsolethathasmostofthefeaturesprovidedbytheStandardStreams,andothersbesides.TheConsoleisparticularlyusefulforsecurepasswordentry.TheConsoleobjectalsoprovidesinputandoutputstreamsthataretruecharacterstreams,throughitsreaderandwritermethods.BeforeaprogramcanusetheConsole,itmustattempttoretrievetheConsoleobjectbyinvokingSystem.console().IftheConsoleobjectisavailable,thismethodreturnsit.IfSystem.consolereturnsNULL,thenConsoleoperationsarenotpermitted,eitherbecausetheOSdoesn'tsupportthemorbecausetheprogramwaslaunchedinanoninteractiveenvironment.TheConsoleTheConsoleobjectsupportssecurepasswordentrythroughitsreadPasswordmethod.Thismethodhelpssecurepasswordentryintwoways.First,itsuppressesechoing,sothepasswordisnotvisibleontheuser'sscreen.Second,readPasswordreturnsacharacterarray,notaString,sothepasswordcanbeoverwritten,removingitfrommemoryassoonasitisnolongerneededThePasswordexampleisaprototypeprogramforchangingauser'spassword.ItdemonstratesseveralConsolemethods.importjava.io.Console;importjava.util.Arrays;importjava.io.IOException;publicclassPassword{publicstaticvoidmain(Stringargs[])throwsIOException{Consolec=System.console();if(c==null){System.err.println("Noconsole.");System.exit(1);}Stringlogin=c.readLine("Enteryourlogin:");ThePasswordexampleisaprototypeprogramforchangingauser'spassword.ItdemonstratesseveralConsolemethods.Stringlogin=c.readLine("Enteryourlogin:");char[]oldPassword=c.readPassword("Enteryouroldpassword:");if(verify(login,oldPassword)){booleannoMatch;do{char[]newPassword1=c.readPassword("Enteryournewpassword:");char[]newPassword2=c.readPassword("Enternewpasswordagain:");noMatch=!Arrays.equals(newPassword1,newPassword2);if(noMatch){c.format("Passwordsdon'tmatch.Tryagain.%n");}else{change(login,newPassword1);c.format("Passwordfor%schanged.%n",login);}ThePasswordexampleisaprototypeprogramforchangingauser'spassword.ItdemonstratesseveralConsolemethods.Arrays.fill(newPassword1,'');Arrays.fill(newPassword2,'');}while(noMatch);}Arrays.fill(oldPassword,'');}//Dummyverifymethod.staticbooleanverify(Stringlogin,char[]password){returntrue;}//Dummychangemethod.staticvoidchange(Stringlogin,char[]password){}}Password follows these steps: 1.Attempt to retrieve the Console object. If the object is not available, abort. 2.Invoke Console.readLine to prompt for and read the user's login name. 3.Invoke Console.readPassword to prompt for and read the user's existing password. 4.Invoke verify to confirm that the user is authorized to change the password. (In this example, verify is a dummy method that always returns true.) 5.Repeat the following steps until the user enters the same password twice: a.Invoke Console.readPassword twice to prompt for and read a new password. b.If the user entered the same password both times, invoke change to change it. (Again, change is a dummy method.) c.Overwrite both passwords with blanks. 6.Overwrite the old password with blanks. TheprintandprintlnMethodsInvokingprintorprintlnoutputsasinglevalueafterconvertingthevalueusingtheappropriatetoStringmethod.WecanseethisintheRootexample:publicclassRoot{publicstaticvoidmain(String[]args){inti=2;doubler=Math.sqrt(i);System.out.print("Thesquarerootof");System.out.print(i);System.out.print("is");System.out.print(r);System.out.println(".");i=5;r=Math.sqrt(i);System.out.println("Thesquarerootof"+i+"is"+r+".");}}HereistheoutputofRoot:Thesquarerootof2is1.4142135623730951.Thesquarerootof5is2.23606797749979.TheformatMethodTheformatmethodformatsmultipleargumentsbasedonaformatstring.Theformatstringconsistsofstatictextembeddedwithformatspecifiers;exceptfortheformatspecifiers,theformatstringisoutputunchanged.TheRoot2exampleformatstwovalueswithasingleformatinvocation:publicclassRoot2{publicstaticvoidmain(String[]args){inti=2;doubler=Math.sqrt(i);System.out.format("Thesquarerootof%dis%f.%n",i,r);}}Hereistheoutput:Thesquarerootof2is1.414214.Like the three used in this example, all format specifiers begin with a % and end with a 1-or 2-character conversionthat specifies the kind of formatted output being generated. The three conversions used here are: d formats an integer value as a decimal value. f formats a floating point value as a decimal value. n outputs a platform-specific line terminator. Here are some other conversions: x formats an integer as a hexadecimal value. s formats any value as a string. tB formats an integer as a locale-specific month name.In addition to the conversion, a format specifier can contain several additional elements that further customize the formatted output. Here's an example, Format, that uses every possible kind of element. public class Format { public static void main(String[] args) { System.out.format("%f, %1$+020.10f %n", Math.PI); }}Here's the output: 3.141593, +00000003.1415926536The additional elements are all optional. The following figure shows how the longer specifier breaks down into elements. Elements of a Format Specifier.WhatIsanException?Thetermexceptionisshorthandforthephrase"exceptionalevent."Definition:Anexceptionisanevent,whichoccursduringtheexecutionofaprogramthatdisruptsthenormalflowoftheprogram'sinstructions.Whenanerroroccurswithinamethod,themethodcreatesanobjectandhandsitofftotheruntimesystem.Theobject,calledanexceptionobject,containsinformationabouttheerror,includingitstypeandthestateoftheprogramwhentheerroroccurred.Creatinganexceptionobjectandhandingittotheruntimesystemiscalledthrowinganexception.Afteramethodthrowsanexception,theruntimesystemattemptstofindsomethingtohandleit.Thesetofpossible"somethings"tohandletheexceptionistheorderedlistofmethodsthathadbeencalledtogettothemethodwheretheerroroccurred.Thelistofmethodsisknownasthecallstack(seethenextfigure).Thecallstack.Theruntimesystemsearchesthecallstackforamethodthatcontainsablockofcodethatcanhandletheexception.Thisblockofcodeiscalledanexceptionhandler.Thesearchbeginswiththemethodinwhichtheerroroccurredandproceedsthroughthecallstackinthereverseorderinwhichthemethodswerecalled.Whenanappropriatehandlerisfound,theruntimesystempassestheexceptiontothehandler.Anexceptionhandlerisconsideredappropriateifthetypeoftheexceptionobjectthrownmatchesthetypethatcanbehandledbythehandler.Theexceptionhandlerchosenissaidtocatchtheexception.Iftheruntimesystemsearchesallthemethodsonthecallstackwithoutfindinganappropriateexceptionhandler,asshowninthenextfigure,theruntimesystem(and,consequently,theprogram)terminates.Searchingthecallstackfortheexceptionhandler.TheThreeKindsofExceptionsThefirstkindofexceptionisthecheckedexception.Forexample,supposeanapplicationpromptsauserforaninputfilename,thenopensthefilebypassingthenametotheconstructorforjava.io.FileReader.Normally,theuserprovidesthenameofanexisting,readablefile,sotheconstructionoftheFileReaderobjectsucceeds,andtheexecutionoftheapplicationproceedsnormally.Butsometimestheusersuppliesthenameofanonexistentfile,andtheconstructorthrowsjava.io.FileNotFoundException.Awell-writtenprogramwillcatchthisexceptionandnotifytheuserofthemistake,possiblypromptingforacorrectedfilename.CheckedexceptionsaresubjecttotheCatchorSpecifyRequirement.Allexceptionsarecheckedexceptions,exceptforthoseindicatedbyError,RuntimeException,andtheirsubclasses.Thesecondkindofexceptionistheerror.Theseareexceptionalconditionsthatareexternaltotheapplication,andthattheapplicationusuallycannotanticipateorrecoverfrom.Forexample,supposethatanapplicationsuccessfullyopensafileforinput,butisunabletoreadthefilebecauseofahardwareorsystemerrorfunction.Theunsuccessfulreadwillthrowjava.io.IOError.Anapplicationmightchoosetocatchthisexception,inordertonotifytheuseroftheproblem—butitalsomightmakesensefortheprogramtoprintastacktraceandexit.ErrorsarenotsubjecttotheCatchorSpecifyRequirement.ErrorsarethoseexceptionsindicatedbyErroranditssubclasses.Thethirdkindofexceptionistheruntimeexception.Theseareexceptionalconditionsthatareinternaltotheapplication,andthattheapplicationusuallycannotanticipateorrecoverfrom.Theseusuallyindicateprogrammingbugs,suchaslogicerrorsorimproperuseofanAPI.Forexample,considertheapplicationdescribedpreviouslythatpassesafilenametotheconstructorforFileReader.Ifalogicerrorcausesanulltobepassedtotheconstructor,theconstructorwillthrowNullPointerException.Theapplicationcancatchthisexception,butitprobablymakesmoresensetoeliminatethebugthatcausedtheexceptiontooccur.RuntimeexceptionsarenotsubjecttotheCatchorSpecifyRequirement.RuntimeexceptionsarethoseindicatedbyRuntimeExceptionanditssubclasses.Errorsandruntimeexceptionsarecollectivelyknownasuncheckedexceptions.CatchingandHandlingExceptionsThefollowingexampledefinesandimplementsaclassnamedListOfNumbers.Whenconstructed,ListOfNumberscreatesaVectorthatcontains10Integerelementswithsequentialvalues0through9.TheListOfNumbersclassalsodefinesamethodnamedwriteList,whichwritesthelistofnumbersintoatextfilecalledOutFile.txt.//Note:Thisclasswon'tcompilebydesign!importjava.io.*;importjava.util.Vector;publicclassListOfNumbers{privateVectorvector;privatestaticfinalintSIZE=10;publicListOfNumbers(){vector=newVector(SIZE);for(inti=0;iHello, worldKnow where to place this file and how to see it in your browser with an http://prefix. Your first JSPJSP simply puts Java inside HTML pages.You can take any existing HTML page and change its extension to ".jsp" instead of ".html".In fact, this is the perfect exercise for your first JSP. Take the HTML file you used in the previous exercise.Change its extension from ".html" to ".jsp".Now load the new file, with the ".jsp" extension, in your browser. You will see the same output, but it will take longer!But only the first time.If you reload it again, it will load normally. What is happening behind the scenes is that your JSP is being turned into a Java file, compiled and loaded.This compilation only happens once, so after the first load, the file doesn't take long to load anymore.(But everytime you change the JSP file, it will be re-compiled again.) Of course, it is not very useful to just write HTML pages with a .jsp extension!We now proceed to see what makes JSP so useful. Adding dynamic content via expressionsAs we saw in the previous section, any HTML file can be turned into a JSP file by changing its extension to .jsp.Put the following text in a file with .jsp extension (let us call it hello.jsp), place it in your JSP directory, and view it in a browser.Hello!The time is now <%= new java.util.Date() %> Notice that each time you reload the page in the browser, it comes up with the current time. The character sequences <%= and %> enclose Java expressions, which are evaluated at run time. This is what makes it possible to use JSP to generate dyamic HTML pages that change in response to user actions or vary from user to user. ScriptletsWe have already seen how to embed Java expressions in JSP pages by putting them between the <%=and %>character sequences. But it is difficult to do much programming just by putting Java expressions inside HTML. JSP also allows you to write blocks of Java code inside the JSP.You do this by placing your Java code between <%and %>characters (just like expressions, but without the =sign at the start of the sequence.) This block of code is known as a "scriptlet".By itself, a scriptlet doesn't contribute any HTML. A scriptlet contains Java code that is executed every time the JSP is invoked.ScriptletsHere is a modified version of our JSP from previous section, adding in a scriptlet. <%//This is a scriptlet.Notice that the "date"//variable we declare here is available in the//embedded expression later on.System.out.println( "Evaluating date now" );java.util.Date date = new java.util.Date();%>Hello!The time is now <%= date %> If you run the above example, you will notice the output from the "System.out.println" on the server log.ScriptletsBy itself a scriptlet does not generate HTML.If a scriptlet wants to generate HTML, it can use a variable called "out".This variable does not need to be declared.It is already predefined for scriptlets, along with some other variables.The following example shows how the scriptlet can generate HTML output. <%//This scriptlet declares and initializes "date"System.out.println( "Evaluating date now" );java.util.Date date = new java.util.Date();%>ScriptletsHello!The time is now<%//This scriptlet generates HTML outputout.println( String.valueOf( date ));%> The JSP "request" variable is used to obtain information from the request as sent by the browser.For instance, you can find out the name of the client's host (if available, otherwise the IP address will be returned.)ScriptletsLet us modify the code as shown: <%//This scriptlet declares and initializes "date"System.out.println( "Evaluating date now" );java.util.Date date = new java.util.Date();%>Hello!The time is now<%out.println( date );out.println( "
Your machine's address is " );out.println( request.getRemoteHost());%> Mixing Scriptlets and HTMLWe have already seen how to use the "out" variable to generate HTML output from within a scriptlet.For more complicated HTML, using the out variable all the time loses some of the advantages of JSP programming.It is simpler to mix scriptlets and HTML. Suppose you have to generate a table in HTML.This is a common operation, and you may want to generate a table from a SQL table, or from the lines of a file.But to keep our example simple, we will generate a table containing the numbers from 1 to N.Not very useful, but it will show you the technique. Mixing Scriptlets and HTMLHere is the JSP fragment to do it:

<%for ( int i = 0; i < n; i++ ) {%><%}%>
Number<%= i+1 %>
You would have to supply an int variable "n" before it will work, and then it will output a simple table with "n" rows. Mixing Scriptlets and HTMLAnother example of mixing scriptlets and HTML is shown here it is assumed that there is a boolean variable named "hello" available.If you set it to true, you will see one output, if you set it to false, you will see another output. <%if ( hello ) {%>

Hello, world<%} else {%>

Goodbye, world<%}%> It is a little difficult to keep track of all open braces and scriptlet start and ends, but with a little practice and some good formatting discipline, you will acquire competence in doing it.JSP DirectivesWe have been fully qualifying the java.util.Date in the examples in the previoussections.Perhaps you wondered why we don't just import java.util.*; It is possible to use "import" statements in JSPs, but the syntax is a little different from normal Java.Try the following example: <%@page import="java.util.*" %><%System.out.println( "Evaluating date now" );Date date = new Date();%>Hello!The time is now <%= date %> JSP DirectivesThe first line in the above example is called a "directive".A JSP "directive" starts with <%@characters. This one is a "page directive".The page directive can contain the list of all imported packages.To import more than one item, separate the package names by commas, e.g. <%@page import="java.util.*,java.text.*" %> There are a number of JSP directives, besides the page directive.Besides the page directives, the other most useful directives are include and taglib.JSP DirectivesWe will be covering taglib separately. The include directive is used to physically include the contents of another file.The included file can be HTML or JSP or anything else --the result is as if the original JSP file actually contained the included text.To see this directive in action, create a new JSP Going to include hello.jsp...
<%@include file="hello.jsp" %> View this JSP in your browser, and you will see your original hello.jsp get included in the new JSP.JSP DeclarationsThe JSP you write turns into a class definition.All the scriptlets you write are placed inside a single method of this class. You can also add variable and method declarations to this class.You can then use these variables and methods from your scriptlets and expressions. To add a declaration, you must use the <%!and %>sequences to enclose your declarations, as shown below. <%@page import="java.util.*" %><%!Date theDate = new Date();Date getDate(){System.out.println( "In getDate() method" );return theDate;}%>Hello!The time is now <%= getDate() %> JSP DeclarationsThe example has been created a little contrived, to show variable and method declarations. Here we are declaring a Date variable theDate, and the method getDate.Both of these are available now in our scriptlets and expressions. But this example no longer works!The date will be the same, no matter how often you reload the page.This is because these are declarations, and will only be evaluated once when the page is loaded!(Just as if you were creating a class and had variable initialization declared in it.) JSP SessionsOn a typical web site, a visitor might visit several pages and perform several interactions. If you are programming the site, it is very helpful to be able to associate some data with each visitor.For this purpose, "session"s can be used in JSP. A session is an object associated with a visitor.Data can be put in the session and retrieved from it.A different set of data is kept for each visitor to the site. Here is a set of pages that put a user's name in the session, and display it elsewhere.Try out installing and using these. JSP SessionsFirst we have a form, let us call it GetName.html What's your name?

The target of the form is "SaveName.jsp", which saves the user's name in the session.Note the variable"session".JSP SessionsThis is another variable that is normally made available in JSPs, just like out and request variables.(In the @page directive, you can indicate that you do not need sessions, in which case the "session" variable will not be made available.) <%String name = request.getParameter( "username" );session.setAttribute( "theName", name );%>Continue The SaveName.jsp saves the user's name in the session, and puts a link to another page, NextPage.jsp. JSP SessionsNextPage.jsp shows how to retrieve the saved name. Hello, <%= session.getAttribute( "theName" ) %> If you bring up two different browsers (not different windows of the same browser), or run two browsers from two different machines, you can put one name in one browser and another name in another browser, and both names will be kept track of. The session is kept around until a timeout period.Then it is assumed the user is no longer visiting the site, and the session is discarded.Beans and Form processingForms are a very common method of interactions in web sites.JSP makes forms processing specially easy. The standard way of handling forms in JSP is to define a "bean".This is not a full Java bean.You just need to define a class that has a field corresponding to each field in the form.The class fields must have "setters" that match the names of the form fields.For instance, let us modify our GetName.html to also collect email address and age. Beans and Form processingThe new version of GetName.html is
What's your name?
What's your e-mail address?
What's your age?

To collect this data, we define a Java class with fields "username", "email" and "age" and we provide setter methods "setUsername", "setEmail" and "setAge", as shown.A "setter" method is just a method that starts with "set" followed by the name of the field.The first character of the field name is upper-cased.So if the field is "email", its "setter" method will be "setEmail".Beans and Form processingGetter methods are defined similarly, with "get" instead of "set".Note that the setters(and getters) must be public. package user;public class UserData {String username;String email;int age;public void setUsername( String value ){username = value;}public void setEmail( String value ){email = value;}public void setAge( int value ){age = value;}public String getUsername() { return username; }public String getEmail() { return email; }public int getAge() { return age; }} Beans and Form processingThe method names must be exactly as shown.Once you have defined the class, compile it and make sure it is available in the web-server's classpath.The server may also define special folders where you can place bean classes, e.g. with Blazix you can place them in the "classes" folder.If you have to change the classpath, the web-server would need to be stopped and restarted if it is already running.Note that we are using the package name user, therefore the file UserData.class must be placed in a folder named user under the classpath entry. Now let us change "SaveName.jsp" to use a bean to collect the data. Continue Beans and Form processingAll we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag!The useBean tag will look for an instance of the "user.UserData" in the session.If the instance is already there, it will update the old instance.Otherwise, it will create a new instance of user.UserData (the instance of the user.UserData is called a bean), and put it in the session. The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean!Let us modify NextPage.jsp to retrieve the data from bean.. You entered
Name: <%= user.getUsername() %>
Email: <%= user.getEmail() %>
Age: <%= user.getAge() %>
Beans and Form processingNotice that the same useBean tag is repeated.The bean is available as the variable named "user" of class "user.UserData".The data entered by the user is all collected in the bean. We do not actually need the "SaveName.jsp", the target of GetName.html could have been NextPage.jsp, and the data would still be available the same way as long as we added a jsp:setProperty tag.But in the next tutorial, we will actually use SaveName.jsp as an error handler that automatically forwards the request to NextPage.jsp, or asks the user to correct the erroneous data.

Description
Its the slide from Thapar varsity...and if one wants to start from beginning its the best one.

Comments

Want to learn?

Sign up and browse through relevant courses.

Name:
Your Email:
Password:
Country:
Contact no:


Area code Number
Subjects you are interested in:
Word verification: (Enter the text as in image)


Sign Up Already a member? Sign In
I agree to WizIQ's User Agreement & Privacy Policy
Gurditta Garg
Web Developer and learning Java dese dayz
User
4 Followers

Your Facebook Friends on WizIQ

Explore Similar Courses

Develop Android Apps with Java

Price:$300
$40

SAVE 86%

Give live classes, create & sell online courses

Try it free Plans & Pricing

Connect