a guide in csjv101 - mr. ap's website · a guide in csjv101/apcs saudi aramco college...

15
A Guide in CSJV101 II. Introduction to Java Applications I. Introduction II. Printing a Line of Text using print and printf III. Memory Concepts, Adding Integers, and Arithmetic IV. Decision Making: Equality and Relational Operators

Upload: others

Post on 16-Jan-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101

II. IntroductiontoJavaApplications

I. IntroductionII. PrintingaLineofTextusing

print andprintf III. MemoryConcepts,Adding

Integers,andArithmeticIV. DecisionMaking:Equalityand

RelationalOperators

Page 2: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page2of15©2012©2012

ChapterII–IntroductiontoJavaApplications

I. Introduction

Inthischapter,thestudentswilllearnhowtocreateasimpleJavaprogram.Asshownin

Program2.1,aJavaprogramconsistsofdifferentpartsasexplainedbelow.

Program2.1|TheprogramsimplyoutputsthemessageWelcometoJavatothescreen.

• Comments

Beingagoodprogrammer,youhavetothinknotjustyourselfbutotherprogrammersaswell.Oneofthemanythingsyoucandoisbywritingcommentsinyourprograms.Sowhateverhappens(e.g.leavingyourjobandsomebodyhastoreplaceyou),yourprogramscanberead,understood,andcontinuedbyotherprogrammers.

Good Programming Practice 2.1

Ideally,alwaysbeginyourprogramwithacommentthatdescribesthepurposeoftheprogram,author,date,andtime.

Page 3: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page3of15©2012©2012

TypesofComments:

