New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Geraldine McLaughlin

HONComputerProgrammingI CS240

Geraldine McLaughlin
GPA 3.87


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 33 page Class Notes was uploaded by Geraldine McLaughlin on Thursday October 29, 2015. The Class Notes belongs to CS240 at Wright State University taught by Staff in Fall. Since its upload, it has received 12 views. For similar materials see /class/231107/cs240-wright-state-university in ComputerScienence at Wright State University.

Popular in ComputerScienence


Reviews for HONComputerProgrammingI


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/29/15
CS 240 Computer Science Admnwhdgamm mas 51m wen mum 17 Ma Damwnh mmm9 yl uzsmmmlsm mm P de m Mam mm sums umwm hwquotAdnumwasky mg Mamm w mam mamn s caas Compingquot 6 yyga mufalo mw xmx x n engineer s introduction to abstraction and the digital computer Themudem gmeml puxpuse dlglal cumpula39 AbslmcnmEnmpsulauun Desyi decumpusmun What is a computer a Whatis cumputatm 7 T y suns afaampmmg aamaas they fall mm twu categunes a Analug rmdnnes Lhatpmduce ananswer that msuras sama cunhnuuus physml prume suah as distance lighlxnlensny urimltage E les 7 cigar nachmes Lhalperfurm cumputaums by rmmpulaung a xed mle set ar aiamams Exampiasn The dif th mm analag devices is mantis va39y mm in mtrase man accuracy t Befuremudem digital cumputers the must aamman digtal mashmas were adding machmes a ddmg rrachmes pafurm Exac y une sun arapamuan Ganeral purpuse diam cumputers alsu perfurm une upera un a Mndzmcmnpmzxs accept asst afmsmlctmns um aim hnwla dn mysaxt afcampulnonn a Wa nuW maka a clear dishnchun between calculaturs and umputersquot wmmmmm mom cx m How do we get the electrons to do the work t Wa describe am pmblems m English m sama uLhernatural language Cumputer prublems are sulved by eleclxuns uwmg aruund mslde ma cumputer t It is necessary tn lxansfurm uurpmblem 39um anamral language tn lhevultages Lhatm uence ma uw ufeleclxuns This lxansfurmatmnxsreally a sequence ufsystemauc transfurmanuns develuped and lmpmved uverthe last 5n years which cumbme tn gva the cumputer ma gamma carry uutwhatmay appeartu he very cumphcated tasks In reality these tasks must decumpused mm anumber ufslmple and skaghtr furward subtasks Engneenngdesxgq a Tapdnwndzggn a gamma m mllnpmblzms ma momma a szalsafAbsmconn K quot 392 EXZE EJL 3 S Eililwamx The principle of design abstraction a Gmeml model forEngmeenng Eyme1992 Alteranan Reverse Cunr remnk Cunr Furward Engineering aepuai a Engineering Abxtmcmm Re nement w rrulfvw Deng m Desxgu Implemmtzuun ImplEmmlzuun Emsung System Target System E 39 TEMWinauia mms 5m x Levels of abstraction in digital computation The Prublem cs 24x 4m Sam M Cnmputer Science Algunlhm amp Language I CEG zzn Hmwm level CanME Engineering ISA amp Mmm architecture git hm CnmpllterElect Enginaaring I CEO mm Circuits ampDevxces J quot 2 EIZZL E A 3 SJ ifiilwxamx The statement of the problem a Natural languages are fraught Wlth a lot of a We descrlbe problems thatwe Wlshto solye Wlth a computer ln a u uage ll o a computer Algurlthm amp Language t The lmp ortant ofthese unacceptable attrlbutes ls amblgulty To mfer the meanlng of a ISA amp MlErD archltecture a n n that the computer does not have 7 Mary had al tlelamh and uthernursery r ymesquot a A computer can not deal Wlth any amblgulty thus 6 mnemonle selloummmr or m The algorithm The Problem throat m in E t ISA amp Mleroarehlteeture some clreults ampDevlces It a The rst step ln the sequence oftransfol39matlons the problem to an algorlthm An algorlthm ls a steprbyrstep procedure 7 That txansful39ms anlnpot posslbly NULL lnto some uutput or uutput aeaon e Thatls gu terml at Deflrllreness Each step ls n e preclsely stated ach step must be erform o For any computable prob lem there are an lnrlnlte number of algonthms to solve lt r Whlch sulutmn ls best7 H mm th ea mummyquot or at The programming language The Problem The nait step ls to transform the algorlthm lnto a computer program a Progammlng languages are unamblguous mechanlcal languages ampL2nglage a There are two klnds ofprogrammlng languages ISA amp Mleroarehlteeture It clreults ampDevlces rirl e nghrlevel languages are maehlne lndependent They are far abovequot the un erlylng cumputer e Lowrlevel languages aremaehlne dependent They are aed to the cumputer on whleh the progam wlll execute There ls g e ly only one suehlanguage permaehlne refenedtu as lts AssEMBLYlanguage l Suwawcque outgrow el lll em l Exponential growth 10 1 s 10 3 Number of students ln the college of englneenng lOVt Numb er of students enrolled at erght State Uan erslty 1vo Number ofpeople ln Dayton 10 8 Number ofpeople ln 0th a 10 10 Number of stars ln the galaxy e 10 20 Total number of all stars ln the unlv ase e 10 80 Total number ofpartlcles ln the unlverse 10 100 ltlt Numba ofposslble solutlons to travellng saleman 100 e Trayelllng salesman 100 ls computable but lt ls NOT feaslble 1 Mie lil iili39l a ffl izlquot axiom 9 How do we specify the program s Contemporary languages 7 Java c c c perl Fythun Ruby and many more Languages ofyore e Foman coBoL and many more e Speclalty languages 7 VHDL slmulallun languages and man more D Thae are over 1000 standardlzedquot programmlng languages today e The only goal ofthese languages ls to help humans lmplemmt thelr algorlthms ln the lnsh uctlons ayallable for a partlcularISA 7 Thls ls what we mean when we say progammlng39 4 mxzznilsgx ll Universal computing devices urlng39eThesle eom t dhy pu e ageneral purpuse compute e b purpuse eomputer pruvldEd that lthas enough tame and enough memory What does thls lmplyv Cumputer sclentlsts helleve that ANYTHING that can be r can he eomput d y any general 7 All cumpulErs rrom thelmst Expenslve to the most Expmslve are mpahle or cumpulmg EXACTLY the me thl ngs 11 they are gym enough tlme and enough 7 Same computers En do thlngs sta39 but none En do more thanany other computer 7 Allcm39mlltms candnexanlydwmmthingl Thus any g39ven p e thhan rohlem is either cnmpnmhle or it is not cnmpumhle msihlz NFC myheeonpulahlemutsunnmr J2 moment t mourn or m l2 The instruction set architecture ISA The next step ls tu translate the pmgam lntu the lnstaueaun set quhe pameulal cumputerthatwlll be used tu eany uut Lhawurk quhepmgam The lnstaueaun SetAxchltecture ISA ls the eumnlete speuaeaaun ufthe lnterface between l L l hardware that carry uutthe Wurk uflhuse pmgrams 7 Examples IAJZlntelAMDanduLhasFuwerFC Mutumla ISA amp Mlcmarchltecture a Prugrams are translated Circuits amp Deylees a 33 3quotZquotZT iil l 2lquot ifi imeml u hum hlgh languages lntu glages are tnnzvazhzdasthey exeeute an axxembler Compilation vs Interpretation a leferent ways uftaanslatlng hlghrlevel language Inlerprelanan e Inla39pr esnmgam that exeeutes pmgam statements 7 gmeallyunellneeunmanuatatlme ges mswmla39medlale results is c al quota s s s warm 7 parmmsuptlmlzatlunu multlpl statements 7 elangemnmlesleeumpllauun eanbe haloslta debug slnse exeeuleueal maybe Mean 7 languages CH CFmranFasm1 ete mu am Hi l yllcdd w v TM mm a tlmllvll j 39 raggamcmmxelanyplan N The von Neumann Model Illustration Memory rill TEMP Memory holds both data and Instructions out me mslmcnons and Inherpras instructions uracil Decode Execulet n k l c Ft 8 s l E l Intothememory sboard mouse olsk Mic etc Outpu produces results tonne user ltuotulor pnmler olsk Mic em 5311 leml ls E I mtg wilxenlnggm The instruction set s ngheLev el Language rJavaC r r A 13 C e Memurerrznsfer Equlvalent Manrh e MEmB MarnC MaanAun e MemEAEI8 MaanAlu n MachlneeLeVelEqulvalenl 7 Assembly uman readable ex Maehlne f l a R2ltR2R3 XEIZZK a BltseBLnaly ollngs 7 Two yalues zero or one 7 We canrepresentthls as eunent cluwlng eunut cluwlng u slmplearchltecture LE XEZEAEIB lllEl U l lll l l l XEKEAIEI lllEl U lllll l l l U l l ll XFZEAEIEI llll l lll l l IUEIU 1 IE The m icroarchitectu re a Thenext step ls tu transful39m the ISA lntu an The Pmb em lmnlementaaun The aetalleu urgamzahun ufan lmnlementaaun ls ealleu lts mlcmarchltecture r The A732 hasbeEn lmplanented by SETail daffaem pmeessuls Ever the past t 1m 8286 8386 8486 Pentlumnany gmelatluns Algunthm lee Language Athlnnmany gmelatluns ete e Eaehlmplemmtatlun ls an uppultunlty fur cumpula39 designs in make dlffamt tmderu s between oust and pa39fm39mance c nmpula39 oeslgl ls always an elem nae ISA ampMi mmhiu1um 0 Some ISA are lmplemented by a Vlltual i E sel deru s by an actual mlcroarohlteotule r Emu slurs 4 SWSZ ZZZ SEZTJLE A SSEJTE ifiilarnml n The logic circuit The pmblgm e The nail step ls to lmplement each element of a Helethele are also ohOloes as the loglc oleslgnel decldes how to best make the trade nnanoe offs between cost and per 0 Algunthm amp Language lsAMLlemarehlteeture Cmespmdmg costs I r m Cholces of loglc ollcults to perform thls operatlon and dlffenng speeds and ml 2 lll The devices ance wth the requrrements oth partrcular deyrce technology used c So Algmmm amp Language crrcurts whlch are drfferent ln tum from gallrum arsenrde crrcurts ISA dz Mlcrrarchltertlxe Rs 3 V a Flnally eachbasrc logrc crrcurtrs rmplemented ln accord e 6 Errmrxrznmoxcllxrrnmr rmx x 19 Programming basics Semanucs syntax and style Declamuuns mamas and data types Asslgumenls operators Parts of a program public class Hellnwnrld 39n StrinyU args uhl c static aid nun Sy em nut printlnC elln Wurld Semantlcs r the meanlng a When programmrng we to should focus on semantrcs s Syntax s the rules that must be followed when wrrtrng a progam c In algebra what ls 5 31w what ls 51w 0 rogra ln language syntax rules are llke grammar rules ln naturalspoken languages Syntax drlrers by languagel a Syntax rules are requlred to ayord ambrgurt c ComprlerstEs help ldentlfy syntax errors but llke grammar they must largely be memorlzed r E I y miwcirxcnlpggrrnwe rm x 2 The class header puhllc class ellnwnrld uhllc static vnid main String args Sy tam nut printlnC elln Wurld puhllc class Hellnwnrld has lmhlynmmmslbwmu palalep ltl ll antlcsr untle l of a desrgn that conceptually belong together r Syntax 7 Every Java flle must have exactly one publlc class The name othaL class ls also the name o the text flle ln whlch the progam ls stored e g HelloWorldJava Case sensrtryekeywords publlc class and ldentlflers HelloWorld s ldentrfrers can use alpha numerrc nonleadrng and underscore K r31quot a 392quotcquotquotni rri3955 3r r EilCEwrsmr 22 The main method header public class Hellnwnrld puhllc static vnid maln String args System nut printlnC elln Wurld puhllc static vnid main String args r Semantrcally 7 Methods aka functlons rouLlnes subroutrnes procedures contarn code to complete a tas c m routrne deflnes that start of the algorrthm Themaln methods rsthe start and endpornt othe program s executlon m 39 Tcnmznwyxcm rrnmr rm x 21 The main method body puhllc class Hellnwnrld puhllc static vnid main String args System nut printlnC elln Wurld System nutprint1n elln Wurld Semantrcally 7 Methods b odles consrsts of statements that descnb e an algorrthm to be executed Syntax s Statements rdentrly a speclflc rnstructron uslng a key word or a programmersystem de ned method wth an rdentrfrer Statements must end wth a semrcolon e whrtespace lncludlng rndentatron ls largely rgnored b System out prrntlno ls a method to produce output The detarls are E Siquot a 2quotcquotquotni rri39f 3r rquot ifi lwrsmr u How Java Compiles Style package Hellnwnrld projectapplication name package Hellnwnrld projectapplication name public class Hellnwnrld classfile name public class Hellnwnrld t classfile name public static vnid main String arcs public static vnid main stringn args system out printlnC elln Wurld system out printlnmtello Wurld Javabyte code gt Hello class le Java JavaBytecude package Hellnwnrld Hellnwnrld e 7 Java suurce nude Hetto t ava Text le NM 5 a publi class 1 an T mewmp lert Hellnwnrld public static vnid main String args t Systemnutprintln nellu Wu d RunsunderXF Runs under Lmux Runs under Umx H an a PC un aFC un amam ame 22 m zzmi sx xtures 25 are quot3 12 3 Eaten 25 Variable declarations Assignment statements Vambles are used to hold data ems a Asstgnment statements take the followlng form a variableuame value react variable gets value to be stored and how much space ltneeds etc gt The Lett Hand Slde LHS othe asslgnmentmustbe a varlable The nghl Hand Slde RHS can be a htecat a vanabte a method an ran mg thatcan d as a value Varlable Declarations Lake the form daLaType vanableName l t counter equattono yth betnterprete e anmvedala types arebulll mloaprogammmg language and have u L Lemlsrepresemanumhangmgmmvmableommmnmalue Vedkeyw 5 ome ldemedwamypesam ea edby e Ea hhterat asadmatypewhlchcanbespecl edorwlllbelmplledby rogrammers and use tdenttfters her e JavahasSpnmlee datatypes byte that 7 5th 7 dwhlg e value Integer numbers default to type int e price 55m Floating point numbers default to double 1 EDDIE e letter e39 Single character literals tuse H 7 lung 7 Elm e word e Dogma strings are a cterivect data type tuse H a Local vanables have a hfettme scope fornow assume to method end 1 mamui z sx more 27 m quot9 2ttbi3 men 2x Variables In summary Operators Varlabledeclaratlon Asslgnmmt statement Imuallzeddeclaratlon r memesmmxpuatevanetesusmetheaperatmspmmaeahymehshtevet mtvatue valuees tntvatuees 1mg t Yuu need to knuw the operators funetron assuclatlvlty precedence and the data type oftheresutt lxt a We39veatreadysemtheassrpnmentoperator ball 5 n JavahasSanthmeacuperaturs quotm nae mac m an two munmt we beat m am an mm 1 muwn Em roe muleux et ran a u ThlslsaSLnngltterM Itwdtbepnntedaa o a Systemooeprinttvvane value is H mm 5 n m I Themtege wm t o one on aprons Systemootprintintvaioet Mm E m x M H be pnnted out here W 17 slut tn will A SWSZ ZZZ SEZTJLE A SSEJTE iflilemnnar 29 J2 3 quot a tquotcquot quotmi mri39f a 2 mquot ifi lwramar In Example a cum Lhaxecxpmcalafavalue mExampleS Program design and control pm class mmnm a m mm mm m 7 x m x 7 5 public static mud mam tsuqu Blast m Mama Emma 1mm mm mm L l393939t 1 Structured programming Semantics of control ow Hawdayaudeaglanalgmxthmtasalveacamplzx pramng v mguamxmmg 7 ma mdcanque 7 s mud n Stanthhsystzmaucdecampaatmnufpmblem mam 7 wapamvvmyas 7 sgxgcmcmum 7 mpwxsexe nzmmt m mm Th 27 t l d bl Id 7 quotHanan g m MM ecampasngapm emmcu LW 7 s halexecuuan pmmmammm 7 Semwcmum Thes ecanc eplsuemvexsalta Damukum P T25 quot3 7 K a m 7 exam y quot 41 specifythzsebehawmsm Method calls WWW quotng an n K 27 u Syntax of control ow Relational Operators se wma 549mm quot Hm 1 CommuanaltestsmmewluatetaTRUE mFALSE statemm swam whlecandnuar3 gunman gamma statemen gt t 7g mama Hgmmmts are swam Hueatzdu onequot gamma um as gamma 3 m x m Stepwise re n ement illustrated Create apmgam that cwuntsdawnfmm mu Sample when mu 9 92 Stepwise re n ement illustrated e n i Method calls The Call Return mechanism e MethadxsanOOPtemi v The guexllusntesthz execuumafapmgam emphehgeaae 7 Cammanlyusedtumnnlagymcludesfunctmns pmcenhres a mgmmsA w x v maz mutmzs 7 Natemat agnmtAxsxepuudswexalumes andsaxs n Usedfm 7 7 Deeampaeum 7 Frequen yexrculzdcade 52939nt 7 Lehmymmheepeeemuhgmehaemperm cammanmsks Requnrzments 7 peeephmemehhpue andxetunwluasofany 7 Callfmm anypmntmthe aw anhe pragam mdxmxncmtml m thesamepmnt Example syeem vutpnn xf HellaWadd39 W sue 3 i a Java API library A method for input e JavasendsmfammmmthemndardIO dewcesbyuangahvaclass e heeearuemmeehhamgemheeheemheheehihesehheehee madman mud MmImxy n The Scanan classxs eaheehmeum 5a we wxl use the fa vwmg natanentnlthzmp ufvurpxagam 7 The cmsalethatstms Alma spphcauanxstypxca y lmnwn as the enzymaom device 7 Th2smwiwdmpttdmceislypxca ythekeybaard n Javaclasszsmthz standazdhwhb rvue accessedusnzthz 1m Applicn om Prognmmmg Interface API Hem Wurld l em dassfmm the hle mm and abjectsthatperfami system level Systemmu prnln Thnsstatzmentusesthzsyst The Systzm class emhhsme tasks The humane Amanda71 ufthe System ems cmmnsthz meqhha hhuh mpurr Javaurl De 0 Scannzxablectswmk withsvslzmm 4 Ta create ascmmxalqen Scanner kEthar e Useful meqhhae mdude n a new acehhe l vscemJnl he Ihm exemmehehexmhmsemmegex nextDDublEll exemmehehex asadauhle hex when exemmehehexumemsmhg n 12 Example input with nextlnt arest c seeexe vuxd mexntserxng 1 s new Scann9r ystem1n eenner keyboard xne numl 1n numz Systemuutpr1ntlnquotvalue 1 ll numl keyboardnextlnt Systemuutpr1ntlnquotvalue 29 ll keyboardnextlnt sum numl numz Systemuutpr1ntlnquot um 15 ll Systemuutpr1ntlnsum 6 Sommzmtoxctttn mmr ximx x u Debugging Comptlers help nd syntax errors often wtth crypttc messages Semanttc errors requtre domatn speclflc context to Identify Most tntegrated development enytronments proytde a debuggtng tool A debuggtng tool proytdes at least the abtltty to 7 stop executton when destre Emkpmms alluwthe usertu set punts atwhteh exeeuttun will halt ampWal tor a new mnquot ur cum1nuequot tnstruettun e Examtne the contents ofvanables and memory locattons e Execute tnstructtons one at a ttme or tn small goups Runwill settheprugremrunrtn Slngle step muses a stngle tnstruettun to be exeeuted ever muses the a elled method to be exeeute tntu fulluws the pmgammlu the elled method Step Step I 39 metronomequot otsam Style Programmlng languages h general noytce programm 1 These shomuti ar c ave a yartety of tnteresttng features that tn ers should ayotd Learn to ayotd bad programmtng habtts earlyl e Example rne x y y 5 V5 xne numseudenes xne x 5 numseudenes wttrtmmmmr cttrrrnme ct ttt as Representing information Btts Bytes andMemory E Type casttng u DesignDebugging examples Input a number count down from tt to 0 then back a Input two numbers output thetr mean Input a rate ofpay and a number ofhours worked to calculate wage m Etnggawcmmuc tantrum or to mourn as Encoding How do we represent information data tn a form that ts mutually comprehenstble by human and machlne7 e The devlcesLhai make up a computer are swrtches that can be on or off t e at htgh or low voltage 7 Thus they naturally provldeus wtth two symbols towork wtth we c m on go off or more usefully o and l Btt Btnary then We wtll start by how to represent 7 Integernumbers e Floattngpotntnumbers Characters e Ulttmately we wtll have to develop schemes for representtng all concetyabletypes oflnfor rnatlon 7 language tmages acttons etc J Siquot r 2quotcquotquotni rri39f 3r rquot ifi lwnmr at Why do Computers use Base 2 v BasemNumherRepresmtauun 7 Natural represemauun fur human m muns 124siinz2ini4innsin7i 7 Evmmmesurmughinsnatinenutaum l 5213 x 1m 7 Hard tr inniement Ele mmmlly NIAC First eieetmnie eumputer used In meuumtuhes digit Hard tr sturetransmit Need high prensiuntu eneuue 1U agar ieveis m singe wire tat runeums E 7 Easy in represmtsture with eieetrie eurrmthistahie elements 7 Reliably tmnsrntteu un nmsy anuinaeeurste wires Main Memory s Commonly implementedwith randomaeeessmemory RAM a Each address contains 0 u ted in 5 groups ofeighi bits A diso en320r64bits or numbers with bits7 Main memury eanhe wsuahzeu as a culumn urmw ufcells Ahyteaaaressahie memury Iii m zzisx Warmer as Unsigned Binary Integers Y abc a22 b21 020 r rm mrrm h m d 39 h h m i i 1 Wm quotm m 1 my a a N number ofbits Range is 0 g i lt 2N7 1 Umin 0 U max 2 1 1232 22221232 Problem 1322 22221322 How d numbers u 1 rx tui l x more si Two s Complement 9 Transformation AAA 7 Tu txansfurm 2mm 1 invert all bits in a and add quotquotquot tn the result i quotquot Range is2Nquotlti lt2N39171 j min 2er 4 im Tmavzmel j 2 ML Operations need not check the sign Only one representation for zero I Ef cient use of all the bits 7n max zmhi39mam sixiwmr 5 3 quot3 2quot ZL LZZ 3 IJ 5n Signed Magnitude Leading bit is Lhe mbii Y abc 1ab21 c20 j 1 Rangeis 2N3911ltilt2N39171 s Smin 2N391 1 j 2 Smax 2N3917 1 n W Prob ems How do we do additionsubtraction I We have two numbers for zero z 7m quot9 Limzri39sya axiom 52 Manipulating Binary numbers s Binaryto Decimal conversion amp Viee7versa 7 A decimal number can be broken down by iteratively determining the highestpower oftwo that fits in the number 7 e g lt i a 1101 13 1011 7 1000 gt 8 as expectedi o What ifthe value othe answer can not be represented7 r Ova owi m ammo a WWW 5 Dangers of abstraction Real numbers 7 Assume machine viitn 32 bit word size tw o s complement integers v Must numbers in Lhe realquot Wurld arenntinteger i a gay yuu nave spaeetn represent aten dint neeimat number Where Wuuld jnu e For each othe following arpressions either puttine neeimat place7 A etnatistruet anargumentiatues 7 Range Thermmludeufthe umbasvaemnrepresmldelarmnedbyufh s Give Example Where nnt true e g wuhZbels ti largest representable nnmhens t minim ma sm faxmnypnrpusesl e Freclsmn Theexacmesswithwmnhweanwenfyanwnberweiamnedby3tufbns 2g a bnnnmhexgmsus31bllsafpxecismnaxmughlyg gmpncmanmdzcml Is xx gt 0 always eruea xepxesenlnonn initiaiimioquot If or is am lt 0 true a Our denmal system handlesnunrmtegerrealnumbersby adding yet anuLhersymbul rthe neeimat paint tn make a xedpamtnutauun int x 17170 Is xyz ppm 5 7 g 5 mg ml int y harO 6 l n7 1U 81E ur 345678X103 a The mnngpamt nr seienase nntaann allqu us tn represent very large and very small numbers integer nrreat vvitn as muen nr asiittiepreeisinn as needed is g 2575 n12 1131l lZ lZ2 llElEll llEl2 url lEIEIlllEI X Z eAs aiiterai 2 75151 Ernutanun int 2 funharO What if x y and z are 17f flushing paint nulnhers 6 gagginvimnxeviirtfnnnr cx iii 3 33 quotSIZLiXiTMZ A SSSL ISr ifiilwimi 56 lEEE754 fp numbers Numeric data types in JAVA o Duubie preeision 64 bit oating p6int 1 11 bits N 1S x 1fraction x 20mm exii1 23 52 bits o Range amp Precision 0 32 i mantissa utza bits 1 gt approx 7 uigits ueeimai i a X Wise 2quot 7 gt mm min eigts ntaeeuraey o 64 bit mantissa utsz bits 1gt approx 16 digits ueeimai THEM 3 mm mm vvitn 15 aigts ntaeeuraey E EWS39TM ZZZES ni39JLE L ESr iZJTE Smitten 51 K illquot 39tquotequotxquotni rii39 3l Eililwimi 5x Data type of result Shortcuts and Pitfalls Typecasting a problemsarisewnmyouattempttomixtwo minim a AdditionSubtraction Itmixedtypes smallertype is promoted to different data types 2 v larger e ewary ofcomp er assumptionsi mm am e x 43 an vverisimpiieitiy prnmnteatypeeasttnnnub1e In 1mmegamgaimeucasfi amt ta3mm e Division IfboLh operands are otintegertype Lhe detauitresuit isa e In avarealnumber literals are Casi as 3 mm mm quotuncatedmteger double new r in x 5 aerate a e in r is a if A i ii erue lite 16 not 2 but 11 e Resultsofmixedtypesarepramatedtolhe l d 3 mama up mm mm m largertype WWW r i ldouhle x 3 1 t false lexpllclt typecastlng 1 Examples W m39 a Themles canbeovariddenbytypecastmgme operands orresul m 5 5 m eg spe auyogt ii in e PutthenameoftheLypeinparenLhesesbeforeLheRHS vanabieor e 2 03 is Casi as a double Specifically o 666 uni13 M resut a Java automaucallyconvertslowerprecisiontypes mmmm float x lfloat isaui to higher precision types butnotvisarversal usewmk ti Typecasting teiisthatthe programmerKNoWs what they are doing A ti A MSZ ZZZ SSXii39JLE L SSZJTE ifiilwnm 59 42 illquot tquoteitliiiii39i f 3l Sliilwimi 6n Representing text input characters 7 cc uses standard 74m Ascll eneuurng 7 Java uses lorbltumc name nunrher r391u213quot E s NlcoDE rsa supersel quSCH that rneludes eharaetes rur nuannglrsh alphabets Character A has code x0065 charact er nurnher 0 has code x0030 48 in decimal 48 50 a Escapesequences used forspeclal characters e Java supp rt ype char type HEX r butstnngs are a bulll in class in Java 6 rmrazwmxeulrrrrarr 5331 rrmr 5 Boolean data types e Two valued true or fats n Thebuulean datatype ls u en used tn secure the result Ufa eundluunal test l Thehuulean lrterals are the keywurds true and false nu quute eegha n ea u 3159 a A predrcate method ls one that returns a boo le nvalue a The Character class has severalpredlcaternethods lncludlng Character1sD1g1 Character1sLetter char Character1sLowerCase char Character1sUpperCase char Character1swh1tespace char E nquot quot il i rri39l fl i r39 iiiilarrrmr m Enumerated Types ln Engllsh Thls lsamajorpolntofstylel a Enumerate tpes areapowerful alternatrveto schemes lnwhlch you exprcrtly say 1 stands for red 2 stands for green 3 stands forblue J 1f ehusenculur 1 V 1f lehusenculur CulurRED a rne resule reerreveeayrumaea l uaea erue reuse reuse Vs r rne resule reerreveeayrumaea lea Employee tatusCURR a ea angellemma Marruageseaeus muumn payruluype SALAR n enurn TypeNamelt One orrnore comma separated labels A msx mz sg lr xs ifiilarrrmr 55 Escape sequences 3 39 Staggevcmmxelexam 52 String A simple object String 15 such a useful data typethat ll 15 bulltlnto the language lava lang e String has Its Own contectfor ena e String ob J ects are bullt automatically wthoul the need to 111V oke new Y ObjectsnsereferEnEEpninters rnessagel E llellu Wurldn rnessagez E Guudhye messagel messagez serrna nessagar mam r a r world n u G E e strrng objects corne wth usefule methods llke len loL ovverCaseo and charALO Strung mess ehar leeeer messagezcharm l 1 emnwremr so Enumeratecl Types Syntax Each value of an enurnerated type ls an object oftype Day and should be treated as suc g Eachvalue ls ordered ordlnal value from o to lastvalue enun hay va h u noum ruasuay Elm w SDAY THURSDAY may SATURDAY nay euuay r tdayDa quotD v 1f ltud 7 ay r y r 1f ltudayequalslbayMO y a If ltuday eunpareTu may it ueeeer MONDAY 71 lt u System uue pruneln ltuday tudayurd1nall n DaySLVIlD pruuuees pruuuees MONDAY 1 AYurd1nall preuuees u E wnnxmvanq r unmnrnrnr mm amnnrrnernrrmr fi lwremr st Scope Global and Local Vlhexe lsLhevanable accesabl a 1 languagesvmahlesarede mdasbemgmam Z 5 395 a mug m 7 Statmxtnxageclau mmmmy1moalmdtn07 Compiler mfexs scape rm Wm variable 5 declaredunless Wm Naman mimxpmymmummywaww mu 7 mm MM 7 m mt y a Glabal accessedanywhzre mpmgam stemming 7 Glahalvanahlz u declared mum a1hlnckx a Lacs myaccesammapamcmmegmmammmm 7 vim u lacaltn m methodblack 3mm pmmltu declared 7 black de mdhynpenam chxedhmex i mmumguag Scoping Example 1mm 7 in mm mm mm ma mm mm up M m yum imam m7 mam 7 1 1m 7 my mm m yum imam t mm m w quotin imam mtg1 m 322232 i a Summary Representing information Summary ll Representing information Dammit allocate mmanfmmnmzmrytn bald mfmmaonnnfthz Wm 5mm rahnnztplac mm mfnmlamn am 7 a mmnhmmnh nahmxmmtanmunfth mmmm 7 m maxtnndmmmrycanhuhrge mahlzlmntahlz7 symmypmgmrmmua 7 mwmm a can xanmoalvmcnmtamlunrrmtahl 7 m Mu MM 57 lg mmkm 31 mm Us MWMMmM cm mnmmmx u mmzdmaufmzmmyu x fmmhmnudeclmdunmmzem Gamma afthz mtlwd r Ihxem hcalWanahlu 7 c P 7 mm vanahl fall mm memnxyxtu reclamlzd 7 canmtxunlv mmquot a mm mm m xk nmnmlmpchavmmvh Cmm ydzcmewhatdatatypex tmu m m mfnnmtmn mrugrmmm WKWVM 7 Cnmidexymxmultvamex 7 Declamtmncnnvemmxa 7 u typecamrgthhcautmn mmbm rEzwa ufexceed the mcuxmnf xdata quot1quot m P m W rlrmalmtmnconvenmm 521 m a 22 70 Real world realities Here be dragons Pit ll Ariane 5 mxsswwwwww n D Systemuurprncln m was 1 m is m my Eggnmmgmgm Systemoumprmcln nn Gamma man lam LEI 3141 7kagdoKrmAmm mmmmmmmm 0 mm A 5 count from m w 15 by u m Useasm do 1 Dun m 3 Rem quothue i count 15 i t M 7 Explnded xecnndx am 5 em on an In councl39 quotwwwwwwww mm 1 E EP l 39 nwwwwwwww 7 Caignwnnh oom wn a count 7 m n wwwwwww m n 13 lwmmmmmmm 2 i u i 1 Classes objects methods and fields Introduction to methods s Objects Software entltlesLhatcontaln alirlbutes elds andmethods functions 9 Class The codeblueprlntthal descrlbes related eldsmethods e The data typequot ofan object 7 Objects are msmrlcex ofa class created uslng new clasSNamequot Zem urmnre Dialects nay heermted Sums class methuds an be sad withuutan uhlemmsiances Smugsufmgms r Fields Typedvanables conialned lnquot the object Usngm ads 7 Objectfleld note thatthe eldmay ltselfbeanobjed Wnungmemuds e Methods Functlmsmatme objectclass IS capable ofperformmg Cummnnly used Jam hhmry methuds a Class method 7 ObjectmeLhod 33 quotTZiitri st 3 f Sitters u Semantics of Methods Methods in Java Smaller simpler subcomponentofprogram AmeLhod t3 Provldes a consists of A atmn e hde luwrlevel detads 7 Deal ar meludes return mlue runeunn name and the nrder and data type ufall arguments 7 name r t39 h nal e glvehlgurlevel saueture tn prngram 5U argumen amp u gt d easier tn understan nverall prngam tan 935mm Names urmahles du nut need tn rrateh prutetype but must mateh urdertype e enahles separable lndepmdent develnpment De nes runetlmalltysuuree eude and returns euntml anda value tn alla c Method calls ypmduee sidereffects e zern nr mulaple arguments passed m D Declamm e smgleresultretumeduphunal publn scam2 nr sum nhe hum nr huhzi Vald c De nition DA A YF publn scam2 1m sum lln numl 1m nulle l e by ennvenann unly nne methnd named man th5 de nes starang pmnt reeurh lhuhl may a Methodsmustbedeclaredde e r In oLherlanguages called functions procedures subroutines Ca cheateraae sum lexahl exam I yyhhf m lil i rri39l i a fl illquot initiate 15 m W ZE ZWZCL nZIEJL r IESSJE Eililwmmr 76 The Method call A method call illustrated Avold method 15 onethatslmplyperformsatask andthentermtnates swamalums Method can Systemoutpr1ntln H11 The argument 5 ts enpled mtn the parameter vanahle nuln a A Valuerrelumlng method not only performs a task but also sends a value back to the code thatcalled ll lnt number keyboardnextlnt Method Declaration publlc statlc vold dlsplayValueunt numl Method Deflnltlon Systemoutprlntln The value 15 num a Valuesthat are sent into a method are called arguments Systemout prlntln Hello length Mathsqrtarea e The datatype ofan argumenlaka acmalparametergtlnamethod call must correspond to the method declaratlon c Parameters a k a formal parameters are varlables m the called method matholdsthevaluyargummtsbemgpassed Argument or actualparameter 5 W39hatlsdlsplayed7 Pamm LEA t W39hal ls retumed7 42 SWhT ZZZ SEKri39JLE A SSEJTE ifl lwnmr 77 J2 quot a tquotequot quothi ni39f 2 ifi lwmmr 7x PaSSinQ mumple arguments Calling a valuereturning method The argument 5 is copied into the numl parameter total sumvalue1 val 62 4 The argument to is copied into the num2 parameter publlc stetlc lnt Sum1nt numlr showsumE1EI lnt num2 i publlc steelc vold showsumdouble numl double num2r int result double sum to hold the sum result numl numZ sum numl numZ return result Systemoutprintln The sum ls sum Arguments Parameters Iii 33quotZquotZE LTJLY S EJT 5331 er 79 3 quot3 ff liiriiri sfa r hapterear miwrmr K sirdetta Methods and your data Writing your own method A localvanable is deeiared statements outsidethemeth puhlre elass Mara i cope e Drtferentmethods canhave ioeai variables wiLthe same names beeausethe methods eamot see each others ioeai variables mm x methodsioeaivanabiesexrstoniywhriethemethodrsexeeuung H and mm md increment The vaiuesarguments passed to the parameters othe method become localvariablestoLhatmeLhod e Caubyvaiue inside a method and is not accessible to 0d seaele lne lneremenerlne x l x s x 1 puhllc seaere vole marnrserrneti Brgs l e ChmgesloLhelocalcopiesofvanablesdonotchangetheoriginal m maximum 7 Use umedvaiuetomakeehangestoprrmrtrvedatatypes H I x if IfrefaencesloanobjectarepassedloanmelhodthenLhemeLhod Hyena path mam y y makes a cop othe reference and can use thatrerereneeto make changestoLhealiasedobjeci H and class Mm e Caliby reference 12 yyhhf m m i rri39l39 e flr ri r39 Ellilarremr in A r31quot 7 392quotequot3ri rri39 e r iflilwramr K2 Under the hood Library methods c Making a method eaii involvesLhree basic steps a s Th argumean quhe call arepassed 39nm the caller tn the eallee Java comes eompiete with an extensive library ofgenerally useful meth k paekages 7 return vaiuersretumed tn the eaiier im 1mg default r Themn nmerstaek s Javautil must import Memory Memory eiassJ eiassm Memory Methods are assoeratedwrth a eiass or an object memuair manna 7 Object an mstance ofa eiass ampere j ava uell seanner seanner keyhoa a caller caller oare keyh new seanner l3ystem1n syseemueprrnelninrr rne number keyhoardnextlntl Before call During call Aftercall 7 class ObJSCLmSLhOdOr obiect methodO AZ ma tr mmri39l a r 533 er in 4 r31quot quotequottquota ri39f a 2 iiiilwraaar no Math class methods H a TheJuvaAPIhmuypmwdesaclassnxmedMa h 11mm 1 v a Leunhnwta ndme39hads 7 mum11m W7 1 TthDE W111 halfqu in X the 11911111111111 and a TheMammssmsamgammbmrusm mm ewlanwhmmm methndsmdacawleufmefu canstmt elds l mm 1 Yauhmw E mm 1 51111111111113 11118 a 5111191e Calmhte 39heareaufacxrcle gm Newmatmmmemnasmaw pm multiple mum argummt a double y 7 314 x x 1mm types 5W7 1 Thsxsc ledovalondmg mm a double area 7 11511111 WW Hathpuwlrsdlusy mtg1 a 11 1 1 String class methods O methods 1 TheJwalanguagepxmudesaclassnamedsmng my 1 We39vesezn39heScmnzr a We39ve 5111111115me 11er 5W1 1mm chuutuanhzhxdpaahanuf Wm classfunnput my 160m 11ch v mmm 7 w H gmnbmcun 1mwa symmpmmm quot 3mquot quotm mm 39 mm 7 aaummmwhm 7 91111111011 that 1mg 7 wordmharAHZI mm M mnewm WWW mumquot 7 mtnexdmo 7 pnn n5mng a M 1m U 1 mm 3 g 3 3 quota l C 139 11111114311 7 mmgmxlxmo a symmpzm1v11u 3 m 32 7 new 3 x 11w mm r g c 11121 1 My 11 lem 7 shnnmxtshmo pnnun 113117 w s 3 SE MW7 is 321 i J PITFALL MU mphmem a 37111131513 true 11mm rm Name 1 cumpare D1 1 1 1 true mm mm 1111 1115151752211151751 51 n a 271 Systemoutprintf Buffered O system mmmmam v1 v2 vn xnmmy systems chancursare bufferedmmanaxy nhnnganUO apenum p mew mm magmas mpmm Farmnt smug 7 Ca eplua y eachIO 51mm 1115115 awn buffer a wxdlhpucxaantype 1mm mum 111m 1117 11m mlywhenthz nzwlmz character S4sum wt nnW UID admquot 111a LE M 1 e m Emu kew xspxessed symmmmmu1n7u1uagr7s1nm yd mmmw 7 T1115sumSusanacmxenxmmbefmecan mmgthhlint WWW 39r na Wm v Omputsueam 39 g n w w 7 Chaunexsaxemt huhedtathz amputdmcemhlthemwhm pnnthWatSd mm 1mm wh 151 WW7 cmmnmw 111 2 n a Advmtagesstadmagzs pmmvoz 3r 7 2m 2345611234557 1 234 1 23 57 30 Inclass examples Subsqwm nm Control ow Selection 7 1mm sequence characters gmgpmm mdalengh 7 0mm subsequent 7 Packang mmmnand nmmahtyasamethad Pattun ndex 7 1mm sequence Ema and athree charmer subsequence Mm 7 Outputwdy stamngpaaumafthz subsequzncemthz 5mm mm mmm 7 Package nmmahtyasamethaulxetun nextquotpaauanfwund La 0mm watch c mum operator L l393939t WI Semantics of control ow Syntax ofcontrol ow Tmmmmmms I a Sequentnl a Selection 1 1mm 7 5 mm mum amt mmm mmm whlecandnuur3 7 sdecum maumu mama mummy mum Wmmmm U r Harman quotquot quot39 mp 7m black mexggjgmmmm A A Hammemsm cmmt 7 Tm mmmy uuudas mequot gm 5 specifythesebehawmsm mum gt 45quot plug mmgl 5 WWW gt K x ii Selection control if statements Nested ifs n Mumwwm n mmmymmm mm n mummmm n Mummumn e n mam xntmmmn mummy u an lt m mm n Mumywm m7 nu mmme m N t H m U m mm nmammuwm m m m h mmquot m m n Muman n WWquot lt n t mm a WWW Nahum 1 t H mam m H mm 1 t m wmxmmWWW mm mm mm a WWW Wm w 7 mm M Nu m n m 12 m as Predicate logic and logical Operators lB AampampB AllB 6 ymmnzwmyxcm mnn Erinx x in Order of Precedence 0 quot Operztnrs Descripu39un E I ygmnzwmyxmip mwe ya Best programming practices Flags e Ii is generaiiy a bad practiceto repeal atesl in a progam meoneupdating the test may only see il in oneplacel s A ag is a booleanvariableLhaLmoniLors some condition in a progam n W39henaconditionistruelhe agissel o e The nag canbe Lestedto see ithe condition has changed h o age gt 95 a Late lhiscondilioncanbelesled 1fh1gh5core l Systemoutprlntln That 5 a hlgh scorel mommnmm no known or iii Shortcuts and pitfalls s OrderofPrecedaTce 7 The l operatorhas a higher order ofprecedenceLhan Lhe ampamp and ii operators 7 The rm and ii opaatorshave a lowaprecedenceLhan relational opaators like lt and gt 7 Style hint Always full39y39parenLhesize Short circuiiing 7 Logical AND and logical OR operations perform shortcircuil evaluation of expressions 7 Log cal AND Will evaluate to false as soon as il sees that one ofits operands is a false expression Logical OR will evaluate to true as soon as ll sees Lhal one ofits operan s is a true a ressio 7 Sier hint Avoid stale changingbehavior in logical expressions m 39 Tgmznwyxcm mnn 5min x m 3 nr1nm Cmymarkiunznrnumr cmwwiami ax Logical operator 1le gt y 55 y gt z Shnncircuivjng Systemout prlntlnl true Duestesi gelimmkedifx27 xm l 1H lx gt 1 ll testl l llx gt y 55 iv gt 2 do someehing llxgtylllYgtZ l lx 4 l l l lX 1ft lgtltgt1 sstestl l lXlty do someehing min isquot Distributl n Assl l lC Ac DeMorgan s lAl lE Wank W Al i E 7m mantimiirxyaxzx mien in Shortcuts and pitfalls e ifand 7 The istaLernenL does notrequire curly braces for single slatemml b 7 Style hint ALWAYS include the braces 1f lnumStudents gt MW 7 anemones Wimp 1f lnumStudents gt 5 MW 7 anemones giveizxamsi 1f lnumStudents gt 5H MW 7 anemones l giveizxamsi m WWW WWW m Shortcuts and pitfalls gnm topexawz j Wmqu wmnouse m7 a Eewue ufmngthe 55a E Damn equahty 097mm 7 mswm xesullm mmcampauble type error mm mt 7 Expusaanmust b7 rm antmgpmm pnmmve Switch 7 Hum mmquot Lifesmhfzumues 3372 m mm Mt W m N y mum m 3 m H i 7 W7 mm in w t ym N7 memm mm mm 77va x magmrum MS H and Jquot x g 39 Eewmufmngmgnmangeommmfumw quot kwmbmk 7 xsmzmmeRapemm mm Exxtsfmmlacalcmtxnlblack amp WWW MND Wm mm a swam Exceptfonnswtach 7 We39ncwnmesmw wmmh staumzntswewdlavmdfmmw 21323 m 0322 27 1m Conditional operator 7 vanablemme oolemcm hm 7 wluexftxue Mums Control ow Iteration 37mg gunmnmn 7 wt 7 n 7 WW mm V5 7 7g 7 n t on t swam wadthz m armsmumymbmm operator in rnr 1m Semantics of control ow Syntax ofcontrol ow Tmmmmms v Sequentnl 7 smum Imam 7 s7 mm m W vhfuh statement swam wm7mnmm 7 sdecum maumu mummm mum Wmmmm 7 Wm mp mama Tm nfgfpwjmmmm mums cmmr P TM minyw uuudas mequot gamma specifythesebehawmsm N m gt asst pmgammmgl 75 mmms I m m m dnzntddn test updaEE3 lt d Style 3 end a 0 Use to countthough an exact mber of ltemtlons m I d Alwaysusebmces a l11lt511ltlt seetedntnnntlnnv a Besrpmcuces amatemat 3 end a Varlablesln a for loop notbe used outslde ofthe loop at lent d e 1 lt 1 e um lt body seetedntnnntlnnn 3 end a a Declanngthe loop Variable ln the for statement llmlts the scope 42 quot T EIZ E A E IJ stalth m N ested loo ps o A loop can contarn any statement lncludlng another loo 7 Each rteratron ofthe outerloops causes an rnnerloop to rterate to cornpletron for 1n 1 1 1 11 l for rne j 1 j 5 j amt 1f 1 j l Systemoutpr1nt l 9159 l Systemoutpr1nt l en 1f Systemoutpr1nt n l end for j 6 Errmmimmxalo nnmr me x I IS Using loops to gather input Loops are used to perform rep etrtrye tasks 7 Gettrng rnputrs ottenrepetrtrye e What do you do lfyou don tlmow how much rnputyou have7 standard test condrtrons rnclude r Inputthecou t th szeothelnputasLhelnpul r 17 7 Useauserspecr edsentrnelyalue Eg 15 3r1 7 Test for the end of an lnpul strearn usrng standard sentrnels The EOF runtml character ls embedded as a senlmel value by every rnput device to slgral the aid unhetransrnssrun 1 mmzzzzzritrytsx mm r n More about operators Cornbrned assrgnrnent operators t 7 etc In rern entDecrernent operators Operator assocratryely Operator precedence IrnplrcrtExplrcrtType conyersrons Break statement Exlts current sub statementblock of a loop or sztch statement Jump statements break continue return tryfinally Return stalemenl passes control ofa melhodback to lts caller r Passes control to the nart llne a er the current rnnerrnost rteratron 7 Labels can be used to break from outer loops Contlnue statanenl S rrnrnedrately to the nert Ernallystaternent 1 1 r Latal a style hrnts klps all renarnrng statements and goes iteration othe innermost o ls canbe used m L 7 Av old using breakcontrnue for ow control 53 mommrwo a bpunnm mr us gt00Hgtn Say thatwe needto nd the longestcornrnon subsequence shared by two strrngs Nested loops example blan ro r Blologlcal sequence search Dotrplol avlsualrepresmtatlon ATGGCATTATGGA m womanly c mum ux Combined assignment operators Many erpressrons modlfy an errstrngyarrable x A cornb med operators 7 r m d assrgnrnent operators rrnplrcrtly rncludethe Left Hand Slde x c varlable on the nghl Hand Slde as well 7 E xcl assrgnrnent operator exrsts each othe 5 anthrnetrc a V Style hlnl Use or do no use these operators consrstentlyl 42 nnrrcmuxr 2mm rr m swimmer lzn 20 Increment and decrement operators e IncrementlngDecremmtlng a varlable by one ls a very common task Bitwise operators Ex xx1 yyr1 The lncremenldecremenl operators allow a shorthand notatron 7 Ex x y r x ls a postrlncremenl operator Bltwlse operators allow you to dlrectly manrpulate the blts ln a varlable 7 Generally ths ls not somethng thatyou wlll need to do as a novlce ro ammer p 7 Systems levelprogrammers needto do ths often y X y X 7 Generally you can nutperform these tasks wth any other operator x x 1 runs uruu Hun uruu 1m BllWlseAND amp 795 uuuu nun EIEIEIJ mu N795 111 mu 1m EIou X is aprermcramntopemtor a FW 1 MW OR l mus c 79a anon anon anon nun y r 7 v BWMEXCIUSMQR XOR a mug i ran uruu 111 um 11 Y X 11309 A 798 Hum 11 Elm Elm e style hrnts Use or do not use these operators consrstentlyi Bithse mega 10quot N r x ls frequently used as the rncrement acpressron ln forrloops Literal Values for hexadecimal Values These ope Iii WSZ ZZZESSJLYQSSEJTE 5331nmr 121 a mm th cc mum t e rators also work on boolean typed data 0 ls false 1 ls true e Pltfall what does 1f lt xry Shift operators Bit masking Shl operators moye shrtt all the blts ln a number to the le towards the Most SlgnlflcantBll orto the rlghl towards the Least Srgar cant Bll c There are Lhreebltwlse shl operators 7 Leftshl ltlt 7 Slgnedrlehtshl gtgt 7 Unslgnedrlghtshl gtgtgt c Assume x ls a 8rbltvarlable for ease oflllustratlon In computer scrence a mask ls some da ls used ln order to extract rnformatron stored The most common mask used status of certain bits in a gt11 9 E 5 i r E In the real world mask ls anotherterm for a stencll ta that along wth an op eratron elsewhere also known as a bumask extractsthe blnary stnng or number a blt fleld orbll array LheblnarV strlng 10011101 and we wantto most slgnlflcanl ld use a brtmask such as 00001000 and usethe bltwlse ltlt 2 gtgt 2 gtgtgt 2 r Recalllng that1 AND 11wrth 0 otherwrse we flnd the status of 31 mm 1111 mm mm mm D111 mm mm Lhe hbltslnce10011101AND0000100000001000 17 1m 1111 mm mm 1111 mm mm mm o leewlsewe can setthefrtthbrtby applylnthemasktoLhe datauslng the OR operator E mm limi i ffl l i 5311 rem m m 3 quot 39 L39i39 3 Zii lwhm m Example Networking Example RGB colors 8 Intanet protocol addresses 1 addresses are stored as a 3Zrbltvalue a Z4rbltRGB colors 0 T ey are communrcated as a set of four octets A common way to encode color lsto encode the rntensrty ofRed e Each octetls a speclfled ln a network class ArD Green and Blue contained m the color 7 Z4rbll colors represml each color on a scale from OrZSS a Conslder 129122516 bits 24 is a In Hex 0x817A050F 000011110000 0000 00001111 1s what color 7 a In Decmal 2122709745 E W39hatbltwlse instruction extractsjusl the red componml atbltwlse instruction sets the green componentto15 wllhoul Gwen an lnteger contarnrng a 3Zrbltvalue how would you Chang g me ah Componenm r Dete me the classA subnel for routl e Outputthe address lnIP address formal e c angeLhe class D address to broadcast2557 4 mex zmzri39tsy lms sixlwm 125 oz quotrttt tzri39st axiom m 21 Complete Java Order of Precedence an arm mm ma Dealing With files i o r ii Watertmmrmmrm w PanmnmeSldunmm K a i w m um a mu m or m i i r mm in r m mmwm m r e ss rmiomtwinnm s e s e A manuremammnnrunm M an mam r i arr i m y a bmaDaa Am LWK 13 V0 in n museum running n i ax Excepums a so mom i m a ii ismimrmns amine a m N haehenslamm smssianumxswressiannuss k L memorandum is mmnmmwr 22 m zzisx mum in Introduction to Files File Input and Output lO A computer le is a block of arbitrary information or resource for a The Op erating System handles all file operations for programs stonng informath 7 he os lmows how to interactwith the durable storage device Ayailableto a computerpro ram g e The os has policies on whowhatwhen can access a file 7 Based on some kind ofdurablestora e 7 Given some identifier for future ease ofreference a rilename Blepmpemesm handle he 7 Ayoidshaying toreenterorprintouttedious data 5 any WESSEMMW n A file is Justa Sequence ofbinary digits 7 These bits may represent integer values text characters or anything else s The Operating System 0 3 must upen files for programs 7 programs usemethod callsto invoke os routines Thepmgmm 5mg me me mu quotde sm d me my me 7 New files can be created and opened to wrlne output information to present it to the user as a text document image song or program 7 Existing files canbe opened to read in ut Text me As CIIWCODE Chamch 7 Existing files can be opened to wnteappend output ery le Pretty much evaymmg else 7 Existing files can be destroyed and opened to wrltdclobba output mmzzizzziuzs isx mum in m wmvw Warm w u nr1nm cmymarklunznrnumr swimmer nn File Buffers File Buffers a A program invokes a method to ask the os to open the file a After data isreadwritten from the file the os must nush thebuffer and r The os creates a memory area a buffer that the program has access cluse th to e A l open files will be closedwhen the progam ants e The os gives the program a reference to this area a le handle 7 You s ould always explicitly close every file thatyou open 7 cs policy decides ifa progam will be provided a file handle 7 In the future your routine may NOT be the mam routinel Securitypennissions what ifsomeone attem ts to 0 en a filethatis already 0 ened7 The use ofbuffers improyes performance 7 emory is much faster that durable storage devices 7 Tfa file is openedto read the os copiesthe contents ofthe file into e u er 7 Tfa file write occurs the change occurs in the writebuffer e Eventually the os copies the information from the write buffer into e file on the durable storage device 43 3 i 7 3 f i iflilurnmr m J 339quot a 2quotcquot3ii rri39f ifi lwremr 112 File pointers e Open leshaye a u olntel39quot whrch rndrcateswhere thenext read orwnte operatron wlll take place a A le ls treated as a sequentral oneedrmentronal sequence of characters a Recall Llne breaks are represented by nonepnntrng characters 1 The Read pnsitiun mdlcates What Charaders W111 be returned on the mad read operatron e TheRead posrtron ls updatedmoy ed to the rst character follow mg the last characterread Ex 1501 245 e If1501 was read wrth nexthto then the read pornter would be on the space followlng the drgrtl e Ithe nertreadwas yra nextLrneo tlnereturned strrng would be u 2 e 6 Woodmener er m Filenames e Frlenames are specr ed drlrerently rn each os polrcy decrsron Fllenames can be specr ed from a defaultworleng drrectory relative rererence e Netbeans e Set rn project propertres Strlng fllename quotDatatxtquot Frlenamescanbespecr ed arootdrrectoryabsohrterererence e c Documents and Settlngsw001tedDeskLop ata txt Strlng fllename quotCDocument5 and Settlngsquot wDD1tedDesktopDatatxtquot s Prtfall Wlndowsevolved omDOSwhlchusedLhe characterto rndrcatedrr ctory structure Thls ls the escape sequence In ASCIIUNICODE Thus we mustuselll U39N39I s X 03 use a forward slash w I quot f li 1 nitri et 3 Sitters m Writing to a file report java1uFlleVJr1ter report java1DPr1ntVJr1ter 1 t stetrt voru neon letrrnell ores throws Exteptron l tr e Dulean hpeeuniexlenuoirm u rrnel boolean chosen EXISTING rm falsE stung 112 quotDatatxtquot uses workrng dreeotory stung fllenamez quotCDulume eettrngslv nts en quotwEE1tedDesktupDatatxt ll rrlewrrter rrleuenoue new rrlewrrter fllenameCLOEEERJXISTINGJILE errntwrrter outputrrle new errntwrrtet lrrleuendle outputrrleprrntlnlvvuello rrlelquot uutput 11ampcluse l l end method neon 1 efwquotlil iiri39l 2quot5 axiom us The PrlntWriter Class hd FrleWrrter WARNJNG Ifyou glve PrmLWnLa a lename 11 W111 overwnte destroy any enstrng le othaLname eerntwertee outputrrle new PrlntwrlterquotNamestxtquot outputrrle perntlm quotChr15quot outputrrlepernt1nvvrltetheynvv anutputi lle println weenquot outputrrlee1ose Wnte dam tn the me cm mg mg The FileWriter Class e TheFrleWrrterclass ls rn Lhejava lo lrbrary m o t java1 er or 1mport java1o lmpor1alljavaloclasses c To ayord erasrng a le that already ensts e Create a FlleerLerobJectuslng an optronal boolean argument tlnat tellstlne objectto append data to the le mlemrter fwrlter new mlemrtetwnlenemequot true e Thebulrerwrll be created m such a manner tlnat any outputwrllbe appendedto the end othe exrstrng e e The Flleerter ob J ect can be passed to Prlnterter 4 3x i i l 2 ifiiiorremr m m quotyhit lhiy3 signers ur Exceptions e Excep nn when somethng unerpected happens durlng executron The progam ls lnformed by the os so that rt can respond appropnately e Common FlleIO exceptrons rnclude c o reate le lack of permrssrons dlsk space etc Can not nd le le doesnot exrst c The method maklng the os method call that generated the exceptron e Han 1mg onwrllbedrscussed later a To pass rt up the lrne add a throws clause m themetlnod header puhho stetro vord mere lstrrngl ates throws Exoeptron l e FlleIO ls a checkedexceptlan e the etc tron must behandled orpassed up A method wrth le IO wlll generate a comprleetrme eror lthe erceptron ls nothandled orpassed up J2 plenum r mourn er m m 23 Reading from a file s worki statit void nain lettingtl args theows Exteption i t us 39Da atxtquot w riieitiienaine ng directory Scanner inputriie new Scanner itiieeandie string 1 l inputriie hasuextLine l whiie l nextLine i inputriie Systemuutpr1ntlni11ne i inputriie tiuse i i End method nain i end tiass M 2 mmmx msx in File class methods Ifyou attemptto create a ScannerWith a file that doesn texlsl in then aninnieiiitninaaxaepnini ine Danna nni tie nie spanneai at manniernnitsteanineniiiame iieainai at mainniernnitsteaneineiniernnitsteannanino at ianannisinnemneisann ianitnti at ini m i a TheFlle classhas predicate methods ioi doingbasic sanity checking e ex canWriteo canReado canExecute t The Flle class has oLheruseful methods for performlng common tasks e createNewFileo deleteo getpatho getAbsolutePatho The File class can also set 05 properties e setExecutableo setReadableo setWritableo setLastModificationDateo 1 mmzzzzzziii sx salami iii Handling exceptions s A program indicates that it wlll handle an exception rather than throw it up to enext levelby Surroundlng one ormore potentially exception generating methods wth a try black r If a statement in a m blocks generates an exception tlnen the try block s sequential execution halts and it immediately eiecutes the code in a followlng catch block a Multiple catch blocks may be used lfbehavlor dlffers by Exception type a A try statement may optionally be followed by a rmly block that is executed atter statements in the try bl andor any statennents in the catch block lfan exception occurs e statements in the flnally block are eiecuted even If an exception oes not occur m 43 nr39Knm cwnnrreaaariniamr The File class o 3 nr1nm Cmymarkmunznrmumr TheFlle class is in Lhejava io library import javalOFlle Use LheFlle class create a le handle F119 filEHandlE new F119 fllename A Scanner ob i ect can then be made to parse the associated buffer Scanner inputflle new Scanner flleHandle Once an instance ofScanner is created data can beread using the same methods thatyou have used to read keyboard input nertLine nexttnt nextDouble Use the Scanner predicate methods hasNextLineo hasNexthto ha N KW ilhl l Wartimeiwiwti ti aminniamr I w Using multiple Scanner objects scaiiiiex isysteiiiniit ileum l Scannex keyhnazd e new systeiiniitpiiiitt Enlex the eyhnaidiiextuiie ll rue us e new rdleifuenaniel Scannex inpuli ile e aw Scannexi let The lines above e Creates an instance othe Scanner class to read from the keyboard e prompt the user for a lename e Get the fllename from the user e Create an instance othe File classto represent the flle 7 Create an lnstance othe Scanner class that reads Rom the le K i39i39quot n 392quottquotquotni rri3955 3i wquot Eililwramr I oz TryCatChFinally statements try l stateinents that tan tause exteptiuns i tatth laxteption e hat a do is an exteption happens i sinaiiy i what to do no inattet what happens ahove J Siquot n 2quotcquotquotni rri39f 3 nquot ifiilwramr I u 24 TryCatchFinally statements palms seem yam mam is1ng Brgs try 1 Scanner luput new Scanner new F112 iquotDatadatquot more code here catch Exceptlon e t yste u prlntln quotError v e rel v ry code here Systemex1tiz trneIIy t System out puntIn i quotProgam complete I Systemex1t tn Systemex1t t1 end method maln wmmmnmo gunman cx 1m 33 nr 1 Bum cmynwremnammemr I as Introduction to arrays Array usage style Exercise 9 Create a text le named Inventory txtthat contams the followlng Item Inventory Cost Sprocket 10 1 45 wldget 3 3 oo o Wnte a program that produces an output le Accountlng ixt that contalns l e n me number cost and total value of each Item as well as the tota value othe lnventory Item name Inventory Cost Value Sprocket 10 145 14 50 W et 3 3 00 9 00 OT 23 50 Creating Arrays Syntax An array ls an objectso rtneeds an object reference o Thls reference can be stored ln a Varla 1nt t s ores r Array objectsmustbe created tobe a certarn starts slze testseores new Int6 Comblned declaratlonlnltlallzer Inti testseores new Int6 r Nevv array elements values are lnltlallzed to o In Java testgcnres rnder u rnder l lndexZ Index lndex4 lndexS Array lndlces start at o and are oftype mt e Uslng an out ofboundsquot exceptron m 39 Tenmznwyxcme rmem 51140 x m are quot3 2L 3 m Arrays simple data structures Semantics Fundamental data types e Integers Floatlngrp olnt numb ers characters and strlngs Boolean bl Data structures contaln groups ofrelated ltems 7 Thus ata eru ures are contalnas or object o Fundamental data structure the array or ls e Arrays are the slmplest and most common type of data structure e In some languages arrays are the only data structure An Ia lns a group ofliems that are all othe same type and that are drrectly Indexed uslng Lhelr order m ths llst e The elements othe array can be fundamental data types ordenved types lncludlng other arrays 9 We ve already seen ths conceptln Strlng an array of char m m r xmy3 mien m Accessing Arrays Syntax a An element of an array ls accessed by the array name and an rnder m 1 testscoresm 95 testscores 1 testscores El 5 1m CurrentTest 2 testscores CurrentTest 75 munu testScures I 1 Z 3 4 5 e Array elements can betreated as any othervarrable othe element type Array subscrrpts can be accessed uslng rnteger lrterals or varlables J quot 2 EIZZL E A 3 SJ ifi lwremr lsn Array Initialization Syntax a By default array elennents are initializedto o in Java implementation time daysPerMonth lt31 28 31 3D 31 3D 1 31 3D 31 3D 31 c Thenumbers in tlne list are stored in tlne anay in order r daysPerMonthm is assigned 31 r daysPerMonthl is assigned 28 e c e An array variable contains a referenceto daysFerMunLh II tempSwap an anay obiec i What does ths Initialize do7 1n tempswap days Fe rMonth mommiva snowman 33 i nr 1 hum cmuurirmumnmr I s I Bounds Checking Array inderes always start atzero and continueto anay length r 1 1m values w 1nt1EF s This array would have indexes 0 through 9 0 Java throws an exception lfyou access an anay outside oflLs legal indices r Notall progammlng languages performbounds checklngl r whatdoesthisirnp y7 E I y mwmyxcir nrwe xun39x x I 53 Arrays are objects Stringl monthNames Janquot Feb Mar l obiectshold data fields and methods In addition to yourdata all arrays in Java The length of an anay can be obtained via its length ie 1n slze g r Useful anay method includetostnngo cloneo equalso rovide some functionality f ld monthNames len Also note that arrays can hold ob i ects and array elements that are ob i ects have accessto all oflhe nonnnal methods for that obiect Strlng monthNameInCaps monthNamem tuUpperCase j 39 Hni7cmmxcitrimmer glutquotx x I 52 Pitfall OffbyOne Error It is vey easy to be offby one when accessing arrays T hyrune error 1nt numbers new 1nt1EIEI lt l 1 has an one for 1n 1 1 1 number51 r 1 c Here the equal sign allows the loop to continue onto Index 100 whee 99 is the last Index in the array r This code would tlnrow an AnayTndexOutotBoundsException K i39i39rquot n 392quotcquotquotni rii39 3r r Eililwirmi I so for foreach loops Some othe brightestpeople in ComputerScience suggesttlnatanays should neverbe accessed randomly but only sequential 7 Random accesses in arrays tendto be undisciplined error prone and hard to prove conec 7 They suggest other more advanced data structures for random access The enchomed for loop a type offorreach loop provides a means to implement this stylistic constraint For ldatatype elementvarlahle arrayll Statements Compare Mien r Mitten intern r isuirirni miquot en ir Mme ism wi Ml mm mm mm lt 3mm m xriariaimrrrimriiii mm m vnmmmhmr l m Trnmiziwnxcnir mpn 51140 x x 155 Array usage Style e Anays canbe declared usingtwo ditrerent syntax styles songl Sonngst um t playLl t song sonngstH albulestH r Theflrs e as itmore accuratelyindicatestlne variablet eexlh riablesongListisananayoftypesong 7 int doublell stringll ObjeCLNamel can also be used asmetlnod argumentan re umtypes e Bestpractices MAXiNUMioFisoNGS 7mm p1ayListll song songList new song MAXiNUMioFisoNGS e Anays elements are usually accessed sequentially in order with a loop e L and k are conventionally accepted names for loop index vanables Whm the index has no domain specific contail J S39quot n 2quotcquotquotni rii39f 3r rquot ifiilwirmi 156 Style No data structure quot 39 quot quot quotquot al39 mm s museum mm s mm We ml mayhem nsvsma memo mean a tag sans l mess u lmxsxsenm s a mm mm WWW ms mu sewagequot w amen m smm mm s tag w mess l amen m smm mm s sweatquot w Mame l millagequot mm s smnmn Style Usage of an array instead of multiple name va 3 3 i K h esxlmlenltz x an mm mm we sum iv We ml mum s mm n My meym nsvsma Mm mev a as sans l lwsmxvm gt a u s ll x mm m Wm wen womanqu as chum 53 u ml riables u ifiilwnml 15K 22m 1 sw mam 157 Style Usage of named indices 52 Li f iiquot liliii iiii flglx 1 e 231a quotquot 4532 gtiixrtmzl mmm zzmzairxaxm Elihu lsa Objects and References MLLludlmenuunal arrays Exercises Calculate maximum minimum value In an array s SumLheValueslnanana s Avaage the values In an anay e Find sequentlally search for the rst location of a given value In an array gaggawcm nxc bylaw m Eililwnml mu Arrays are objects stungu monthNames l Janquot Feb ObJecLs hold data flelds and methods a In addition to yourdata all arrays In Javaprovlde some functionality The length of an array can be obtalned vla its length eld Useful anay method lncludeLoSmngO eloneo equalsO 0 Also note that arrays can hold ob J ects and anay elemean that are ob J ects b eel have access to all oflhe normal methods for that o J Strung monthNameInCaps monthNameD tDUpperCase Mar l 42 ngvnlscmmxc lr A meml39 fi lwnml 152 27 Assigning object references a A yanabie canbe assrgaedto any object othe approprrate type bets Create an array referenced num 1nt numbers new 1nt1u 1nt digits new numbers digits 1nt5EIEI a Both yarrabies reference the sarne object NOT a copy 0 Ifan objecthasno referencesthen objecLLhm the object rs lost e rt rs garbage andwillbe collectedquot 13 womaner Ceiwn znnnunnr 1 Copying objects You cannotcopy an objectby rnereiy assrgnrng one reference variable to another For an array you need to copy the rndryrduai elements of one array to another 1nt XLlSt 1nt yLlSt 51D152D25i new 1nt5 1 lt xLlstlength 1 yLlSt 1 Or xLlSt yLlstclone e To change the srze of an array you rnust make a new array othe appropnate srze and copy the approprrate eternentst morn th er apnoea a ifiiiwrmr I so How not to test equality Consider 1ntXL15t i1 2 1ntYL15t i1 2 a Whattslt xLlSt yLlst 0 Consider xLlSt yLlSt xL15tE 5 W39hahs7 xLlSt yList yLlSt El 7 1 Wyndham renown 1 55 Testing equality You cannottest equahty srrnipy by deterrnrnrng ithe references are the samei t XLlSt 1ntyL15t i51u152u25i You need to cornpare the rndryrduai elements ofone array to another 5 1D 15 2D 25 llstsEqual xLlstlength yLlstlength for 1n 13 1 lt xLlstlength 1 1f xArray1 l yL15tl i llstsEqual false eORe xLlstequalsyL15t K 339quot a 392quotequotmi rri39 3r EilCEwramr m Passing objects as arguments e Objectreferences can bepassedto methods hke any data type 1nt numbers 51D15 prrnerra inunhera nnnhera referenee referenee tree puhln aeaere yora prrneLraeirner treett for irne 1 u a A t E i i ena method prrneLrae 3 Wrrnrrmnnmn ciin znrnnnl 1ength rm Systemuutpr1nt i115 1 u it reference rrnr m Com pareContrast Ster puhlre aeaere yarn awaprrraemomemenea 1nt array t rne irraeValue arrayru arrayru arrayl arraym irraeValue i end method awaprrraemomemenea awanrrraemonleneneannnhera neehod call pnhlre aeaere rner awaprrraemanlenenea rnen array t rne raytu irraeValue ar arrayru arrayl arraym irraeValue reeurn array i end method awaprrraemomemenea nnnhera awanrrraemonleneneannnhera neehod call ngtnrrcmmxe anyway J2 fi iwramr m 28 Arrays of references e Array elemmts can Conmmpnmmve dam types or referemex to ob J eats e We ve seen unrs so far as arrays ofsmn ecerngn nemeLrsc s g emquot Bubble Pat weerquot madame unkn znnnunnr 13 1 5a Multi dimensional arrays e Arrays are ob Jects Lhat contam references to ob r eats e Thus arrays can conrarn references to ouner arrays wnrcn can conrarn ouner arrays ad nausern hauleanU n renamed new haulean um mouma NunLDMS xtRamedUl xtRamedUl 3n 33E 39 Sluggencmmxcrexam cmnwremr nu TwoDimensional Arrays A woedxmensxonal array rs an array ofarrays s n can be thoughtofas havmgrows and columns a Declanng a woedxmensxonal array requrres two sefs ofbrackers and two srze declamtors each m 5 own brackets a Each elementrequlrestwo subscnptsto accessr duuhleU scores new duuhlE 4 4 Wu eaxesrnlln reuesrnmr mwr ecxesullnl amen rr m raw 2 raw 3 1 mmzzzrixzfsx mm r u Iterating through array values s Nested loops are useful tools for dealmg wrun mulhedlmenhonal arrays punan seems we punczorrsc men 1 115 r for me 10 1 lt listlength 1 r in mt en 3 lt llst1length n Systemuutpr1nt 115t1j quot V39 gt Systemuutpr1ntln gt end method perncznmsc n Wnte sumRuWO nr sumCulumnO Wrrnenaanrmnr snowman 42 Sili urremr m Accessing elements in multidimentional arrays Op aatxons on muluedlmenhonal use rnumple array rndrces e Each responses wrun une appropnare type for rnsrance mt or mt 1 HM nuleSt 1rZr3r nuleStU 345r 456 H numL15t1 numL15tZ eyscenuucperncrnumnrscrurm 1 mm z eyscenuucperncrnumnrscrl2 5 E a c Er F Systemuutpr1nt rnummecru reaezSes reaezSes e a perncrnumnrscm Systemuutpr1ntlnumL15t3 neeeyIndexoueorauunusaxceperun 3 quot n 392quotcquotquotni rri3955 3 Eililwremr nz Referencespointers in arrays publn scam yarn mnlscnan arcsr lt nncrm numnsc nncr xm lt1 Pubhl scam yarn lt9 5 a Um nnnmsc UnEU Jnscr lt y s nunLnsc e new nncram lt 115 length scrz r Syscenaucprnncrnn quotquot L s m 5quot r end necnad prnnansc nulesEU yhsc ansc e yLnsc nrnncrnsc LnulesEWN nrnncrnsc LnulesEUN nrnncrnsc rxnnscr nrnncrns Lyhscy nrnncrnsc LnulesEUN39 r end necnau nann 34 meme 2 a a a Nulleurnceeaxc epcrun J quot 2 EIZEZTE A 3 SJ ifi lwremr m Variablelength argument lists e What lfyou wrsh to make a method that calculates the average for any number ofparameters xmeanlo rorr xmeanlo15 rorr xmeanlo1545z a Many contemporary progammlng languages provrde a mechanrsm for variablesugar argument trsrs v ararg parameters uhln statue double meanllnt nulest i s The argument nulestls treated as an array oflntegers puhlre seaere double mean int must i double sun uu for 1m u 1 lt nuerse1engeh 1 i um numL15t1 l reeurn sumhumiditlength 6 yygairmoxenro rrnnrr cx 1m emmremr I75 Commandline arguments a The mam method header puhlre seaere vars narn lserrnarl arse system commandrllne 0 Java progam er testtxt arglol rf o e arg t test txtquot 1n Netbeans you can set command lrne arguments rn projectproperties Style Parallel Arrays Vs Objects Don tcreate per a St1ng naneLrse a o ByparallelwemeanthatnameLlStDnumL15t nand costL15tD all contarn data forthe same rnventory rtem Instead use objects to goup related data rtems cs 241 l nunrre class In enearyreen t serrns nane rne nunner double case i ena class rnveneary reen Inveneor Itemll anveneor Last E 39 Err nrrzrwnrxers rrnnrs 177 x an x x m Exercises s Create a copy ofa Zrdlmentlonal array 0 ort a LI and LD arrays usrng selectron sort 7 Search for the mlnlmum value ln the data structure 7 Swap thrs valuewrth the value rn the lowest unsortedposrtron 7 Move to the next posrtron and repeat a Selectlon Bubble sort 2 search for posrtron 0 mm value 2 swap wrth to e 2 5 lo 7 search forposrtronlmrn value5swap wrth5 e 2 5 lo 7 search forposltlon 2 mm value7 swap wrth to e 2 5 7 to final position reached 2 mammzriest sxs Salem m Array of Objects Diagram Revisited Using objects simple data structures opaauuns un array data Wrapper classes The ArrayLrst elass Hashes Copying array elements e Suppose we wantto move a sectlon ofan array 7 To make room for a new element Oreo e We could vvnte the code ourselves uslng a for loop c 1nsteadwecanuseamethodln e ystemclass Systemaxxaycapyt fmmL E cranSeerc cause eaSeerc eaune l Growing an array e Suppose your anay 15 full but you need room for one more element a 2 Copy extstlng elements tothlsnew anay Systemauaycapyt meme u eennmse u menselenem l e 3 Maketheoldvanablerefertothenew ngsr cemlesc j 39 Hnncmmxecmmmmr Emu x 132 ArrayList methods Addlng elements 7 Method add object adds the objectrefaence to the end 7 Method add lndex object lnsets an objectrefaence before the lnto the speclfled posltlon all suhsequmt uh eets have the lndleesupdated accnrdmgly 7 Method setlndex object overwntes an enstlng object 5 gt1 Remevlng e emen 7 Method get lndex returns the objectrefermce te thls lsa genene abjedrefermce andmusthe type msttu he used e2 Removmg elements 7 Method remove lndex removes an objectrefermce from the AmyLlst o Checklng slze K quot 392 Emi i 5 3 3 EilCEwremr m anayname lndex 22 m zzlsx mam m Array Lists a The ArrayLlst class tn the Java API ls slmllarto an array but lt does not store prlmltlve data types as elements 7 ArrayLlst data structures store any Objectusmg a genenc data type 7 AnAmyLlchanhold objectsofdlfferenrtypest e ArrayLlst datastrucmresprovlde the followlng abstractlonsfeatures e d an e ement The ArmyLlst Object automatlcally expands as ltems are added to lt 7 Remove an element The ArrayLlst objectautomaucally reduces as ltems are removed from lt nee avaut11ArrayLlst Arr L15 nememse new ArrayLlstt quoton no em nenemse eddl new senngl Bub mum OBJECTS na ELlSt ad t n ngt Pat nameLlstaddt new Strung Aprll tr g name lseung eeeuunesgeel u quoton Typecasuuol 1 mmzzzzzzri1 sx mum m Traversrng an ArrayLIst m 1 e 1 e 1 lt nameLsleEt 1H1 lt Stung name 7 Sunny nameLlscgect 1 l entanglement enactment w W a l 1m 1 u 1 lt shapeLsrszEH 1H t Shape emanate e temper snapemmeel l Shape amp 42 mxzzuilssx Salem ms Style ArrayLists If an arrayLlst only hold objects of a smgle objecttype then lt should be strongly typed 7 strongly typed data structureshelp reduce errorsl e AmyLlchanbeused as apa meterlzedclaxx Aeeeymselteeunggt nememse n w Aeeeymseweungm If an anayLlst has an expected slze provlde a clue to lts slzeby settlng lts lnltlal capaclt e The Size ls sull dynamlc e Helps ereaderunderstandthescopeoftheanayLlst e Increasesmemory ef clency 7 Default lnltlal capaclty ls lo Aeeeymselteeunggt nemenls new Aeeeymselteeunggtrsu J quot 2 EIZ ZTE A 3 SJ ifi lwremr 1x5 31 Wrapper Classes o Java 15 not completely objecte W onented a Tthas pnmrtrve data types aswell as m Mega objects long Long Java prov ldes wrappersquot whlch shod Sheri creates objects rnstead ofvarlables byte Byte There are wrapper classes for all 8 prrrnrtrve types oat Float Allhave the same name wth double Double cap rtal letter fully spelled out note Integer and character char character boolean Boolean 13 warmerser mlwn znnn nnr m Wrapper Diagram Double ol new Double 157E Systemuutpr1ntln ol 157E olouble olvel ololoublevelue Wrapping boxingunboxing creeee ehe Arreyllse ArreyLlse ol deeeeolol new Double 3l4 ta 7 new ArrayL15t0 buxlng 314 deeeeolol new Double 272 boxlng 272 Deerleve elemene D lneo Double duh olouble olvel or you can replace ehe last 2 llnes ebove olouble olvel duh oloubl evelue o a prlnuelve eype ln Double dataget n unboxlng 2 seeps Db eee w h Double dataget n oloubleVelue 1 Wynn4rerme panama 189cm m Wrapper class methods e evvrapper e Exam oloubl C r ommon classeshave a numberofhlghly useful methods for deallng types useful ls are theparse rneth of a pnmrtrve value rnto the pnmrtrve value Th vvrth Lhelr subject data 0 We ve already rntroduced some such as character rsDrgrto character rsUpperca e e Oneofthemost representatron e P serlng lnpueVolue 12356 D ubleperseDouble lnpueVolue ofthe wrapper class predrcate methods ods whlch turn a strrng o Wrapper classes are a good place to look for methods to perform tasks 3 womewmw cslwn znrnunnl m are quot3 2 3 meme m AutoboxingAuto unboxrng Wlth currentversrons ofJava 5 0 the compllerwlll automatrcally convert boxunbox from prrmatrve data types to wrapped objects creoee ehe ArreyllseltDoublegt eeeeyrleeeoeoblee am e new eeeeyrleeeoeobleeo Add elemenes as oloubles v13 oueoeboxlng dataaod 314 dataaod 272 Deerleve elemene D as double v13 eueoeunboxlng oeobre x e aeeeeeu o l m I 310rmwxe eyequot mint x m StringBuilder Class The stnngBullder class 15 to stnngswhatthe ArmyLlchlass IS to Arrays o strrngBullder lspart othe default APT no rmport statement lsneeded e nae eeemeeouaee heme e new eeemeeouaee neemeo heme speeea n We 0quot ln ex nameln f quotDoomquot lnolex 7 heme meeee aex quotE v heme eeereee ml or nolex nomelnoexof quot PhDquot lnolex 16 nemeoleleee lnolex 1ndex PhDquotlength 1 eyeeemeoeeemere heme m 3 quot 7 tquotequotquotni ri39fe 3 Saleem 192 32 Hashmaps A map ls a collectron ofkeys and Vduex 1t ls much llke an lndlces from o e utwrth wrthouttherequrrementofusrng rnteger Lo slzerl A hash ls a one way to organrzermplement a map more isvautilHashMap HashMaplt tr1ng tr1nggt phone uu new Hasmaplt tr1ng scunggtm phone uukput quotTrans omquot quot937 7757mmquot phone uukput quotc551 Offlcequot quot937 77575133quot Systemuutpr1ntln phone uukget quotTrans DDDmquot 13 WSZ M ZZZESEYA SSEJTE 5331 remr m Wait there s more In C3241 look forward to e Objectrorlented desrgd e Dlalogboxes and other GUI features 7 Us of asserts unrt testrng and other error detectron features 7 Advanced debugglng and the st Many many new classes methods and objecttypes thatwrll help you deal wth complamy 1 r3 aquotf lquotl i rri39l lquot Ziliiarremr 195 Tokenizing Strings e Splrttrng a erlng rnto rts components tokens Wee meantsemarakemee em a ates quotWNWquot see narakemee memes crrngToken enscuuntTuke ens nexeTokenl 3 ng day 7 dateTukens nextTu enl ng yea 7 date tTukEn l day Integertutr1ng lxncege date month quotequot day quotw Systemuutpr1ntlnldate a mommnwu ct bpnnmmmr seperated by delrmrnators ls a necessary step m the processlng ofmost data uerldace quot7quot ns l rparselnt lday 1 year m System exit Thls method call rmmedrately ends the executron othe progam wth the return call 0 e o lmplles all ls well 7 otheryaluesrepresmtpossrbleerrorcodes Hopefully we ve reached Systemex1t El m m 33


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Anthony Lee UC Santa Barbara

"I bought an awesome study guide, which helped me get an A in my Math 34B class this quarter!"

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.