Expressions and Data Types CSC 121 Fall 2016...
Transcript of Expressions and Data Types CSC 121 Fall 2016...
ExpressionsandDataTypesCSC121Fall2016
HowardRosenthal
LessonGoals� UnderstandthebasicconstructsofaJavaProgram� Understandhowtousebasicidentifiers� UnderstandsimpleJavadatatypesandtheoperationsonthosetypes
� Understandhowtowriteandevaluateexpressions� Understandtheconceptofcasting
2
public class Hello { public static void main ( String[] args ) { System.out.println("Hello World!"); } } • Above is a source program (source file) for a Java program. The purpose of this program is to type the characters Hello World! on the monitor.
• The file must be named Hello.java to match the name of the class. The upper and lower case characters of the file name are important. (So if the file is named hello.java with a small h it will not work). On all computers, upper and lower case inside the program are important.
• The first line class Hello says that this source program defines a class called Hello.
• A class is a section of a program. Small programs often consist of just one class. Most programs use multiple classes to create objects
• Some classes are are imported while other are created by the programmer
• Every class is contained within a set of braces • When the program is compiled, the compiler will make a file of bytecodes called Hello.class. - This is the file that the JVM uses.
KeyTermsandDefini/ons
3
KeyTermsandDefini/ons(2)• Methodsarebuiltoutofstatements.Thestatementsinamethodareplacedbetweenbraces{and}asinthisexample.
• Amethodisasectionofaclassthatperformsaspecifictask• Allprogramsstartexecutingfromthemainmethod• Eachmethodiscontainedwithinasetofbraces
� Braces� Foreveryleftbrace{thereisarightbrace}thatmatches.
� Usuallytherewillbesetsofmatchingbracesinsideothersetsofmatchingbraces.Thefirstbraceinaclass(aleftbrace)willmatchthelastbraceinthatclass(arightbrace).Abracecanmatchjustoneotherbrace.
� Useindentingtoshowhowthebracesmatch(andtherebyshowthelogicoftheprogram).Lookattheexample.� Increasetheindentingbythreespacesforstatementsinsidealeftandrightbrace.If
anotherpairofbracesisnestedwithinthosebraces,increasetheindentingforthestatementstheycontainbyanotherthreespaces.Lineupthebracesvertically.� WithNotepad++theindentlevelsforbothbracesandparenthesesarecolorcoded� Afteraleftbraceanindentwillbecreatedforyouautomatically� Makesurethatyoustepbacktoalignyourleftandrightbraces� Youcanalsoindentwhennecessarybyusingthetabkey
4
• Mostclassescontainmanymorelinesthanthisone.Everythingthatmakesupaclassisplacedbetweenthefirstbrace{anditsmatchinglastbrace}.
• Thenameoftheclass(andthereforethenameofthefile)isuptoyou.• Byconventionthefirstletterofaclassistypicallyuppercase.If
theclasshasacompoundnameeachwordinthenamestartswithauppercaseletteri.e.NumberAdder
• Asourcefilealwaysendwith.javainlowercase.• ThereforethefilenameisClassname.java
• Inprogramming,thenameforsomethinglikeaclass,amethodoravariableiscalledanidentifier.
• Anidentifierconsistsofalphabeticalcharactersanddigits,plusthetwocharacters'_'and'$'-underscoreanddollarsign
• Thefirstcharactermustbealphabetical,theremainingcharacterscanbemixedalphabeticcharactersanddigitsor_or$.
• Nospacesareallowedinsidethename.• Anexpressionisasequenceofsymbols(identifiers,operators,
constants,etc.)thatdenoteavalue3*(2*x+y)-6*z
KeyTermsandDefini/ons(3)
5
• Areservedwordisawordlikeclassthathasaspecialmeaningtothesystem.Forexample,classmeansthatadefinitionofaclassimmediatelyfollows.Youmustusereservedwordsonlyfortheirintendedpurpose.(Forexample,youcan'tusethewordclassforanyotherpurposethandefiningaclass.)Page250fthetextlistsreservedwords
• Astatementinaprogramminglanguageisacommandforthecomputertodosomething.Itislikeasentenceofthelanguage.
• AstatementinJavaisalwaysfollowedbyasemicolon.• Agroupofstatementswithinasetofbracesiscalledablock
• Wewilllearnthateachblockleveldefinesascopeforthevariablesdefinedwithinthatscope
• Thepart"HelloWorld!"iscalledaString.AStringisasequenceofcharacters.ThisprogramwritesaStringtothemonitorandthenstops.
KeyTermsandDefini/ons(4)
6
ReservedKeywordsInJava
7
abstract assert boolean break byte case
catch char class const* continue default
double do else enum extends false
final finally float for goto* if
implements import instanceof int interface long
native new null package private protected
public return short static strictfp super
switch synchronized this throw throws transient
true try void volatile while
The table below lists all the words that are reserved Java. Words in red are those that we will be using this semester
*Even though goto and const are no longer used in the Java programming language, they still cannot be used.
Comments
� Asinglelinecommentbeginswith//� This//cancomeatthebeginningofthelineorafterastatementontheline:
System.out.println("Onawitheredbranch");//Writefirstlineofthepoem
� Multilinecommentsbegin/*andend*//*Program1Writeoutthreelinesofapoem.Thepoemdescribesasinglemomentintime,using17syllables.*/
� Itisagoodideatofullycommentyourprogram� Thisincludesdefiningthelogic,anddefiningyourvariables
8
DataTypesandOperators� Adatatypeisasetofvaluestogetherwithanassociatedsetofoperatorsformanipulatingthosevalues.� Whocanthinkofsomebasicdatatypesinthenumericalworld?Thelogicalworld?
� Whenanidentifierisusedasavariableitalwayshasadefineddatatype
� Themeaningofthe0’sand1’sinthecomputerdependsonthedatatypebeingrepresented
� Wewillbeginbydefiningtheeightprimitivedatatypes� byte,short,int,long,float,double,charandboolean–alllowercase
9
DataTypesandOperators(2)� AlldatainJavafallsintooneoftwocategories:primitivedataand
classeswhichareusedtoinstantiateobjects.� Thereareonlyeightprimitivedatatypes-byte,short,int,long,
float,double,char,andboolean.� Referencevariablescontainmemoryaddressesthatrefertoobjects� However,Javahasmanydifferentclasses,andyoucaninventasmany
othersasyouneed.� Anydatatypeyouinventwillbeacreatedasaclassandinstantiatedasan
object.� Muchmorewillbesaidaboutobjectsinfuturechapters(sinceJavais
aobjectorientedprogramminglanguage).Thefollowingisallyouneedtoknow,fornow:� Aprimitivedatavalueusesasmall,fixednumberofbytes.� Thereareonlyeightprimitivedatatypes.� Aprogrammercannotcreatenewprimitivedatatypes.
10
SomeNotesonObjects� Anobjectisabigblockofdata.Anobjectmayusemanybytesof
memory.� Anobjectusuallyconsistsofmanyinternalpieces.� Thedatatypeofanobjectiscalleditsclass.� ManyclassesarealreadydefinedinJava.� Aprogrammercaninventnewclassestomeettheparticularneedsof
aprogram.� Wecreateclassesandaccessthemethodsofthoseclasses
� Someclasseshavestaticmethodsandcanbeaccessedwithoutcreatingnewobjects
� Wewillseethedifferencesaswemoveahead
11
Primi/veNumericDataTypes(1)� NumbersaresoimportantinJavathat6ofthe8primitivedatatypesarenumerictypes.
� Therearebothintegerandfloatingpointprimitivetypes.
� Thereare4integerdatatypes� byte–asinglebyteusedforsmallintegers� short–twobytes� int–4bytes–allconstantintegersareassumedtobeoftypeint
� long–8bytes–useforverylargenumber
12
Primi/veNumericDataTypes(2)� Therearetwodatatypesthatareusedforfloatingpointnumber
� float-4bytes� double-8bytes–thisisthedefaultforallfloatingconstantsandisusedin
almostallcasesforfloatingpointarithmetic� Floatingpointnumbers,unlikeintegers,arenotalwaysprecise.
� Ifyoucomparefloatingpointnumbersyoucangeterrorsorunexpectedresultswhenexecutingduetothewaythattheyarerepresentedinthecomputer
� Duetothislackofperfectprecisionweusuallyprefertousedoubleoverfloatforrealnumbersthataren’tintegers,sincetheprecisionisgreater,althoughstillnotperfect.� Aswewillseeshortly,therearecastingissueswhenyoumixnumbers,
especiallywithfloatingpointnumbers� Javahasadvancedmethodsusingobjectstocalculatenumbersevenmore
precisely� ThisclasscalledBigDecimalisusedforveryprecisemonetaryandscientific
calculations� Inthetables,Emeans"tentothepowerof".So3.5E38means3.5x1038
13
Primi/veNumericDataTypes(3)
� Thereisafundamentaldifferencebetweenthetherepresentationsofintegersandfloatingpointnumbersinthecomputer.� Integertypeshavenofractionalpart;floatingpointtypeshaveafractionalpart.
� Onpaper,integershavenodecimalpoint,andfloatingpointtypesdo.Butinmainmemory,therearenodecimalpoints:evenfloatingpointvaluesarerepresentedwithbitpatterns.
14
Primi/veNumericDataTypes(4)� Eachprimitivetypeusesafixednumberofbytes.Thismeansthatifyouareusingaparticulardatatypethenthesamenumberofbyteswillbeusednomatterwhatvalueisrepresented.� Forexample,allvaluesrepresentedusingtheshortdatatypeuse2
bytes(16bits).Thevaluezero(asashort)uses2bytesandthevaluethirtythousanduses2bytes.
� Allvaluesrepresentedusingthelongdatatypeuse8bytes(64bits).Thevaluezero(asalong)uses8bytes,thevaluethirtythousanduses8bytes,andthevalueeighttrillionuses8bytes.
� Valuesthatarelargeinmagnitude(negativeorpositive)needmorebitstoberepresented.Thisissimilartowritingoutnumbersonpaper:largenumbersneedmoredigits.Ifavalueneedsmorebitsthanaparticulardatatypeuses,thenitcannotberepresentedusingthatdatatype.
15
SummaryofPrimiJveNumericDataTypesInteger Primitive Data Types Type Size Range byte 1 byte (8 bits) -128 to +127 short 2 bytes (16 bits) -32,768 to +32,767
int 4 bytes (32 bits) -2 billion to +2 billion (approximately)
long 8 bytes (64 bits) -9E18 to +9E18 (approximately)
Floating Point Primitive Data Types Type Size Range float 4 bytes (32 bits) -3.4E38 to +3.4E38 double 8 bytes (64 bits) -1.7E308 to 1.7E308
Remember:Integerdatatypesreservetheleftmostbittoindicatepositive(0)ornegative(1)intwo’scomplementformat
16
Inthetables,Emeans"tentothepowerof".So3.5E38means3.5x1038
NumericOperators(1)
Operator Meaning Precedence
- unaryminus highest
+ unaryplus highest
* multiplication middle
/ division middle
% remainder/modulus middle
+ addition low
- subtraction low
17
Precedenceofoperatorscantaketheplaceofparentheses,butjustasinalgebra,youshoulduseparenthesesforclarity.Wheretherearenoparenthesesandequalprecedenceevaluationisfromlefttoright
NumericOperators(2)� Alloftheseoperatorscanbeusedonfloatingpointnumbersandonintegernumbers.� The%operatorisrarelyusedonfloatingpoint.(wewon’tbeusingit,buttheremainderconceptwouldbesimilar)
� Whenmixingfloatingpointnumbersandintegernumbers,floatingpointtakesprecedence–thisiscalledcasting
� Anintegeroperationisalwaysdonewith32bitsormore.Ifoneorbothoperandis64bits(datatypelong)thentheoperationisdonewith64bits.Otherwisetheoperationisdonewith32bits,evenifbothoperandsaresmallerthan32bits.� Forexample,with16bitshortvariables,thearithmeticisdoneusing32bits:
18
IntegerArithmeJc� Inintegerarithmeticyoualwaystruncate
� 7/2 = 3 � 11/4 = 2
� Themodulusoperatorgivesyoutheremainder� 7%4 = 3 � 9%2=?� Anyideasonwherethe%canbehelpful?� Note:InJavathesignoftheresultofa%bisalwaysthesignofa(thedividend).
19
CasJng� Javaisahighlytypesensitivelanguage� WhenevaluatinganyexpressionwithoperandsofdifferenttypesJava
firstpromotesorcaststheoperandofthe“smaller”datatype� Bysmallerwemeantherange� byteissmallerthanshortwhichissmallerthanintwhichissmaller
thanlongwhichissmallerthanfloatwhichissmallerthandouble� booleanexpressionsarenevercast� charautomaticallycastsuptoint,nottoshort
� Youcanonlycastdownwardsexplicitly,otherwiseyoumaycreateanerror
� Example:inta=10;shortb=5;a=b;Thisiscastingupwards–itisimplicitandautomaticb=(short)(a);Thisiscastingdownwards–mustbeexplicit
20
MixingNumericDataTypes(1)� Ifbothoperandsareintegers,thentheoperationisanintegeroperation.Ifanyoperandisdouble,thentheoperationisdouble.7.1+7.4 = 14.5 � 7.0+7.4 = 14.4 � 7+7.4 = 14.4 � (15/2) +7.4 = ? � (15%2) + 7.4 = ?
� Thenumbersare“casted”upwards� Thisbecomesmoreimportantinthenextchapterwhenwelearnabouttypingvariables
� Note: Unless otherwise declared all decimals are assumed to be of type double
21
MixingNumericDataTypes(2)� Rememberthatwithoutparenthesesyoufollowthehierarchy� Mixedinteger/decimaladditioniscasttodecimalwhenthemixing
occurs(10.0+5)=15.010/4*(18.0)=36.0(5/9)*(212.0-32.0)=0.0
� Note:Integerscanbeoftypebyte,short,int,long,butdefaulttointHoweveryoucandirectlyassignaninttoashortorbytevariable(ifitfitswiththerange)shortb=5;works
� Decimalcanbeoftypedoubleorfloat,butdefaulttodoubleExample:floatz;z=2.0+3.0;thiscreatesanerror–Why?Javadoesn’tallowthedoubletocastdownbecauseofprecisionissuesz=(float)(2.0+3.0);-Thisiscorrect–weexplicitlycastdown.
22
Typeboolean� Typebooleanidentifierscanhaveonlyoneoftwovalues–trueorfalse.(1or0)� Abooleanvaluetakesupasinglebyte.
� Therearethreeoperators� &&-meansand–bothoperandsmustbetrueforthevalueoftheexpressiontobetrue
� ||-meansor–oneoftheoperandsmustbetrueforthevalueoftheexpressiontobetrue
� !-meansnot
p q p&&q (and) p||q (or) !p (not) true true true true false true false false true false false true false true true false false false false true
23
Typeboolean–ShortCircuiJng� Therearealsobooleanoperators&and|� What’sthedifference?
� Whenyouuse&&or||thecompilerismoreefficient,itcanshort-circuitwhennecessary
� Thismeansthatonceitdeterminesifastatementistrueorfalseitstopsevaluatingi.e.:
(true||false)||false–itisevaluatedtrueafterthefirst||isevaluated(true&&false)&&true–sameidea,butevaluatesasfalseafterfirst&&
� Sowhenisthereaproblem:� Ifyoutrytoassignalogicalvalue(allowed,thismightnottakeplaceifthere
isshortcircuiting:� (true||false)||(a=true)–adoesn’tgetassignedthevaluetrue(a=true)is
allowedastheexpressionevaluatesastrue� (true|false)|(a=true)–adoesgetassignedthevaluetrue
� Don’tusethesetypesofassignmentstatementsinsideofbooleanstatements–itwillinevitablyleadtoerrors
24
SwitchesandBooleanLogic
25
XA BY
TogetfromAtoBbothXandYmustbeclosed–X&&Y
A B
X
Y
TogetfromAtoBeitherXorYmustbeclosed–X||Y
A
A
RelaJonalOperatorsOperator Description Example (with A=2, B=5
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.
� Theresultofapplyingarelationaloperatorisatrueorfalsevalue
26
OperatorHierarchyPriority Operators Operation Associativity
1 [] arrayindex
left () methodcall . memberaccess
2
++ pre-orpostfixincrement
right
-- pre-orpostfixdecrement +- unaryplus,minus ~ bitwiseNOT ! boolean(logical)NOT (type) typecast new objectcreation
3 */% multiplication,division,remainder left
4 +- addition,subtraction left + Stringconcatenation
5 << signedbitshiftleft
left >> signedbitshiftright >>> unsignedbitshiftright
6 <<= lessthan,lessthanorequalto
left >>= greaterthan,greaterthanorequalto instanceof referencetest
7 == equalto left != notequalto
8 & bitwiseAND left & boolean(logical)AND
9 ^ bitwiseXOR left ^ boolean(logical)XOR
10 | bitwiseOR left | boolean(logical)OR 11 && boolean(logical)AND left 12 || boolean(logical)OR left 13 ?: conditional right
14
= assignment
right
*=/=+=-=%=<<=>>=>>>=&=^=|=
combinatedassignment
• Thehierarchyisverysimilartowhatyouknowfromalgebra
• Whenthereisanequivalenthierarchylevelandnoparenthesesyouevaluatefromlefttoright
• Whenindoubtuseparentheses
27
SomeExtraExamples� 5>4 – true � 4>5 – false � (5>4) || (4>5) - ? � (5>4) && (4>5) - ?
28
AnotherExampleEvaluateastrueorfalsetrue || false && 3 < 4 || !(5==7) (true || (false && (3 < 4))) || !(5==7) – putting in the parentheses correctly always helps (true||(false&&true))||!false(true||false)||truetrue||truetrue
29
Typechar� Typecharisthesetofallcharactersfoundonthestandardkeyboard,and
thousandsofothercharactersaswell.� charisaprimitivedatatype� Typecharisdenotedusingsinglequotes� ‘A’,‘5’� JavausesUnicode–2byterepresentationsthatincreasesthenumberof
charactersthatcanberepresentedfrom255to65536uniquecharacters� Note:KeyboardlettersinASCIICodeandUnicodehavethesamevalue–i.e.‘A’=65
ie01000001inASCIIor0000000001000001inUnicode� Youcanaddandsubtracttypechar–theyareactuallytreatedlikeintegers
whenadding� i.e.‘A’+1 = 660r0000000001000010 - char would automatically cast up to int
� You could cast back down to char by saying (char)(66) which yields ‘B’ � They are added as type int – 4bytes – to accommodate all Unicode characters
� The most common characters and their Unicode values are found in Appendix B � You can also compare type char values – they compare based on their ASCII value
� ‘A’ < ‘B’ – true
30
String� StringisaclassinJavawithlotsofdifferentmethodsthatallowsyoutomanipulate
them� AnindividualStringisanobject,notabasicdatatype.� AStringisasequenceofcharactersenclosedindoublequotes
� JavaprovidesaStringclassandwecancreateStringobjects� WhydoesStringhaveacapitalSwhileprimitivedatatypeshavelowercasefirstletters–
Stringisthenameofaclass� Stringscanbeconcatenated
� “Iam”+“aman”=“Iamaman”� Stringsandvalues
� Everythingdependsontheorder� “Thesumoftwonumbersis”+ (5*2) prints as The sum of two numbers is 10 Why? You always work from inside the parentheses outwards � However (“The sum of two numbers is 5”) + 2 prints as The sum of two numbers is 52
� In Chapter 9 we do a lot more with String objects
31
Cas/ngWithStringsandCharacters‘A’+‘B’=131(integer)‘A’+“B”=AB(String)“A”+“B”=AB(String)“”+‘A’+‘B’=AB(String)–‘A’getscasttoString‘A’+‘B’+“”=131(String)3+4+“”=7(String)“”+3+4=34(String)Keyisthatwithoutparentheseswearereadinglefttoright
32
PrinJngandSpecialCharacters� TheSystem.outobjectispredefinedandisincludedwiththebasic
java.langandthereforeisalwaysavailableforuse.� Itiscalledthestandardoutputobject,andprintstotheterminal� WewilllearnhowtoprinttootherFileobjectslaterinthisterm
� Wewillbeusingtwobasicstaticmethodsfromthisclass� System.out.println(“abc”)//printstheStringandacharacterreturn� System.out.print(“abc”)//printsaStringwithoutacharacterreturn
� EscapesequencesinsidetheStringcanbeusedtocontrolprinting
EscapeSequence Character
\n newline
\t tab
\b backspace
\f formfeed
\r return
\" "(doublequote)
\' '(singlequote)
\\ \(backslash)
\uDDDD characterfromtheUnicodecharacterset(DDDDisfourhexdigits)–usedwhenthecharacterisn’tavailableduringinput
33
PrinJngExamplepublicclassPrintAPoem{publicstaticvoidmain(String[]args){System.out.println(“Hewrotehiscode”);System.out.print(“\tHeindentedwell\n”);
System.out.println(“\tTillhewasdone”);System.out.print(“\nTheAuthor\n”);}}Hewrotehiscode
HeindentedwellTillhewasdone
TheAuthor
34
System.out.println(concatenatedString)–printsandgoestothenextlineSystem.out.print(concatenatedString)–printsandstaysonthesameline
PrinJngExample–ConcatenaJoninPrintStatements� WhenyouwriteexpressionsinaSystem.out.println()statementtheexpressionmayormaynotbecalculatedfirst,dependingonifandwhereyouputtheparentheses� Therulesareexactlythesameasusedwhenconcatenating
String(s)� UltimatelytheprintlnmethodwilloutputasingleString
publicclassPrintingNumbers//Classname{
publicstaticvoidmain(String[]args){ System.out.println("Thesumof5+6is"+(5+6));
System.out.println("Thesumof5+6is"+5+6); System.out.println("Thesumof"+5+"+"+6+"is"+(5+6));}}
35
ProgrammingExercise-Class(1)Modifythefollowingprogramsothatit’soutputis:WelcomeToJavaProgrammingpublicclassWelcome1{
publicstaticvoidmain(String[]args){ System.out.println(“WelcomeToJavaProgramming”);}
}
36
ProgrammingExercise-Class(2)Exercise6.TriangleWriteaprogramthatprintsthetriangle:*********************Usethisframework:public class Pname //Class name { public static void main ( String[] args ) //main method header { Code goes here //Body } } CompilewithjavacPname.javaExecutewithjavaPnameonceyoucompilesuccessfully
37
ProgrammingExercise-Lab(1)Exercise7.TriangleWithInitialsWriteaprogramthatprintsthetriangle:****H***G****R*******
38
ProgrammingExercise-Lab(2)Exercise2.UptimeTheuptimecommandoftheUNIXoperatingsystemdisplaysthenumberofdays,hoursandminutessincetheoperatingsystemwasstarted.ForexampletheUNIXcommanduptimemightreturnthestringUp53days12:39.Writeaprogramthatconvertsthe53days,12hoursand39minutestothenumberofsecondsthathaveelapsedsincetheoperatingsincewaslaststarted.
39