1. Single-Line(// text)// This program displays a line of text

2. Multiple-Line(/*text*/)

• SometimesthecommentistoolongtofitinonelinesoitiswritteninseverallinesforreadabilitylikewhatisshowninFigure2.1.

Figure2.1|Multiple-Linecomment.

3. Documentation(/**documentation*/)http://java.sun.com/docs/codeconv/html/CodeConventions.doc4.html

• Doccomments(alsoknowninformallyasJavadoccomments)documentyourAPIsforotherprogrammerswhouseyourclassesandformaintenanceprogrammers.

• Doccommentsstandardizethewaysourcecodeisdocumented.• DoccommentscanbeextractedtoHTMLfilesusingthejavadoctool.• RefertoFigure2.2foranexample.

Figure2.2|Documentationcomment.

Page 4: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page4of15©2012©2012

• Classdeclaration

Figure2.3illustrateshowaclassisdeclaredanddefineseachdeclarationpart.

Figure2.3|Classdeclaration.

• JavaNamingConvention

AprogrammershouldfollowtheJavanamingconvention.Aclassname(i.e.identifier)shouldstartwithaletter.

Byconvention,aclassnamestartswithacapitalletterandcapitalizethefirstletterofthesucceedingwords(e.g.WelcomeToJava).Eachclassnamemaycontaindigits,underscores(_)anddollarsigns($)butmaynotstartwithadigitandmaynotcontainspaces.

ValidIdentifiers InvalidIdentifiersSampleClass 1Sample$ThisIsOkay ThisIsNotOkay

_Fine1

Table2.1|Samplevalidandinvalidclassnames(i.e.identifiers).

Thebodyofanyclass(i.e.insidecurlybraces)canhaveoneormoremethods.InChapter4,methodswillbeexplainedcomprehensively.

Error Prevention Tip 2.1

Alwaysnameyourclassafterthenameofthefile.

Page 5: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page5of15©2012©2012

• main()methoddeclaration

Figure2.4illustrateshowamethod,specificallythemain()methodisdeclaredanddefineseachdeclarationpart.

Figure2.4|main() methoddeclaration.

• Javastatement

Thebodyofamethod(i.e.insidethecurlybraces)housesoneormorestatementswhichFigure2.5illustrates.Alwaysterminateeachstatementwithasemicolon.

Figure2.5|AJavastatementthatprintsthestring WelcometoJava.

Page 6: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page6of15©2012©2012

Hereiswhatitmeans.

InsidetheSystemclassisthedeclarationofoutvariablethatlookslike:

andinsidethePrinstreamclassisadeclarationofprintln()methodthathasamethodsignaturethatlookslike:

PrintStreamclassisabuilt-inclasswhichcontainsmethodstoprintthedifferentdatavalues.

Figure2.6andTable2.2shownbelowillustratehowSystemandPrintStream classesarewrittenandhowtheyareusedwithprint()orprintln()method.

Figure2.6|ItshowshowSystemandPrintStreamworkstogetherwithprint()orprintln()method.(http://stackoverflow.com/questions/3406703/whats-the-meaning-of-system-out-println-in-java)

System

• Declaredas public final class System • Itisabuilt-inclasspresentinjava.langpackageandmayormay

nothaveafinal(i.e.whichmeansthat,itcannotbeinheritedbyotherclasses)modifier.

• Itcontainspre-definedmethodsandfields,whichprovidesfacilitieslikestandardinput,output,etc.

out

• Itisastaticfinalfield(i.e.variable)inSystemclasswhichisoftypePrintStream.

• staticfieldsandmethodsmustbeaccessedbyusingtheclassnamelikeSystem.out.

• ItdenotesthereferencevariableofthetypePrintStreamclass.print or println() • ItisapublicmethodinPrintStreamclasstoprintthedatavalues.

Table2.2|ItexplainshowSystem.out.printstatementworks.(Part1of2)

Ø HencetoaccessamethodinPrintStreamclass,weuseout.println()(asnon-staticmethodsandfieldscanonlybeaccessedbyusingthereferencevariable).http://www.chetanasforum.com/index.php?showtopic=463

Page 7: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page7of15©2012©2012

• EscapeSequences

Program2.2illustrateshowtodisplaymultiplelinesoftextwithasinglestatement.Thiscanbedonebyusinganescapecharacterbackslash(\).ItspecifiestoSystem.out.print()orprintln()methodthataspecialcharacteristobeoutput.

Escapecharacterisusedsoitformsanescapesequence.Program2.2usesescapesequence\nwhichsignifiesnewlinecharacterandTable2.3illustratessomecommonescapesequences.

Program2.2|Theprogramdisplaysmultiplelinesoftextwithasinglestatement.

EscapeSequence Description

\n Newline.Positionthescreencursoratthebeginningofthenextline.\t Horizontaltab.Movethescreencursortothenexttabstop.

\r Carriagereturn.Positionthescreencursoratthebeginningofthecurrentline–donotadvancetothenextline.Anycharactersoutputafterthecarriagereturnoverwritethecharacterspreviouslyoutputonthatline.

\\ Backslash.Usedtoprintabackslashcharacter.\” Doublequote.Usedtoprintadouble-quotecharacter.

Table2.3|Somecommonescapesequences.(JavaHowToProgram,8thEdition,DeitelandDeitel,page46)

• FormatSpecifier(%)

Amoreconvenientmethodusedtowriteaformattedstringisprintf().Thefinprintf()means“formatted”.ThismethodhastwoargumentsnamelyformatofdatatypeStringandargumentsofdatatypeObject.

Page 8: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page8of15©2012©2012

Program2.3showshowprintf()methodisused.

Program2.3|Theprogramillustratestheuseofprintf()method.

Line11callsmethodSystem.out.printf()todisplaytheprogram’soutput.Themethodcallhastwoargumentsandseparatedwithacomma(,)–knownascomma-separatedlist.

Theprintf()method’sfirstargumentisaformatstring,inthiscase,consistsoffixedtextandthesecondargumentisaformatspecifier(i.e.%s).Theprintf()methodsubstitutesthevalue“College Preparatory Center”forthe%s.RefertoTable2.4forsomeformatspecifiers.

Table2.4|FormatSpecifiers

Page 9: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page9of15©2012©2012

II. MemoryConcepts,AddingIntegers,andArithmetic

Program2.1illustrateshowtodisplayamessageonthescreen;nocalculationandnohumaninteractionbetweenthecomputerandtheuser.InProgram2.4,simplearithmeticcalculationisshownandthreevariablessuchasno1,no2,andsumaredeclaredandinitialized.

Program2.4|Theprogramcalculatesthesumofthetwointegersandillustratesvariabledeclarationandinitialization.

Variablesarecomputermemoryspaces.Theyholddatawhichthecomputerprocesses.Eachmemorylocationmustbenamedandinprogrammingitiscalledidentifier(i.e.variablename).

IdentifierNamingConvention

Liketheclassname,namingtheidentifiermustbedonebyconvention.Therearesomerulestofollowasexplainedbelow.

• Itmaystartwithaletter,$,orunderscore(_)andmayhaveanumberinbetween(e.g.no1,_week1,and$tudentNo).

• Itcanhavemorethanonewordbutthefirstletterofthesucceedingwordsstartswithacapitalletter(e.g.firstName,wkSalary,andnetSales).

• Nospacesinbetween.• Thenameshouldsignifywhatthevalueofthevariablerepresents.

VariableDataTypes

Javaisreferredtoasastronglytypedlanguagesimplybecauseitrequiresallvariablestohaveatype.BeforeavariableisusedinaprogramlikeinProgram2.4,lines12-14,ithastobedeclaredsothecompilerwouldknowwhattypeofvalueisstoredinthememory.AvariabledatatypecouldbePrimitiveorNon-Primitive(i.e.Reference).

Page 10: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page10of15©2012

III. PrimitiveDataTypes

Avariableofprimitivedatatypecanholdonlyonevalueatatimewhileavariableofreferencedatatypecanholdoneormorevaluesatsametime.Referencedatatypewillbediscussedlater.Inthemeantime,wefocusontheprimitivedatatypes.

8PrimitiveTypes

1. int2. byte3. short4. long5. float6. double7. char8. boolean

Toknowmoreabouttheaforementioneddatatypes,lookatAppendixDofJavaHowToProgram8thEditionbookofDeitelandDeitelorvisithttp://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

IV. ArithmeticExpressions

• OperatorPrecedence

Line16inProgram2.4,asimplearithmeticexpressionwhichcontainsadditionisshown.Onearithmeticexpressionmaycontainseveralarithmeticoperationsandtherulesofprecedencemustbefollowed.Table2.5illustratessomeoperatorprecedence.

Key Concept 2.1

AnintcanbeassignedtoadoubleBUTadoublecannotbeassignedtoanint.Therewouldbealossofinformation.

Error Prevention Tip 2.2

Declarethevariablefirstbeforeusingitintheprogram.

Page 11: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page11of15©2012

RulesofOperatorPrecedence1

Operators Operations OrderofEvaluation(Precedence)

()

* /

%

ParenthesisMultiplicationDivisionRemainder

Evaluatedfirst.Ifthereareseveraloperatorsofthistype,theyareevaluatedfromlefttoright.

+

- AdditionSubtraction

Evaluatednext.Ifthereareseveraloperatorsofthistype,theyareevaluatedfromlefttoright.

= Assignment Evaluatedlast.

Table2.5|Precedenceofarithmeticoperators.(JavaHowToProgram,8thEdition,DeitelandDeitel,page54)

Considersomeexpressionsbelowjusttounderstandtherulesofoperatorprecedencemore.

𝑧 = 5 + 4 − 2

12

𝑧 = (5 + 4 − 2)/12

Theadditionoperationisenclosedinparenthesesbecauseitshouldbeprocessedfirstbeforethedivisionoperation.

• IntegerandFloating-PointDivisionOperations

Thereisasimilaritybetweenintegerandfloating-pointdivisionoperations,i.e.bothyieldquotient.Butthedifferenceisthatintegerdivisionyieldstheintegerpartofthenumericvalueandthefloating-pointdivisionyieldsfloating-pointvalue.Doesitmakesensetoyou?

Foryoutounderstandmoreaboutthedifference,considerProgram2.5shownbelow.

1TheOperatorPrecedenceChartcanbefoundinJavaHowToProgram8thEdition,DeitelandDeitel,AppendixA,page1411.

AlgebraicExpression

JavaEquivalent

Page 12: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page12of15©2012

Program2.5|Theprogramperformsintegerdivision.

Figure2.7|OutputofProgram2.5.

LookingatFigure2.7,Program2.5gives0.0asthequotient.0because1dividedby3yields0and.0appearsbecausethevariablequoisofdatatypedouble.

NowconsiderProgram2.6shownbelow.

Page 13: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page13of15©2012

Program2.6|Theprogramperformsfloating-pointdivision.

Figure2.8|OutputofProgram2.6.

Sinceno1andno2aredeclaredasdouble,theprogramarrivestoafloating-pointvalueof0.5.

V. DecisionMaking:EqualityandRelationalOperators

AsexplainedinChapterI,acomputerhasdecisionmechanismsthatallowthecomputertocompareitemsfromthememoryunittodeterminewhethertheyareequal.Andtodoso,Java’sifselectionstatementisused.

ifselectionallowsaprogramtomakeadecisionbasedonacondition’svalue.Aconditionisanexpressionthatcanbetrueorfalse.2

ifstatementscanbeformedbyusingtheequality(==and!=)andrelational(>,<,>=,and<=)operators.RefertoProgram2.7forsomeifstatementexamples.

2JavaHowToProgram,7thEdition,DeitelandDeitel,page56.

Page 14: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page14of15©2012

Program2.7|Theprogramcomparesintegersusingifstatements,equalityandrelationaloperators.

Page 15: A Guide in CSJV101 - Mr. AP's Website · A Guide in CSJV101/APCS Saudi Aramco College Preparatory Program Prepared by: Anselmo A. Pronuevo, Jr. Page 5 of 15 ©2012 • main() method

AGuideinCSJV101/APCS SaudiAramco CollegePreparatoryProgram

Preparedby:AnselmoA.Pronuevo,Jr. Page15of15©2012

Figure2.9|DifferentoutputsofProgram2.7basedondifferentsetsofinputs.

InProgram2.7,therearesixifstatementstosatisfythesixoutputpossibilitiesthetwointegervaluesmighthave.Andbasedonthedifferentconditions,thecomputerknowswhattooutputonthescreen.

Error Prevention Tip 2.3

Toavoidlogicerroratexecutiontime,donotputsemicolonattheendofthefirstlineofeachifstatement.

Error Prevention Tip 2.4

Donotconfuseassignmentoperator(=)withequalityoperator(==).Assignmentoperator(=)isusedtogivethevalueontherightsideoftheequationtotheleftsideoftheequation.

e.g. 𝑥 = 4;Theequationabovemeansthat4isassignedtothevariable𝑥.Itisreadas“getsthevalueof”whiletheequalityoperator(==)isusedtocomparetwovaluesiftheyareequalandisreadas“isequalto”.