STRING
length()
returnsanint,thelengthof
thestring.
indexOf(Stringsub)
indexOf(Stringsub,intoffset)
returnstheindexofthefirst
occurrenceofthesubstring
(sub)inthegivenstring.ifan
offsetisprovided,thenreturns
theindexofthefirst
occurrenceaftertheoffset.
Ifthestringisnotfound,
returns1.
charAt(intindex)
returnsthecharacterat
positionindexinthestring
substring(intstart,intend)
substring(intstart)
returnsasubstringstarting
fromindexstart(inclusive),up
toindexend(exclusive).if
justthestartintegeris
provided,thenreturnsthe
substringfromthestartindex
totheendofthestring.
compareTo(Stringother)
ifthisstringcomesbeforethe
otherStringinthedictionary,
returnsa1.iftheyareequal,
0.ifthisstringcomeslater,
1.
toUpperCase()
toLowerCase()
returnsastringthathasbeen
madeeitherallcapsorall
lowercase
Stringword1=whatever
Stringword2=abcdabc
word1.length()>8
word2.indexOf(abc)> 0
word2.indexOf(abc,1)>4
word2.indexOf(z)>
1
word2.indexOf(d,4)> 1
word1.substring(1,3)>ha
word2.substring(3)>dabc
word1.charAt(0)>w
word1.charAt(40)>Exception
word1.compareTo(word2)>1
word2.compareTo(word1)>1
word2.toUpperCase()>ABCDABC
CHARACTER
Allmethodsarestatic.Anycharactersyouaredealingwithare
passedinasarguments,neverdereferenced.
{
//YouCANNOTdothis:
charx=a
x.isDigit()
//Insteadyoudothis:
charx=a
Character.isDigit(x)
}
Character.isDigit(charch)
returnstrueif09,false
otherwise
Character.isUpperCase(charch)
Character.isLowerCase(charch)
returnstrueifuppercase
returnstrueiflowercase
Character.isWhitespace(charch)
returnstrueifwhitespace
(spaces,tabs,newlines,etc.)
Character.isLetter(charch)
Iwonderwhatthisdoes
Imnotgonnademonstratethese,toosimple.
MATH
Allmethodsarestatic.Themathclasscannotbeinstantiated
(privateconstructor).Servesasalibraryofusefulfunctions
Math.sin(doublearg)
sinfunction,returnsdouble
Math.pow(doublebase,double
exp)
returnsadouble,thebase
raisedtotheexppower.
Math.random()
returnsarandomdoublefrom0
(inclusive)to1(exclusive).To
generatearandomintegerfrom0
ton,use
(int)(Math.random()*n)
Makesureyouapplythe(int)
casttothewholeexpression,
andnotjustMath.random(),
otherwiseyournumberwill
alwaysbezero.:/
Math.max(doublea,doubleb)
Math.max(inta,intb)
Math.min(doublea,doubleb)
Math.min(inta,intb)
returnsthelargerofthetwo
returnsthesmallerofthetwo
Theyworkexactlyasyouexpectthemto.
ARRAYLIST
Ifyouredealingwithlists,orarrays,then,ifyouunderstand
them,arrayListsareverydope.Theymakelifeeasier.However,they
cannotholdprimitivetypes,theycanonlyholdObjects(object
referencesthatis,theydontstoretheactualobject,butjuststore
areferencetoanobject.Areferenceisjustlikeanaddressof
wheretheobjectsactualinformationisstored).Example:
importjava.util.ArrayList
//ArrayListhastobeimported
ArrayListlist=newArrayList()
list.add(Hello)
list.add(newSquare())
list.add(newScanner())
//thistypeofcomboofelementswould
probably
never
exist,butit
canexist
Ifyouredealingwitharrays,andifwhenyoureinitializingthe
array(makingthearrayvariable)youdontknowhowmanyelements
youwillhave,thisiswhenyouuseanArrayList.
YoucanalsoparametrizeanArrayList,tomakeitsothatitcanonly
holdacertaintypeofObject.Example:
ArrayList<String>words=newArrayList<>()
words.add(hey)
words.add(yerr)
words.add(newObject())>compilererror
add(Objecto)
addstheobjecttotheArrayList
size()
returnsthesizeofthe
ArrayList(howmanyelementsare
init)
get(intindex)
returnstheelementatthe
specifiedindex
contains(Objecto)
returnstrueifObjecto(oran
identicalobjectaccordingto
theequalsmethod)isfoundin
theArrayList
indexOf(Objecto)
returnstheindexatwhichthis
objectisfound,1ifnot
found.
set(intindex,Objectelement)
setsthegivenindextothe
givenobject(ifthereisalready
anobjectthere,replacesit)
remove(Objecto)
removestheObjectofromthe
ArrayList,returnstrueif
successfullyremoved.
remove(intindex)
removestheObjectfoundatthe
givenindex.returnstheobject
removed.
ARRAYS
(CLASS)
Arraysisausefulutilityclass,similartotheMathclassinthat
allitsmethodsarestaticandthatitcannotbeinstantiated.
Like,ArrayList,ithastobeimported.
importjava.util.Arrays
AllofthemethodsintheArraysclassworkforanytypeofarray.
(notArrayListsthough!donotconfusethem)Themostusefulofthem
istheArrays.sort()method.
HereIuseint[]asparameters,butanyarraycanbeused,like
double[],boolean[],Object[],etc...
Arrays.sort(int[]arr)
sortsthearrayinplace(does
notreturnanything),byusing
eitherprimitivecomparisonor
theobjectscompareTomethod.
Theobjectmustimplementthe
Comparableinterfaceinorder
foranarrayofthattypeof
ObjecttobesortedbyArrays.
Arrays.copyOf(int[]arr,int
size)
returnsacopyofthisarray,of
thespecifiedsize.Ifyouwant
tomakeyourarraybiggerand
addmoreitemstoit,thisis
useful.
Arrays.toString(int[]arr)
returnsaStringrepresentation
ofthearray,printingallof
itselementsinaneatfashion.
Arrays.equals(int[]arr1,int[]
arr2)
returnstrueifthearraysare
equal.Theyareequalifand
onlyiftheyarethesamesize,
andcontainthesameelementsin
thesameorder.
OBJECTSANDCLASSES(ObjectOriented
Programming)Overview
InJava,thereareTWOmaintypesofinformationprimitivetypes,
andobjects.Primitivetypesincludeintegers(ints),floats,
doubles,booleans,longs,shorts,bytes,andcharacters(chars).One
interestingthingtonote,howeverallofthesedifferentprimitive
typesarejustdifferentwaysofstoringthesamethingnumbers.In
theendeverythingisjustmadeofbits,just1sand0s.Thebits
themselvesarentasimportantashowyoudecidetotreatagiven
groupofbits.
Beforeunderstandingobjects,andhowtheyaredifferentfrom
primitivetypes,itisbesttofirstunderstandprimitivetypes.
Essentially,allconcreteinformationinanyprogramiseventually
storedinprimitivedata.Forexample,eventhoughStringsare
objects,theinformationinastring(aword,forexample,
information),isjustactuallyanarrayofcharacters{i,n,
f,o,r,m,a,t,i,o,n},andwhatare
characters?Charactersareactuallyjustintegers,andwhenprograms
communicatewiththegraphicaluserinterface,theysimplylookup
pixelcoordinateinformationforaspecificcharacterinalookup
table,andthenorganizethosepixelsonthescreentoseethe
lettersyourereading.So,informationisreallyjust{105,110,
102,111,114,109,97,116,105,111,110}...andtogoonestep
further,allASCIIcharacters(thesimpletextencodingmostofthe
webuses(wellatleastusedtouse)),canberepresentedbyjust8
bits,allowingfor128differentcharacters(27
),soinformationis
justastringofbitsinaspecificplaceinmemory,andweonlyknow
itsastringbecausewehaveanaddressthatpointstothefirst
letter,andweknowthelengthofthestring.Soinformationis
actuallyjust011010010110111001100110011011110111001001101101
0110000101110100011010010110111101101110Iseparatedthebytes
withspacesforclarity.
Objectsallowformeaningfulorganizationofprimitivedata.Objects
canpossessinstancefields,whichdescribecharacteristicsofthe
Object(andbywhichdifferentobjectscanbecompared),andObjects
canalsodothings(methods)withthoseinstancevariables,
with/withoutadditionalinputs(externallypassedinmethod
arguments).Thismakesiteasiertoassociatecertainsetsof
informationwitheachother,andtoalsohouserelevantprocedures
operatingonthatinformationtogether.
Forexample,letssaythatweliveinaprogrammingworldwithout
objects.Allyouhaveareprimitivetypes(althougharraysare
objectsinjava,forthisexamplewewillassumethataprimitive
versionofthemareincludedinourprimitiveworld,andthatwehave
accesstoStrings,eventhoughtheyareObjectstoo.(for
simplicityssake)).
Quickquestionwhatisthepurposeofprogramming?tosolve
problems.Letsthinkofanexampleofarealworldproblemwewant
tosolve.
Letssaywehave100studentsenrolledinauniversity,andthat
thereisaconcertthatisupcoming.Studentsareallowedtobuy
ticketsthroughanonlineinteractivesystem,thatyouaretodesign.
Becauseweareinafullyprimitiveworld,andwearetacklingan
intuitivelyobjectorientedtask,thisissomewhatofanightmare.
Therulesyoursystemwillfollowareassuch:studentscanonlybuy
aticketiftheyareonthelistofstudentswithreservedtickets,
andonlyiftheyhaveenoughmoneyontheirwolfiewallettopayfor
aticket(canonlypaywithwolfiewallet).Ticketsare$5.50.There
isalimitofoneticketperstudent.Studentshavethefollowing
informationassociatedwiththem,their9digitStonyID#,their
wolfiewalletbalance,andwhethertheyhavealreadyboughtaticket
ornot.
<Whatdoyouthinkthedatatypesofthesefieldswouldbe?>
Youwanttoprovidetheuserwiththefollowingfunctionality:your
programpromptstheuserforaStonyID#,andifthestudentmeets
allofthecriteriaforthesale,thesaleismade,andthestudents
informationisupdated.Ifthesalecannotbemade,printoutthe
reason(s).
SohowdowedothiswithoutObjects?Iknowyouarealready
squirmingwiththedesiretomakeaStudentclass,createthe
appropriatefields,andimplementthenecessarymethods,butwelive
inaprimitiveworld
Inarealworldproblemlikethis,youwouldprobablybeprovided
withthestudentsinformationintheformofatextfile,whichyou
wouldhavetoparseandputintoavirtualdatabase(arraysofinfo).
Forsimplicityssake,wewillassumetoyouhaveavailabletoyou
threearrays:
publicint[]ids
publicdouble[]balances
publicboolean[]hasTickets
Eachofthesearraysisofsize100,andanyparticularindexfrom
099referstoonestudent(Thestudentwhoseidnumberisfoundin
ids[24],hasabalanceofbalances[24],andwhethertheyboughta
ticketishasTickets[24]).
Letswriteamethod,eligibleForSale(intid),thatreturnstheindex
ofthestudentiftheiridisfound,1otherwise.
publicinteligibleForSale(intid){
intindex=1
//notethatwecantuseids.lengthbecauseour
//arraysareprimitive
for(inti=0i<100i++){
//ifwehavefoundtheindexofthestudent
//withthematchingidnumber,
//savetheindexandbreakoutoftheloop
if(ids[i]==id){
index=i
break
}
}
//ifindexisstill1thereisnosuchstudent
if(index==1){
System.out.println("StudentwithID:"+id+"not
found")
return1
}
if(hasTickets[index]){
System.out.println("Studentalreadyhasaticket.")
return1
}
if(balances[index]<5.50){
System.out.println("Studenthasinsufficientfunds.")
return1
}
//ifeverythingchecksout,theyareeligible
returnindex
}
Nowthatwecandeterminewhetherastudentiseligibleforasaleor
not,letswritethemethodthatupdatesourinformation.
publicvoidmakeSale(intindex){
balances[index]=5.50
hasTickets[index]=true
}
Finally,letswriteamainmethodinwhichweprompttheuserforan
IDandattempttomakeasale.Sincereadinginfromtheuserwithout
theuseofaScannerisaprocessbeyondthescopeof114,welluse
aScanner(anotherthingwejustcantdowithoutobjects).
publicstaticvoidmain(String[]args){
java.util.Scannersc=newjava.util.Scanner
System.out.println(EntertheStudentsID:)
intid=sc.nextInt()
intindex=eligibleForSale(id)
if(index!=1)
makeSale(index)
}
Sooursimplelittleprogramiscomplete.Ifwewantedtoaddmore
features,suchasalsostoringstudentsnames,beingabletofind
thembyname,beingabletosellthemmorethanonetypeofticket,
beingabletoremovethemfromthelistoraddthemtothelist,it
iseasytoseehowourlittleprogramwouldntbetoosimpleanymore.
Objectorientedprogramminghowever,wouldhelpmakeitsimpleagain.
YouwillrewritetheprogramusingObjects,andimplementthree
classes:Student,Ticket,andSBUTicketOffice.
ImplementanencapsulatedStudentClass,andgiveitthefollowing
fields:thenameofthestudent,theirage,theirwolfiewallet
balance,theirmealplanbalance,theamountofjudicialwriteups
theyhave,andwhatticketstheyhavebought(Astudentcanhaveno
morethan3).
Writegettersandsettersforallthemethods.
WriteamethodisEligible()thatreturnsfalseifthestudenthas
threeormorewriteups,trueotherwise.
ImplementanencapsulatedTicketclass,withthefollowingfields:
thenameoftheperformer,andthepriceoftheticket,theamountof
ticketssoldofthistype,theamountofticketsleftofthistype,
andastaticvariablethatrepresentsthetotalamountoftickets
sold(foranyperformer).
Makeaconstructorthattakesinthenameoftheticket,theprice,
andtheamountavailable.
Writegettersandsettersforallprivatemethods.
WriteamethodgetSales(),thatreturnsthecurrentrevenuegenerated
bysalesofthisticket.
Writeamethodsell(),whichupdatestheamountofticketssold,
ticketsleft,andofallticketssold.
ImplementanSBUTicketOfficeclass,whichwillactasthedriver
class(willhaveamainmethod).Itwillstorealistofmaximum100
students,andwillstorealistof6tickets(thereare6different
types).
Inthemainmethod,youwillreadinformationfromtwofiles
tickets.txtandstudents.txt.Theticketsfilestoresabout
differenttickets,oneticketperline,inthisformat:
PerformerName,Price,AmountAvailable(allvaluesseperatedby
commas).
Example:
SuicideSilence,55,10
Studentswillstoreinformationaboutdifferentstudents,onestudent
perline,inthisformat:
StudentName,Age,WolfieWalletBalance,MealPlanBalance,
Writeups,AmountofTickets,Ticket1,Ticket2,...
JeremyJones,20,62.35,43.50,0,3,Panic,Tyson,Usher
BummieBum,65,0,0,3,0
Ifyouwanttoreadfromafileyoucandoitlikethis:
try{
Scannersc=newScanner(newFile("filename.txt"))
Stringline
while(sc.hasNext()){
line=sc.nextLine()
//linecontainslinefromfile
}
}
catch(Exceptione){
System.out.println("Filenotfound.")
}
Youwillthelistofstudentsandlistofticketswithinformation
youreadfromthesefiles.
Also,implementthesestaticmethods:
findStudent(Stringname),whichlooksthroughthelistofstudents
andreturnsareferencetotheStudentwiththegivenname.
findTicket(Stringname),whichlooksthroughthelistofticketsand
returnsareferencetotheTicketwiththegivenname.
makeSale(Studentstudent,Ticketticket)thatattemptstosellthe
studenttheticket,andifsuccessful,returnstrue,returnsfalse
otherwise.Inorderforastudenttobuyaticket,theyhavetobe
eligible,theycanthaveaticketofthattypealready,theycant
havemorethan3tickets(theycanonlyhaveupto3tickets),and
theyneedenoughmoneytopayfortheticketwithwolfiewallet.If
theydonthaveenoughintheirwolfiewallet,theycanusetheir
mealplan,butitwillcosttwiceasmuch.
totalTicketsSold(),whichreturnsthetotalamountofticketssold.
totalRevenue(),whichreturnsthetotalrevenuefromallticket
sales.
Arethereanyothermethodsthatyouthinkmightbenecessarythat
aremissingfromthelistsIhavegivenyou?Tacklethisprogramming
problemandplayaroundwithittoseeifitworksasyoudexpect.
Strings:
YoucouldmakedowithoutusingtheStringclass,andinsteadof
makingStringx=abc,initializechar[]x={a,b,c}.You
couldstillbeabletoachievethesamethings,suchasprintthe
value,lookforacharacter,extractsubstrings,etc.Theadvantage
ofhavinganativeStringclassinJavaasopposedtojustdealing
witharraysofcharacters,liesinthemanyfeaturesoftheString
class,whichdirectlyactasatooltofacilitateprogramming.It
offersaccesstopertinentalgorithmicallyrefinedmethods(Javas
implementationsareverifiedmathematically,andarealsopartially
precompiledandoptimized),descriptivevariables(thelengthofthe
string,itshash),andspecificexceptionsforerrorhandling.
Althoughincrediblyuseful,mostoftheStringclassisrelatively
simple.
Asanexercise,andtobetterunderstandthestructureofanObject,
wewillimplementourownStringclass.
publicclassMyString{}
JavasStringclassisauniqueclass,becausesomeofits
featuresarebuiltintotheJavasyntax,suchasconcatenation,and
usingquotestodirectlyinitializeStrings,withoutusingthenew
operator.Wewillnothaveaccesstothesesyntacticalbenefits,but
wewillstillimplementafullyfunctional(forourpurposes)
version,MyString.
YouarenotallowedtouseanyStringmethods.
Wewillwantittohaveaninstancevariable
length
(thelength
ofthestring),andaninstancevariable
value
(anarrayof
characters).
Wewantittohaveadefaultconstructorthatinitializesthe
instancevariablestoanemptystring.
Wealsowantittohaveaconstructorthatacceptsacharacter
array,andinitializesthevariablesaccordingly.
Methods
length()
,returnsthelengthofthestring.
charAt(intindex)
,returnsthecharacteratindex.
substring(intstart,intend)
,returnsanewMyStringobject
containingthesubstringfromstart(inclusive),toend
(exclusive).
indexOf(MyStringms)
,returnsindexoffirstoccurrenceof
ms
in
thisMyString.1Ifnotfound.
indexOf(MyStringms,intoffset)
,returnsindexoffirst
occurrenceof
ms
,searchingstartingfromposition
offset
.
1Ifnotfound.
concatEnd(MyStringms)
,concatenates
ms
ontotheendofthis
MyString.(this+ms)
concatBeg(MyStringms)
,concatenates
ms
ontothefrontofthis
MyStringwiththis,(ms+this),andupdatestheinstance
variables.
equals(MyStringms)
,returnswhetherornotthisMyStringandms
areequal.
print()
,printsthevaluetotheconsole.
COMPOSITION,INHERITANCE,
POLYMORPHISM,ABSTRACT
CLASSES/METHODS
Somequicknotes:
Compositionwhenaclassdefinitionconsistsofotherclasses
(oritself).ImagineaclassStudent,andTeacher.EveryStudent
containsareferencetoaTeacher,andeveryTeacherhasa
referencetoanarrayofStudents.Compositiondoesnothaveto
bemutuallikethisThestudentcouldhaveareferencetothe
teacher,andtheteachercouldhavenoideawhohis/herstudents
are.
Inheritance:whenaclassinheritsfromanotherclass,usingthe
extends
keyword,assuch:
publicclassNameextendssuperClassName
Thesubclassinheritsallfields,andmethodsfromtheclass,
althoughitonlyhasaccesstothosethatarenotprivate.
Supposeasuperclasshasallprivatevariables,buthasall
publicmethods(gettersandsetters).Thisway,thesubclass
cantdirectlyaccessthefields,butcanusethesuperclasss
gettersandsetterstoaccessitsfields.
Polymorphism:hereisalinktosomeusefulnoteson
polymorphism.Youdonthavetostudythecodeindepth,just
trytogetageneralunderstandingofwhatitdoes:
http://www.sitepoint.com/quickguidetopolymorphisminjava/
AbstractClasses/Methods:AbstractclassesCANNOTbe
instantiated.Abstractclassescanhaveconstructors,butthose
constructorscannotbeusedtocreateinstancesoftheabstract
class(oritssubclassforthatmatter).Theycanonlybe
referencedintheconstructordefinitionsofconcreteclasses.
Abstractmethodsinabstractclassesarebasicallyliketodo
lists,andanysubclassofthatabstractclassMUSTeither
overridetheabstractmethodwithanonabstractimplementation,
oroverrideittodeclareitabstract(thenthatsubclassmust
beabstracttoo,andthentheSUBclassssubclasshasto
overrideitconcretely.)
SomeverygoodnotesandclearexplanationsofInheritance,
Polymorphism,Composition,AbstractClasses:
https://www3.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInhe
ritancePolymorphism.html
Itslong,butIHIGHLYrecommendyoulookthroughit,togive
yourselfabetterunderstanding.Youdonthavetostudythe
codeindepth,whatthecodeactuallydoesislessimportant
thanhowitsalltiedtogether.
RECURSION
Makesureyoucanprintstuffrecursively.
Herearesomepatternsyoushouldpractice,firstiteratively,then
recursively.Whenusingrecursion,themoremethodsyouwrite,the
easieritis(toanextent,therearediminishingreturns).
printSquare(3)
***
**
***
printSquare(5)
*****
**
**
**
*****
printSquare(6)
******
**
**
**
**
******
printspaceShip(2)
\
\\\
>>>>>
///
/
printSpaceShip(3)
\
\\\
\\\\\
>>>>>>>
/////
///
/
(assumethismethodwontbecalledwithanumbergreaterthan10cuz
itwouldntbeneat)
printNumPyramid(5)
123454321
1234321
12321
121
1
printNumPyramid(4)
1234321
12321
121
1
printNumSquare(5)
12345
23451
34512
45123
51234
tartan(3)
323
232
323
tartan(4)
4343
3434
4343
3434
diamond(3)
*
**
*
diamond(6)
**
**
**
**
**
(challenging!!!)
N(4)
NN
NNN
NNN
NN
N(5)
NN
NNN
NNN
NNN
NN