expressions and data types csc 121 fall 2016...
TRANSCRIPT
![Page 1: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/1.jpg)
ExpressionsandDataTypesCSC121Fall2016
HowardRosenthal
![Page 2: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/2.jpg)
LessonGoals� UnderstandthebasicconstructsofaJavaProgram� Understandhowtousebasicidentifiers� UnderstandsimpleJavadatatypesandtheoperationsonthosetypes
� Understandhowtowriteandevaluateexpressions� Understandtheconceptofcasting
2
![Page 3: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/3.jpg)
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
![Page 4: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/4.jpg)
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
![Page 5: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/5.jpg)
• 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
![Page 6: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/6.jpg)
• Areservedwordisawordlikeclassthathasaspecialmeaningtothesystem.Forexample,classmeansthatadefinitionofaclassimmediatelyfollows.Youmustusereservedwordsonlyfortheirintendedpurpose.(Forexample,youcan'tusethewordclassforanyotherpurposethandefiningaclass.)Page250fthetextlistsreservedwords
• Astatementinaprogramminglanguageisacommandforthecomputertodosomething.Itislikeasentenceofthelanguage.
• AstatementinJavaisalwaysfollowedbyasemicolon.• Agroupofstatementswithinasetofbracesiscalledablock
• Wewilllearnthateachblockleveldefinesascopeforthevariablesdefinedwithinthatscope
• Thepart"HelloWorld!"iscalledaString.AStringisasequenceofcharacters.ThisprogramwritesaStringtothemonitorandthenstops.
KeyTermsandDefini/ons(4)
6
![Page 7: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/7.jpg)
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.
![Page 8: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/8.jpg)
Comments
� Asinglelinecommentbeginswith//� This//cancomeatthebeginningofthelineorafterastatementontheline:
System.out.println("Onawitheredbranch");//Writefirstlineofthepoem
� Multilinecommentsbegin/*andend*//*Program1Writeoutthreelinesofapoem.Thepoemdescribesasinglemomentintime,using17syllables.*/
� Itisagoodideatofullycommentyourprogram� Thisincludesdefiningthelogic,anddefiningyourvariables
8
![Page 9: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/9.jpg)
DataTypesandOperators� Adatatypeisasetofvaluestogetherwithanassociatedsetofoperatorsformanipulatingthosevalues.� Whocanthinkofsomebasicdatatypesinthenumericalworld?Thelogicalworld?
� Whenanidentifierisusedasavariableitalwayshasadefineddatatype
� Themeaningofthe0’sand1’sinthecomputerdependsonthedatatypebeingrepresented
� Wewillbeginbydefiningtheeightprimitivedatatypes� byte,short,int,long,float,double,charandboolean–alllowercase
9
![Page 10: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/10.jpg)
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
![Page 11: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/11.jpg)
SomeNotesonObjects� Anobjectisabigblockofdata.Anobjectmayusemanybytesof
memory.� Anobjectusuallyconsistsofmanyinternalpieces.� Thedatatypeofanobjectiscalleditsclass.� ManyclassesarealreadydefinedinJava.� Aprogrammercaninventnewclassestomeettheparticularneedsof
aprogram.� Wecreateclassesandaccessthemethodsofthoseclasses
� Someclasseshavestaticmethodsandcanbeaccessedwithoutcreatingnewobjects
� Wewillseethedifferencesaswemoveahead
11
![Page 12: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/12.jpg)
Primi/veNumericDataTypes(1)� NumbersaresoimportantinJavathat6ofthe8primitivedatatypesarenumerictypes.
� Therearebothintegerandfloatingpointprimitivetypes.
� Thereare4integerdatatypes� byte–asinglebyteusedforsmallintegers� short–twobytes� int–4bytes–allconstantintegersareassumedtobeoftypeint
� long–8bytes–useforverylargenumber
12
![Page 13: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/13.jpg)
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
![Page 14: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/14.jpg)
Primi/veNumericDataTypes(3)
� Thereisafundamentaldifferencebetweenthetherepresentationsofintegersandfloatingpointnumbersinthecomputer.� Integertypeshavenofractionalpart;floatingpointtypeshaveafractionalpart.
� Onpaper,integershavenodecimalpoint,andfloatingpointtypesdo.Butinmainmemory,therearenodecimalpoints:evenfloatingpointvaluesarerepresentedwithbitpatterns.
14
![Page 15: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/15.jpg)
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
![Page 16: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/16.jpg)
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
![Page 17: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/17.jpg)
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
![Page 18: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/18.jpg)
NumericOperators(2)� Alloftheseoperatorscanbeusedonfloatingpointnumbersandonintegernumbers.� The%operatorisrarelyusedonfloatingpoint.(wewon’tbeusingit,buttheremainderconceptwouldbesimilar)
� Whenmixingfloatingpointnumbersandintegernumbers,floatingpointtakesprecedence–thisiscalledcasting
� Anintegeroperationisalwaysdonewith32bitsormore.Ifoneorbothoperandis64bits(datatypelong)thentheoperationisdonewith64bits.Otherwisetheoperationisdonewith32bits,evenifbothoperandsaresmallerthan32bits.� Forexample,with16bitshortvariables,thearithmeticisdoneusing32bits:
18
![Page 19: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/19.jpg)
IntegerArithmeJc� Inintegerarithmeticyoualwaystruncate
� 7/2 = 3 � 11/4 = 2
� Themodulusoperatorgivesyoutheremainder� 7%4 = 3 � 9%2=?� Anyideasonwherethe%canbehelpful?� Note:InJavathesignoftheresultofa%bisalwaysthesignofa(thedividend).
19
![Page 20: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/20.jpg)
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
![Page 21: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/21.jpg)
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
![Page 22: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/22.jpg)
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
![Page 23: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/23.jpg)
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
![Page 24: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/24.jpg)
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
![Page 25: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/25.jpg)
SwitchesandBooleanLogic
25
XA BY
TogetfromAtoBbothXandYmustbeclosed–X&&Y
A B
X
Y
TogetfromAtoBeitherXorYmustbeclosed–X||Y
A
A
![Page 26: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/26.jpg)
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
![Page 27: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/27.jpg)
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
![Page 28: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/28.jpg)
SomeExtraExamples� 5>4 – true � 4>5 – false � (5>4) || (4>5) - ? � (5>4) && (4>5) - ?
28
![Page 29: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/29.jpg)
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
![Page 30: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/30.jpg)
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
![Page 31: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/31.jpg)
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
![Page 32: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/32.jpg)
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
![Page 33: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/33.jpg)
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
![Page 34: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/34.jpg)
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
![Page 35: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/35.jpg)
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
![Page 36: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/36.jpg)
ProgrammingExercise-Class(1)Modifythefollowingprogramsothatit’soutputis:WelcomeToJavaProgrammingpublicclassWelcome1{
publicstaticvoidmain(String[]args){ System.out.println(“WelcomeToJavaProgramming”);}
}
36
![Page 37: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/37.jpg)
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
![Page 38: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/38.jpg)
ProgrammingExercise-Lab(1)Exercise7.TriangleWithInitialsWriteaprogramthatprintsthetriangle:****H***G****R*******
38
![Page 39: Expressions and Data Types CSC 121 Fall 2016 …csc121csudhfall2016.weebly.com/uploads/2/2/7/6/22764976/lesson_2...Expressions and Data Types CSC ... • The first line class Hello](https://reader037.vdocument.in/reader037/viewer/2022110223/5ae708b27f8b9a8b2b8e135d/html5/thumbnails/39.jpg)
ProgrammingExercise-Lab(2)Exercise2.UptimeTheuptimecommandoftheUNIXoperatingsystemdisplaysthenumberofdays,hoursandminutessincetheoperatingsystemwasstarted.ForexampletheUNIXcommanduptimemightreturnthestringUp53days12:39.Writeaprogramthatconvertsthe53days,12hoursand39minutestothenumberofsecondsthathaveelapsedsincetheoperatingsincewaslaststarted.
39