Slides of Java Programming
Slides of Java Programming
COMP231
AdvancedProgramming
By:MamounNawahdah(Ph.D.)
2015/2016
WelcometoCOMP231,
oneofthemost
interesting
programmingcourses
offeredatComputer
ScienceDepartment
9/21/2015
CourseDescription
Inthiscourse,youwilllearn
someoftheconcepts,
fundamentalsyntax,and
thoughtprocessesbehindtrue
ObjectOrientedProgramming
(OOP)
CourseDescription
Uponcompletionofthiscourse,youllbeableto:
Demonstrateunderstandingofclasses,constructors,objects,
andinstantiation.
Accessvariablesandmodifierkeywords.
Developmethodsusingparametersandreturnvalues.
Buildcontrolstructuresinanobjectorientedenvironment.
ConvertdatatypesusingAPImethodsandobjects.
Designobjectorientedprogramsusingscope,inheritance,
andotherdesigntechniques.
CreateanobjectorientedapplicationusingJavapackages,
APIs.andinterfaces,inconjunctionwithclassesandobjects.
9/21/2015
Logistics
Instructor:MamounNawahdah(Masri318)
Textbook:
IntroductionToJAVAProgramming,10th edition.
Author:Y.DanielLiang.
Publisher:PrenticeHall.
LabManual:
Title: LABORATORYWORKBOOK(COMP231)
GradingCriteria
Midterm exam
4Assignments
4Quizzes
FinalPracticalExam
Finalexam
30%
10%
15%
10%
35%
9/21/2015
SpecialRegulations
Assignments:
Allassignmentsareindividual effortsany
duplicatedcopieswillbetreatedasacheating
attemptwhichleadtoZERO mark.
Usingcodefromtheinternetwillbetreated
ascheatingaswell.
Theassignmentsshouldbesubmitted
throughRitaj withinthespecifieddeadline.
Nolatesubmissionsareacceptedevenby1
minuteafterthedeadline.
SpecialClassRegulations
Attendance ismandatory.Universityregulations
willbestrictly enforced.
Mobile:Keepitoffduringtheclass.Ifyour
mobileringyouhavetoleavetheclassroom
quickly,quietlyanddontcomeback.
Late:youareexpectedtobeintheclassroom
beforetheteacherarrival.After5 minutesyou
willnotallowedenteringtheclassroom.
9/21/2015
CourseOutline
Topics
IntroductiontoJava
ObjectsandClasses
Strings
Chapter
Chapter
10thEdition
18
9
4.4,10.10,
10.11
10
11
9th Edition
17
8
9,14
10
ThinkinginObjects
11
InheritanceandPolymorphism
MidtermExam(30%)
13
15
AbstractClassesandInterfaces
12
14
ExceptionHandlingandTextI/O
14
ExternalMaterial
JavaFXBasics
15
ExternalMaterial
EventDrivenProgramming
16
ExternalMaterial
JavaFXUIControls
FinalExam(35%)
#of
lectures
5
3
2
2
3
3
3
3
3
3
LabOutline
Lab#
1
2
3
4
5
67
8
910
11
12
Title
Quizzes
ProgramstructureinJava
StructureProgramming Revision
Methods
ArraysandObjectUse
Q1
ObjectOrientedProgramming
String
Q2
InheritanceandPolymorphism
AbstractclassesandInterfacesandTextI/O
Q3
GUI
EventDrivenProgramming
Q4
PracticalFinalExam(10%)
9/21/2015
WhyJava?
Java is a general
purpose programming
language.
11
CharacteristicsofJava
JavaIsSimple
JavaIsObjectOriented
JavaIsDistributed
JavaIsInterpreted
JavaIsRobust
JavaIsSecure
JavaIsArchitectureNeutral
JavaIsPortable
Java'sPerformance
JavaIsMultithreaded
JavaIsDynamic
12
9/21/2015
JDKVersions
JDK1.02(1995)
JDK1.1(1996)
JDK1.2(1998)
JDK1.3(2000)
JDK1.4(2002)
JDK1.5(2004)a.k.a.JDK5orJava5
JDK1.6(2006)a.k.a.JDK6orJava6
JDK1.7(2011)a.k.a.JDK7orJava7
JDK8(April15,2014)
13
JDKEditions
JavaStandardEdition(J2SE)
J2SEcanbeusedtodevelopclientsidestandalone
applicationsorapplets.
JavaEnterpriseEdition(J2EE)
J2EEcanbeusedtodevelopserversideapplications
suchasJavaservlets,JavaServerPages,andJava
ServerFaces.
JavaMicroEdition(J2ME).
J2MEcanbeusedtodevelopapplicationsformobile
devicessuchascellphones.
14
9/21/2015
PopularJavaIDEs
IDE Integrated DevelopmentEnvironment
15
ASimpleJavaProgram
//ThisprogramprintsWelcometoJava!
publicclass Welcome{
publicstaticvoidmain(String[]args){
System.out.println("WelcometoJava!");
}
}
16
9/21/2015
CreatingandEditingUsingNotePad
TouseNotePad,type:
notepadWelcome.java
fromtheDOS prompt.
17
Creating,Compiling,andRunningPrograms
18
9/21/2015
CompilingandRunningJava
fromtheCommandWindow
SetpathtoJDKbin directory
setpath=c:\ProgramFiles\java\jdk1.8.0\bin
Setclasspath toincludethecurrentdirectory
setclasspath=.
Compile:
javac Welcome.java
Run:
java Welcome
19
AnatomyofaJavaProgram
Classname
Mainmethod
Statements
Statementterminator
Reservedwords
Comments
Blocks
20
10
9/21/2015
ClassName
EveryJavaprogrammusthaveatleastoneclass.
Eachclasshasaname.
Byconvention,classnamesstartwithan
uppercaseletter.
Inthisexample,theclassnameisWelcome.
//ThisprogramprintsWelcometoJava!
publicclassWelcome {
publicstaticvoidmain(String[]args){
System.out.println("WelcometoJava!");
}
}
21
MainMethod
Inordertorunaclass,theclassmust
containamethodnamedmain.
Theprogramisexecutedfromthemain
method.
//ThisprogramprintsWelcometoJava!
publicclassWelcome{
publicstaticvoidmain(String[]args){
System.out.println("WelcometoJava!");
}
}
22
11
9/21/2015
Statement
Astatementrepresentsanactionora
sequenceofactions.
ThestatementSystem.out.println("Welcome
toJava!") intheprogramisastatementto
displaythegreetingWelcometoJava!.
//ThisprogramprintsWelcometoJava!
publicclassWelcome{
publicstaticvoidmain(String[]args){
System.out.println("WelcometoJava!");
}
}
23
StatementTerminator
Every statementinJavaendswithasemicolon
;
//ThisprogramprintsWelcometoJava!
publicclassWelcome{
publicstaticvoidmain(String[]args){
System.out.println("WelcometoJava!");
}
}
24
12
9/21/2015
ReservedWords
Reservedwordsorkeywords arewordsthathavea
specificmeaningtothecompilerandcannotbeusedfor
otherpurposesintheprogram.
Forexample,whenthecompilerseesthewordclass,
itunderstandsthatthewordafterclassisthenamefor
theclass.
//ThisprogramprintsWelcometoJava!
ProgrammingStyleand
Documentation
Appropriate Comments.
Naming Conventions.
Proper Indentation and Spacing
Lines.
Block Styles.
26
13
9/21/2015
NamingConventions
Choose
meaningful
and
descriptive names.
Class names:
CapitalizetheFirstLetterof
eachwordinthename.For
example,theclassname
ComputeExpression.
27
ProperIndentationand
Spacing
Indentation
Indenttwo spaces.
Spacing
Useblanklinetoseparate
segmentsofthecode.
28
14
9/21/2015
BlockStyles
29
ProgrammingErrors
Syntax Errors
Detected by the compiler
Runtime Errors
Causes the program to abort
Logic Errors
Produces incorrect result
30
15
9/21/2015
Elementary
Programming
By:MamounNawahdah(PhD)
2015/2016
TraceaProgramExecution
publicclassComputeArea {
/**Mainmethod*/
publicstaticvoidmain(String[]args){
doubleradius;
doublearea;
//Assignaradius
radius=20;
memory
radius
area
20
1256.636
//Computearea
area=radius*radius*3.14159;
//Displayresults
System.out.println("Theareaforthecircleofradius"+
radius+"is"+area);
}
}
2
9/21/2015
Identifiers
Anidentifier isasequenceofcharactersthatconsistof
letters,digits,underscores(_),anddollarsigns($).
Anidentifiermuststartwithaletter,anunderscore(_),
oradollarsign($).Itcannotstartwithadigit.
Anidentifiercannotbeareservedword.(See
AppendixA,JavaKeywords).
Anidentifiercannotbe true,false,ornull.
Anidentifiercanbeofanylength.
3
DeclaringVariables
int x;
//Declarextobeanintegervariable
doubleradius; //Declareradiustobeadoublevariable
chara;
//Declareatobeacharactervariable
AssignmentStatements
x=1;
//Assign1tox
radius=1.0;
//Assign1.0toradius
a='A';
//Assign'A'toa
9/21/2015
DeclaringandInitializing
inOneStep
int x=1;
doubled=1.4;
NamedConstants
final datatype CONSTANTNAME=VALUE;
finaldoublePI=3.14159;
finalint SIZE=3;
5
NamingConventions
Choosemeaningful anddescriptivenames.
Variablesandmethodnames:
Uselowercase.
Ifthenameconsistsofseveralwords,
concatenateallinone,uselowercaseforthe
firstword,andcapitalizethefirstletterofeach
subsequentwordinthename.
Forexample,thevariablesradius andarea,and
themethodcomputeArea.
6
9/21/2015
NamingConventions,cont.
Class names:
Capitalizethefirstletterofeachwordinthe
name.
Forexample,theclassnameComputeArea.
Constants:
Capitalizealllettersinconstants,anduse
underscorestoconnectwords.
Forexample,theconstantPI and
MAX_VALUE
7
NumericalDataTypes
9/21/2015
doublevs.float
Thedoubletypevaluesaremoreaccuratethanthe
floattypevalues.Forexample,
System.out.println("1.0 / 3.0 is " + 1.0 / 3.0);
IncrementandDecrementOperators
10
9/21/2015
NumericTypeConversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
11
ConversionRules
Whenperformingabinaryoperationinvolving
twooperandsofdifferenttypes,Java
automaticallyconvertstheoperandbasedon
thefollowingrules:
1. Ifoneoftheoperandsisdouble,theotheris
convertedintodouble.
2. Otherwise,ifoneoftheoperandsisfloat,theother
isconvertedintofloat.
3. Otherwise,ifoneoftheoperandsislong,theotheris
convertedintolong.
4. Otherwise,bothoperandsareconvertedintoint.
12
9/21/2015
TypeCasting
Implicit casting
double d = 3;
(type widening)
Explicit casting
int i = (int)3.0;
int i=(int)3.9;
What is wrong?
(type narrowing)
(Fractionpartistruncated)
int x = 6 / 2.0;
13
CharacterDataType
char letter = 'A';
char numChar = '4';
(ASCII)
(ASCII)
charletter='\u0041'; (Unicode)
charnumChar ='\u0034';(Unicode)
NOTE: The increment and decrement operators can
also be used on char variables to get the next or
preceding Unicode character. For example, the
following statements display character b.
char ch = 'a';
System.out.println(++ch);
14
9/21/2015
TheString Type
Thechartypeonlyrepresentsone
character.Torepresentastringofcharacters,
usethedatatypecalledString.Forexample:
Stringmessage="WelcometoJava!";
String isactuallyapredefinedclassinthe
Javalibrary.
TheString typeisnotaprimitivetype.Itis
knownasareference type.
15
String Concatenation
//Threestringsareconcatenated
Stringmessage="Welcome"+ "to"+ "Java";
//StringChapterisconcatenatedwithnumber2
Strings="Chapter"+2;//sbecomesChapter2
//StringSupplementisconcatenatedwithcharacterB
Strings1="Supplement"+'B';//s1becomesSupplementB
16
9/21/2015
ConsoleInput
YoucanusetheScanner classforconsoleinput.
JavausesSystem.in torefertothestandard
inputdevice(i.e.Keyboard).
importjava.util.Scanner;
publicclassTest{
publicstaticvoidmain(String[]s){
Scannerinput=newScanner(System.in);
System.out.println(EnterX:);
int x=input.nextInt();
System.out.println(Youentered:+x);
}
}
17
ReadingNumbersfromtheKeyboard
Scannerinput=newScanner(System.in);
int value=input.nextInt();
18
9/21/2015
Selections
By:MamounNawahdah(Ph.D.)
2015/2016
ComparisonOperators
9/21/2015
ifelse
if (radius>=0){
area=radius*radius*3.14159;
System.out.println("Theareaforthe"+
"circleofradius"+radius+"is"+area);
}
else {
System.out.println("Negativeinput");
}
CommonErrors
Addingasemicolon attheendofanif clauseisa
commonmistake.
if (radius>=0)
Wrong
{
area=radius*radius*PI;
System.out.println("Theareaforthecircleis"+area);
}
Thismistakeishardtofind,becauseitisnotacompilationerror
oraruntimeerror,itisalogic error.
Thiserroroftenoccurswhenyouusethenextlineblockstyle.
4
9/21/2015
LogicalOperators
Operator
Name
not
&&
and
||
or
exclusive or
switch Statements
switch (status){
case 0:computetaxesforsinglefilers;
break;
case 1:computetaxesformarriedfilejointly;
break;
case 2:computetaxesformarriedfileseparately;
break;
case 3:computetaxesforheadofhousehold;
break;
default:System.out.println("Errors:invalidstatus");
System.exit(1);
}
6
9/21/2015
Problem:ChineseZodiac
Writeaprogramthatpromptstheusertoentera
yearanddisplaystheanimalfortheyear.
ConditionalOperator
if(x>0)
y=1;
else
y=1;
isequivalentto:
y=(x>0)?1:1;
(booleanexpression)? expression1: expression2
9/21/2015
ConditionalOperator
if(num%2==0)
System.out.println(num+iseven);
else
System.out.println(num+isodd);
System.out.println((num%2==0)?
num +iseven: num+isodd);
9
FormattingOutput
Use the printf statement:
System.out.printf( format, items );
Where format is a string that may consist of
substrings and format specifiers.
A format specifier specifies how an item should be
displayed.
An item may be a numeric value, character, boolean
value, or a string.
Each specifier begins with a percent sign.
10
9/21/2015
FrequentlyUsedSpecifiers
Specifier
Output
Example
%b
abooleanvalue
trueorfalse
%c
acharacter
'a'
%d
adecimalinteger
200
%f
afloatingpointnumber
45.460000
%e
anumberinstandardscientificnotation
4.556000e+01
%s
astring
"Javaiscool"
11
OperatorPrecedence
12
9/21/2015
OperatorPrecedenceandAssociativity
Theexpressionintheparenthesesisevaluatedfirst.
(Parenthesescanbenested,inwhichcasetheexpression
intheinnerparenthesesisexecutedfirst.)
Whenevaluatinganexpressionwithoutparentheses,
theoperatorsareappliedaccordingtotheprecedence
ruleandtheassociativity rule.
Ifoperatorswiththesameprecedencearenextto
eachother,theirassociativity determinestheorderof
evaluation.Allbinaryoperatorsexceptassignment
operatorsareleftassociative.
13
OperatorAssociativity
Whentwooperatorswiththesame
precedenceareevaluated,theassociativity of
theoperatorsdeterminestheorderof
evaluation.
Allbinaryoperatorsexceptassignment
operatorsareleftassociative.
a b+c disequivalentto ((a b)+c) d
Assignmentoperatorsarerightassociative.
Therefore,theexpression
a=b+=c=5isequivalenttoa=(b+=(c=5))
14
9/21/2015
Loops
By:MamounNawahdah(Ph.D.)
2015/2016
OpeningProblem
Problem:
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
System.out.println("Welcome
100
times
to
to
to
to
to
to
Java!");
Java!");
Java!");
Java!");
Java!");
Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
2
9/21/2015
Introducingwhile Loops
int count=0;
while (count<100){
System.out.println("WelcometoJava");
count++;
}
dowhile Loop
do {
//Loopbody;
Statement(s);
}while (loopcontinuationcondition);
9/21/2015
for Loops
for (initialaction;
loopcontinuationcondition;
actionaftereachiteration){
//loopbody;
Statement(s);
}
for (inti=0;i<100;i++){
System.out.println("WelcometoJava!");
}
5
Note
Theinitialaction inafor loopcanbealistofzeroor
morecommaseparatedexpressions.
Theactionaftereachiteration inafor loopcanbea
listofzeroormorecommaseparatedstatements.
Therefore,thefollowingtwofor loopsarecorrect:
for (inti=1;i<100;System.out.println(i++));
for (inti=0,j=0;(i+j<10);i++,j++){
//Dosomething
}
6
9/21/2015
Note
Iftheloopcontinuationcondition inafor loop
isomitted,itisimplicitlytrue.
Thusthestatementgivenbelowin(a),whichis
aninfiniteloop,iscorrect.
Caution
Addingasemicolon attheendofthefor
clausebeforetheloopbodyisacommon
mistake,asshownbelow:
Logic Error
for (inti=0;i<10;i++)
{
System.out.println("iis"+i);
}
8
9/21/2015
Caution
Similarly,thefollowingloopisalsowrong:
inti=0;
Logic Error
while (i <10);
{
System.out.println("iis"+i);
i++;
}
Inthecaseofthedo loop,thefollowing
semicolonisneededtoendtheloop:
inti=0;
do {
System.out.println("iis"+i);
i++;
Correct
}while (i<10);
break
10
9/21/2015
continue
11
Problem:DisplayingPrimeNumbers
Problem:Writeaprogramthatdisplaysthefirst50prime
numbersinfivelines,eachofwhichcontains10numbers.An
integergreaterthan1isprime ifitsonlypositivedivisoris1or
itself.Forexample,2,3,5,and7areprimenumbers,but4,6,
8,and9arenot.
Solution:Theproblemcanbebrokenintothefollowingtasks:
Fornumber=2,3,4,5,6,...,testwhetherthenumberis
prime.
Determinewhetheragivennumberisprime.
Counttheprimenumbers.
Printeachprimenumber,andprint10numbersperline.
12
9/21/2015
Methods
By:MamounNawahdah(Ph.D.)
2015/2016
DefiningMethods
Amethodisacollectionofstatementsthatare
groupedtogethertoperformanoperation.
9/21/2015
CAUTION
Areturn statementisrequiredforavaluereturningmethod.
Themethodshownbelowin(a)islogicallycorrect,butithasa
compilationerrorbecausetheJavacompilerthinksitpossible
thatthismethoddoesnotreturnanyvalue.
Tofixthisproblem,deleteif(n<0) in(a),sothatthecompiler
willseeareturn statementtobereachedregardlessofhowthe
if statementisevaluated.
3
PassingParameters
publicstaticvoidnPrintln(Stringmessage,int n){
for(int i=0;i<n;i++)
System.out.println(message);
}
Supposeyouinvokethemethodusing
nPrintln(WelcometoJava,5);
Whatistheoutput?
Supposeyouinvokethemethodusing
nPrintln(ComputerScience,15);
Whatistheoutput?
Canyouinvokethemethodusing
nPrintln(15,ComputerScience);
9/21/2015
AmbiguousInvocation
publicclassAmbiguousOverloading {
publicstaticvoidmain(String[]args){
System.out.println(max(1,2));
}
publicstaticdoublemax(int num1,doublenum2){
if(num1>num2)
returnnum1;
else
returnnum2;
}
publicstaticdoublemax(doublenum1,int num2){
if(num1>num2)
returnnum1;
else
returnnum2;
}
}
ScopeofLocalVariables
Alocalvariable:avariabledefinedinside
amethod.
Scope:thepartoftheprogramwherethe
variablecanbereferenced.
Thescopeofalocalvariablestartsfrom
itsdeclarationandcontinuestotheendof
theblockthatcontainsthevariable.
Alocalvariablemust bedeclaredbeforeit
canbeused.
6
9/21/2015
ScopeofLocalVariables
Youcandeclarealocalvariablewiththesame
namemultipletimesindifferentnonnesting
blocksinamethod,butyoucannotdeclarealocal
variabletwiceinnestedblocks.
MethodAbstraction
Youcanthinkofthemethodbodyasa
blackboxthatcontainsthedetailed
implementationforthemethod.
9/21/2015
BenefitsofMethods
Writeamethodonceandreuse it
anywhere.
Informationhiding.Hidethe
implementationfromtheuser.
Reducecomplexity.
TheMath Class
Classconstants:
PI
E
Classmethods:
TrigonometricMethods
ExponentMethods
RoundingMethods
min,max,abs,andrandomMethods
10
9/21/2015
TrigonometricMethods
sin(doublea)
Examples:
cos(doublea)
Math.sin(0)
returns0.0
tan(doublea)
Math.sin(Math.PI /6)
returns0.5
acos(doublea)
Math.sin(Math.PI /2)
returns1.0
asin(doublea)
Math.cos(0)
returns1.0
atan(doublea)
Math.cos(Math.PI /6)
returns0.866
Math.cos(Math.PI /2)
returns0.0
Radians
Math.toRadians(90)
11
ExponentMethods
exp(doublea)
Returnse raisedtothepowerofa.
log(doublea)
Returnsthenaturallogarithmofa.
Examples:
Math.exp(1)
returns2.71
log10(doublea)
Returnsthe10basedlogarithmofa.
Math.log(2.71)
returns1.0
Math.pow(2,3)
returns8.0
pow(doublea,doubleb)
Returnsaraisedtothepowerofb.
Math.pow(3,2)
returns9.0
Math.pow(3.5,2.5)
returns22.917
sqrt(double a)
Returnsthesquarerootofa.
Math.sqrt(4)
returns2.0
Math.sqrt(10.5)
returns3.24
12
9/21/2015
RoundingMethods
doubleceil(doublex)xroundeduptoitsnearest
integer.Thisintegerisreturnedasadoublevalue.
doublefloor(doublex)xisroundeddowntoits
nearestinteger.Thisintegerisreturnedasadouble
value.
doublerint(doublex)xisroundedtoitsnearest
integer.Ifxisequallyclosetotwointegers,theeven
oneisreturnedasadouble.
int round(float x)
Return (int)Math.floor(x+0.5).
min,max,andabs
max(a,b)andmin(a,b)
Returnsthemaximumor
minimumoftwo
parameters.
abs(a)
Returnstheabsolutevalue
oftheparameter.
random()
Returnsarandomdouble
valueintherange[0.0,1.0).
Examples:
Math.max(2,3)
returns3
Math.max(2.5,3)
returns3.0
Math.min(2.5,3.6) returns2.5
Math.abs(2)
returns2
Math.abs(2.1)
returns2.1
14
9/21/2015
Therandom Method
Generatesarandomdouble valuegreaterthan
orequalto0.0andlessthan1.0
(0<=Math.random()<1.0)
Ingeneral:
15
CaseStudy:ComputingAnglesofaTriangle
Writeaprogramthatpromptstheusertoenter
thex andycoordinatesofthethreecornerpoints
inatriangleandthendisplaysthetrianglesangles.
16
9/21/2015
Arrays
By:MamounNawahdah(Ph.D.)
2015/2016
IntroducingArrays
Arrayisadatastructurethatrepresentsacollectionof
thesame typesofdata.
9/21/2015
DeclaringArrayVariables
datatype[]arrayRefVar;
Example:
double[]myList;
datatype arrayRefVar[];//Thisstyleisallowed,butnotpreferred
Example:
doublemyList[];
3
CreatingArrays
arrayRefVar =newdatatype[arraySize];
Example:
myList =newdouble[10];
myList[0] referencesthe1st elementinthe
array.
myList[9] referencesthelastelementin
thearray.
4
9/21/2015
DeclaringandCreatingin1Step
datatype[]arrayRefVar =newdatatype[arraySize];
double[]myList =newdouble[10];
datatype arrayRefVar[]=newdatatype[arraySize];
doublemyList[]=newdouble[10];
5
TheLengthofanArray
Once an array is created, its size is fixed.
It cannot be changed.
You can find its size using:
arrayRefVar.length
For example:
myList.length
returns 10
6
9/21/2015
DefaultValues
When an array is created, its elements
are assigned the default value of :
0 for the numeric data types.
'\u0000' for char types.
false for boolean types.
IndexedVariables
The array elements are accessed through
the index.
The array indices are 0based, i.e., it starts
from 0 to arrayRefVar.length1.
Each element in the array is represented
using the following syntax, known as an
indexed variable:
arrayRefVar[index];
8
9/21/2015
UsingIndexedVariables
After an array is created, an indexed variable
can be used in the same way as a regular
variable.
For example, the following code adds the
value in myList[0] and myList[1] to myList[2]:
myList[2]=myList[0]+myList[1];
9
ArrayInitializers
Declaring,creating,initializingin1step:
double[]myList ={1.9,2.9,3.4,3.5};
Thisshorthandnotationisequivalenttothe
followingstatements:
double[]myList =newdouble[4];
myList[0]=1.9;
myList[1]=2.9;
myList[2]=3.4;
myList[3]=3.5;
10
9/21/2015
TraceProgramwithArrays
publicclassTest{
publicstaticvoidmain(String[]args){
int[]values=newint[5];
for(int i=1;i<5;i++){
values[i]=i+values[i1];
}
values[0]=values[1]+values[4];
}
}
11
Initializingarrayswithinputvalues
Scannerinput =new Scanner(System.in);
System.out.print("Enter"+myList.length +"values:");
for (int i =0;i <myList.length ;i++)
myList[i]=input.nextDouble();
12
9/21/2015
Initializingarrayswithrandomvalues
for (int i =0;i <myList.length;i++)
myList[i]=Math.random()*100;
Printingarrays
for (int i=0;i<myList.length;i++)
System.out.print(myList[i]+"");
13
Summingallelements
doubletotal =0;
for(int i =0;i <myList.length;i++)
total+=myList[i];
Findingthelargestelement
double max =myList[0];
for (int i=1;i<myList.length;i++){
if (myList[i]>max)
max=myList[i];
}
14
9/21/2015
RandomShuffling
15
ShiftingElements
16
9/21/2015
Enhancedfor Loop(foreachloop)
JDK1.5introducedanewforloopthatenablesyoutotraverse
thecompletearraysequentiallywithoutusinganindexvariable.
Forexample,thefollowingcodedisplaysallelementsinthe
arraymyList:
for(doublevalue:myList)System.out.println(value);
Ingeneral,thesyntaxis:
for(elementType value:arrayRefVar){
//Processthevalue
}
Youstillhavetouseanindexvariableifyouwishtotraverse
thearrayinadifferentorderorchangetheelementsinthearray.
17
CopyingArrays
Often,inaprogram,youneedtoduplicateanarrayora
partofanarray.Insuchcasesyoucouldattempttouse
theassignmentstatement(=),asfollows:
list2=list1;
18
9/21/2015
CopyingArrays
Usingaloop:
int[]sourceArray ={2,3,1,5,10};
int[]targetArray =newint[sourceArray.length];
19
Thearraycopy Utility
System.arraycopy(sourceArray,src_pos,
targetArray,tar_pos,length);
Example:
System.arraycopy(sourceArray,0,
targetArray,0,sourceArray.length);
20
10
9/21/2015
PassingArraystoMethods
publicstaticvoidprintArray(int[]array){
for(int i =0;i <array.length;i++){
System.out.print(array[i]+"");
}
}
Invokethemethod
int[]list={3,1,2,6,4,2};
printArray(list);
21
AnonymousArray
Thestatement
printArray(newint[]{3,1,2,6,4,2});
Createsarrayusingthefollowingsyntax:
newdataType[]{literal0,literal1,...,literalk}
Thereisnoexplicitreferencevariablefor
thearray.
Sucharrayiscalledananonymousarray.
22
11
9/21/2015
PassbyValue
Foraparameterofaprimitivetypevalue,the
actualvalueispassed.
Changingthevalueofthelocalparameter
insidethemethoddoesnotaffectthevalueof
thevariableoutsidethemethod.
Foraparameterofanarraytype,thevalueof
theparametercontainsareferencetoanarray;
thisreferenceispassedtothemethod.
Anychangestothearraythatoccurinsidethe
methodbodywillaffecttheoriginalarraythat
waspassedastheargument.
23
SimpleExample
publicclassTest{
publicstaticvoidmain(String[]args){
int x=1;
int[]y=newint[10];
m(x,y);
System.out.println("xis"+x);
System.out.println("y[0]is"+y[0]);
}
publicstaticvoidm(int number,int[]numbers){
number=1001;
numbers[0]=5555;
}
}
24
12
9/21/2015
ReturninganArrayfromaMethod
publicstaticint[] reverse(int[]list){
int[]result=newint[list.length];
for(int i=0,j=result.length 1;i<list.length/2;i++,j){
result[j]=list[i];
}
returnresult;
}
int[]list1={1,2,3,4,5,6};
int[]list2=reverse(list1);
25
LinearSearch
Thelinearsearchapproachcomparesthekey
element,key,sequentially witheachelementin
thearraylist.
Themethodcontinuestodosountilthekey
matchesanelementinthelistorthelistis
exhaustedwithoutamatchbeingfound.
Ifamatchismade,thelinearsearchreturns
theindex oftheelementinthearraythat
matchesthekey.
Ifnomatchisfound,thesearchreturns1.
26
13
9/21/2015
FromIdeatoSolution
publicstaticint linearSearch(int[]list,int key){
for(int i=0;i<list.length;i++)
if(key==list[i])returni;
return1;
}
Tracethemethod:
int[]list={1,4,4,2,5,3,6,2};
int i =linearSearch(list,4);//returns1
int j=linearSearch(list,4);//returns1
int k=linearSearch(list,3);//returns5
27
TheArrays.binarySearch Method
Sincebinarysearchisfrequentlyusedinprogramming,
JavaprovidesseveralbinarySearch methodsfor
searchingakeyinanarrayofint,double,char,short,
long,andfloatinthejava.util.Arrays class.
int[]list={2,4,7,10,11,45,50,59,60,66,69,70,79};
System.out.println("Indexis"+Arrays.binarySearch(list,11));
char[]chars={'a','c','g','x','y','z'};
System.out.println("Indexis"+Arrays.binarySearch(chars,'t'));
ForthebinarySearch methodtowork,thearraymust
bepresortedinincreasingorder.
28
14
9/21/2015
SelectionSort
Selectionsortfindsthesmallestnumberinthelistandplacesit
first.Itthenfindsthesmallestnumberremainingandplacesit
second,andsoonuntilthelistcontainsonlyasinglenumber.
29
FromIdeatoSolution
for (int i =0;i <list.length;i++){
selectthesmallestelementinlist[i..listSize1];
swapthesmallestwithlist[i],ifnecessary;
//list[i]isinitscorrectposition.
//Thenextiterationapplyonlist[i+1..listSize1]
}
30
15
9/21/2015
TheArrays.sort Method
Javaprovidesseveralsortmethodsforsortinganarray
ofint,double,char,short,long,andfloat inthe
java.util.Arrays class.
Forexample,thefollowingcodesortsanarrayof
numbersandanarrayofcharacters:
double[]numbers={6.0,4.4,1.9,2.9,3.4,3.5};
java.util.Arrays.sort(numbers);
char[]chars={'a','A','4','F','D','P'};
java.util.Arrays.sort(chars);
31
main MethodisjustaRegularMethod
Youcancallaregularmethodbypassingactual
parameters.
Youcanpassarguments tomain.
Forexample,themainmethodinclassB is
invokedbyamethodinA,asshownbelow:
32
16
9/21/2015
CommandLineParameters
classTestMain {
publicstaticvoidmain(String[]s){
...
}
}
Inthemain method,gettheargumentsfrom
s[0],s[1],...,s[n],whichcorrespondstoarg0,
arg1,...,argn inthecommandline.
33
Problem:Calculator
Objective:Writeaprogramthatwill
performbinaryoperationsonintegers.
Theprogramreceivesthreeparameters:
anoperatorandtwointegers.
java Calculator 2 + 3
java Calculator 2 - 3
java Calculator 2 / 3
java Calculator 2 . 3
34
17
9/21/2015
Declare/Create2DArrays
//Declarearrayrefvar
dataType[][] refVar;
//Createarrayandassignitsreferencetovariable
refVar =newdataType[10][10];
//Combinedeclarationandcreationinonestatement
dataType[][]refVar =newdataType[10][10];
//Alternativesyntax
dataType refVar[][]=newdataType[10][10];
35
Creating2DArrays
int[][]matrix=newint[10][10];
for(int i =0;i <matrix.length;i++)
for(int j=0;j<matrix[i].length;j++)
matrix[i][j]=(int)(Math.random()*1000);
36
18
9/21/2015
Declaring,Creating,andInitializing
UsingShorthandNotations
Youcanalsouseanarrayinitializer todeclare,
createandinitializea2dimensionalarray.
Forexample:
int[][]array={
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};
37
Lengthsof2DArrays
int[][]x=newint[3][4];
38
19
9/21/2015
Lengthsof2DArrays,cont.
int[][] array={
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};
array.length
array[0].length
array[1].length
array[2].length
array[3].length
array[4].length ArrayIndexOutOfBoundsException
39
RaggedArrays
Eachrowina2Darrayisitself anarray.So,therowscan
havedifferentlengths.
Suchanarrayisknownasaraggedarray.
Forexample:
40
20
9/21/2015
Printingarrays
for(int row=0;row<matrix.length;row++){
for(int column=0;column<matrix[row].length;
column++){
System.out.print(matrix[row][column]+"");
}
System.out.println();
}
41
WhatisSudoku?
CheckingWhetheraSolutionIsCorrect
42
21
9/21/2015
MultidimensionalArrays
Occasionally,youwillneedtorepresent
ndimensional datastructures.
InJava,youcancreatendimensionalarraysfor
anyintegern.
Thewaytodeclaretwodimensionalarray
variablesandcreatetwodimensionalarrayscan
begeneralizedtodeclarendimensionalarray
variablesandcreatendimensionalarraysforn>2.
43
MultidimensionalArrays
[][][]
double
scores={
{{7.5,20.5},{9.0,22.5},{15,33.5},{13,21.5},{15,2.5}},
{{4.5,21.5},{9.0,22.5},{15,34.5},{12,20.5},{14,9.5}},
{{6.5,30.5},{9.4,10.5},{11,33.5},{11,23.5},{10,2.5}},
{{6.5,23.5},{9.4,32.5},{13,34.5},{11,20.5},{16,7.5}},
{{8.5,26.5},{9.4,52.5},{13,36.5},{13,24.5},{16,2.5}},
{{9.5,20.5},{9.4,42.5},{13,31.5},{12,20.5},{16,6.5}}};
44
22
9/28/2015
OO
Basic
Concepts
By:MamounNawahdah(Ph.D.)
2015/2016
ProblemswithProceduralLanguages
Datadoesnothaveanowner.
Difficulttomaintaindataintegrity.
Functionsarebuildingblocks.
Manyfunctionscanmodifyagivenblock
ofdata.
Difficulttotracebugsourceswhendatais
corrupted.
9/28/2015
WhatisObject?
Anobjecthasstate,exhibitssomewell
definedbehaviour,andhasaunique
identity.
Abstraction Modeling
Abstraction focusesupontheessential
characteristicsofsomeobject,relativeto
theperspectiveoftheviewer.
9/28/2015
WhatisClass?
A class represents a set of objects that share
common structure and a common behavior.
A class is a blueprint or prototype that
defines the variables and methods common to
all objects of a certain kind.
ClassAccess
9/28/2015
ClassAccesscont.
ClassAccesscont.
9/28/2015
ClassAccesscont.
InitializationofObjects
Constructors ensurecorrectinitializationofalldata.
Theyareautomaticallycalledatthetimeofobject
creation.
Destructors ontheotherhandensurethedeallocation
ofresourcesbeforeanobjectdiesorgoesoutofscope.
9/28/2015
LifecycleofanObject
AnatomyofaClass
9/28/2015
Encapsulation
Encapsulation
Encapsulationisusedtohideunimportant
implementationdetailsfromotherobjects.
Inrealworld
Whenyouwanttochangegearsonyour
car:
Youdontneedtoknowhowthegear
mechanismworks.
Youjustneedtoknowwhichleverto
move.
9/28/2015
Encapsulationcont.
Insoftwareprograms:
Youdontneedtoknowhowaclassis
implemented.
Youjustneedtoknowwhichmethods
toinvoke.
Thus,theimplementationdetailscan
changeatanytimewithoutaffecting
otherpartsoftheprogram.
Inheritance
Extending thefunctionalityofaclassor
Specializing thefunctionalityoftheclass.
9/28/2015
Inheritancecont.
Subclasses:asubclassmayinherit
thestructureandbehaviourofits
superclass.
MultipleInheritance
Oneclasshavemorethanonesuperclass.
Horse
Eagle
Flying Horse
9/28/2015
MultipleInheritancecont.
Ambiguity inmultipleinheritance:
Polymorphism
Polymorphism referstotheabilityofanobject
toprovidedifferentbehaviours(usedifferent
implementations)dependingonitsownnature.
Specifically,dependingonitspositioninthe
classhierarchy.
drawShape (classShape)
10
10/3/2015
Objects
&Classes
By:MamounNawahdah(Ph.D.)
2015/2016
OOProgrammingConcepts
Object-oriented programming (OOP) involves
programming using objects.
An object represents an entity in the real world that
can be distinctly identified.
For example, a student, a desk, a circle, a button,
and even a loan can all be viewed as objects.
An object has a unique identity, state, and
behaviors.
The state of an object consists of a set of data fields (also
known as properties) with their current values.
The behavior of an object is defined by a set of methods.
2
10/3/2015
ObjectsandClasses
An object has both a state and behavior.
The state defines the object, and the behavior
defines what the object does.
Classes are constructs that define objects of the
same type.
A Java class uses variables to define data fields
and methods to define behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are
invoked to construct objects from the class.
3
ObjectsandClassescont.
10/3/2015
Classes
UMLClassDiagram
10/3/2015
Constructors
Constructors are a special kind of
methods that are invoked to construct objects.
Circle(){
}
Circle(doublenewRadius){
radius=newRadius;
}
7
Constructorscont.
A constructor with no parameters is referred to as
a no-arg constructor.
Constructors must have the same name as the
class itself.
Constructors do not have a return typenot even
void.
Constructors are invoked using the new operator
when an object is created.
Constructors play the role of initializing objects.
8
10/3/2015
CreatingObjectsUsingConstructors
newClassName();
Example:
newCircle();
newCircle(5.0);
9
DefaultConstructor
A class maybe defined without constructors.
In this case, a no-arg constructor with an
empty body is implicitly declared in the class.
This constructor, called a default
constructor, is provided automatically
10/3/2015
DeclaringObjectReferenceVariables
Toreferenceanobject,assigntheobject
toareferencevariable.
Todeclareareferencevariable,usethe
syntax:
ClassNameobjectRefVar;
Example:
CirclemyCircle;
11
Declaring/CreatingObjectsinaSingleStep
ClassNameobjectRefVar =newClassName();
12
10/3/2015
AccessingObjectsMembers
Referencingtheobjectsdata:
objectRefVar.data
e.g.,myCircle.radius
Invokingtheobjectsmethod:
objectRefVar.methodName(arguments)
e.g., myCircle.getArea()
13
ReferenceDataFields
Thedatafieldscanbeofreferencetypes.
Ifadatafieldofareference typedoesnotreference
anyobject,thedatafieldholdsaspecialliteralvalue,
null.
Forexample,thefollowingStudent classcontainsa
datafieldname oftheString type.
publicclassStudent{
Stringname;//namehasdefaultvaluenull
int age;//agehasdefaultvalue0
boolean isScienceMajor;//defaultfalse
chargender;//defaultvalue'\u0000'
}
14
10/3/2015
DefaultValueforaDataField
Thedefaultvalueofadatafieldis:
no defaultvalue
toalocalvariableinsideamethod.
15
Example
Java assigns no default value to a local
variable inside a method.
publicclassTest{
publicstaticvoidmain(String[]args){
int x; //xhasnodefaultvalue
Stringy;
//yhasnodefaultvalue
System.out.println("xis"+x);
System.out.println("yis"+y);
}
}
Compilationerror:variablesnotinitialized
16
10/3/2015
DifferencesbetweenVariablesof
PrimitiveDataTypesandObjectTypes
17
CopyingVariablesofPrimitiveData
TypesandObjectTypes
18
10/3/2015
GarbageCollection
Asshowninthepreviousfigure,afterthe
assignmentstatementc1=c2,c1 pointsto
thesameobjectreferencedbyc2.
Theobjectpreviouslyreferencedbyc1 is
nolongerreferenced.
Thisobjectisknownasgarbage.
GarbageisautomaticallycollectedbyJVM.
19
TheDate Class
Javaprovidesasystemindependentencapsulationof
dateandtimeinthejava.util.Date class.
YoucanusetheDate classtocreateaninstanceforthe
currentdateandtimeanduseitstoString methodtoreturn
thedateandtimeasastring.
20
10
10/3/2015
TheDate ClassExample
Forexample,thefollowingcode:
java.util.Date date=newjava.util.Date();
System.out.println(date.toString());
displaysastringlike:
MonNov0419:50:54IST2013
21
TheRandom Class
YouhaveusedMath.random()toobtainarandomdouble
valuebetween0.0 and1.0 (excluding1.0).
Amoreusefulrandomnumbergeneratorisprovidedin
thejava.util.Random class.
22
11
10/3/2015
InstanceVariables,andMethods
Instance variables belong to a
specific instance.
Instance methods are invoked
by an instance of the class.
23
Static Variables,Constants,andMethods
Static variables are shared by all the
instances of the class.
Static methods are not tied to a specific
object.
Static constants are final variables shared
by all the instances of the class.
To declare static variables, constants, and
12
10/3/2015
Static
25
Static Variable
Itisavariablewhich belongstotheclassand
nottotheobject(instance).
Staticvariablesare initializedonlyonce,atthe
startoftheexecution.Thesevariableswillbe
initializedfirst,beforetheinitializationofany
instancevariables.
A singlecopy tobesharedbyallinstancesof
theclass.
Astaticvariablecanbe accesseddirectly by
the classname anddoesntneedanyobject.
Syntax:<classname>.<staticvariablename>
13
10/3/2015
Static Method
Itisamethodwhich belongstotheclass and not tothe
object(instance).
Astaticmethod canaccessonlystaticdata.Itcannot
accessnonstaticdata(instancevariables).
Astaticmethod cancall only other staticmethods and
cannotcallanonstaticmethodfromit.
Astaticmethodcanbe accesseddirectly bythe class
name anddoesntneedanyobject.
Syntax:<classname>.<staticmethodname>
Astaticmethodcannotrefertothisorsuper
keywordsinanyway.
mainmethodisstatic,sinceitmustbeaccessibleforan
applicationtorun,beforeanyinstantiationtakesplace.
Static example
14
10/3/2015
Static examplecont.
Followingdiagramshows,howreference
variables&objectsarecreatedandstaticvariables
areaccessedbythedifferentinstances.
VisibilityModifiers
Bydefault,theclass,variable,ormethod canbe
accessedbyanyclassinthesamepackage.
public:Theclass,data,ormethod isvisibletoany
classinanypackage.
15
10/3/2015
31
NOTE
Anobjectcannot accessitsprivatemembers,as
shownin(b).ItisOK,however,iftheobjectis
declaredinitsownclass,asshownin(a).
32
16
10/3/2015
ExampleofDataFieldEncapsulation
33
Overloading MethodsandConstructors
Inaclass,therecanbeseveralmethods
withthesamename.Howevertheymust
havedifferent signature.
Thesignatureofamethodiscomprisedof
itsname,itsparametertypesandtheorder
ofitsparameter.
Thesignatureofamethod
is not comprisedofitsreturntypenorits
visibilitynoritsthrownexceptions.
17
10/3/2015
PassingObjectstoMethods
Passingbyvalueforprimitivetype
value(thevalue ispassedtothe
parameter).
Passingbyvalueforreferencetype
value(thevalueisthereference to
theobject).
35
PassingObjectstoMethods
public class TestPassObject {
public static void main(String[]args){
CirclemyCircle =new Circle(1);
//Printareasforradius1,2,3,4,and5.
int n=5;
printAreas(myCircle,n);
System.out.println("\n" +"Radiusis" +myCircle.getRadius());
System.out.println("nis" +n);
}
/**Printatableofareasforradius*/
public static void printAreas(Circlec,int times){
System.out.println("Radius\t\tArea");
while (times>=1){
System.out.println(c.getRadius()+"\t\t" +c.getArea());
c.setRadius(c.getRadius()+1);
times;
}
}
}
36
18
10/3/2015
ArrayofObjects
Circle[]circleArray =newCircle[10];
Anarrayofobjectsisactuallyanarray
ofreferencevariables.
SoinvokingcircleArray[1].getArea()
involvestwolevelsofreferencingas
showninthenextfigure.
circleArray referencestotheentirearray.
circleArray[1] referencestoaCircleobject.
37
ArrayofObjects
Circle[]circleArray =newCircle[10];
NULL
NULL
NULL
circleArray[0]=newCircle();
circleArray[1]=newCircle();
:
circleArray[9]=newCircle();
19
10/3/2015
Immutable ObjectsandClasses
Ifthecontentsofanobject
(instance)can't bechangedonce
theobjectiscreated,theobjectis
calledanimmutable
anditsclassiscalledan
object
immutableclass.
39
Immutable ObjectsandClasses
Ifyoudeletethe publicclassCircle {
set methodinthe
private doubleradius =1;
Circle class,the
publicdoublegetArea(){
classwouldbe
immutable
returnradius*radius*Math.PI;
becauseradius is
privateandcannot publicvoidsetRadius(doubler){
radius=r;
bechanged
}
withoutaset
}
method.
40
20
10/3/2015
Immutable ObjectsandClasses
Aclasswithall private data fields
andwithoutmutators isnot
necessarilyimmutable.
Forexample,thefollowingclass
Student hasallprivate datafields
andnomutators,butitis
mutable!!!
Example
importjava.util.Date;
publicclassStudent{
privateintid;
privateDatebirthDate;
publicStudent(intssn,DatenewBD){
id=ssn;
birthDate=newBD;
}
publicintgetId(){returnid;}
publicDategetBirthDate(){returnbirthDate;}
}
publicclassTest{
publicstaticvoidmain(String[]args){
java.util.Date bd =newjava.util.Date();
Studentstudent =newStudent(111223333,bd);
java.util.Date date=student.getBirthDate();
date.setMonth(5);//Nowthestudentbirthdateischanged!
}
}
21
10/3/2015
WhatClassisImmutable?
Foraclasstobeimmutable:
Itmustmarkalldatafieldsprivate.
Providenomutatormethods.
Noaccessormethodsthatwould
returnareferencetoamutabledata
fieldobject.
43
ScopeofVariables
Thescopeofinstance andstatic variablesisthe
entireclass.Theycanbedeclaredanywhere
insideaclass.
Thescopeofalocal variablestartsfromits
declarationandcontinuestotheendofthe
blockthatcontainsthevariable.
Alocalvariablemust beinitializedexplicitly
beforeitcanbeused.
44
22
10/3/2015
ScopeofVariables
Whatistheoutput?
publicclassA{
intyear =2014;//instancevariable
voidp(){
System.out.println(Year:+year);
intyear =2015;//localvariable
System.out.println(Year:+year);
}
}
Thethis Keyword
Thethis keywordisthenameofareference
thatreferstoanobjectitself.
Onecommonuseofthethis keywordis
referenceaclassshidden datafields.
Anothercommonuseofthethis keywordto
enableaconstructor toinvokeanother
constructor ofthesameclass.
46
23
10/3/2015
ReferencetheHiddenDataFields
47
CallingOverloaded Constructor
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public Circle() {
this(1.0);
}
thismustbeexplicitlyusedtoreferencethedata
fieldradiusoftheobjectbeingconstructed
thisisusedtoinvokeanotherconstructor
24
10/17/2015
Strings
By: Mamoun Nawahdah (Ph.D.)
2015/2016
Constructing Strings
String newString = new String(stringLiteral);
String message = new String("Welcome to Java");
Since strings are used frequently, Java provides a
shorthand initializer for creating a string:
10/17/2015
Strings Are
Immutable
Interned Strings
Since strings are immutable and are
frequently used, to improve efficiency and
save memory, the JVM uses a unique
instance for string literals with the same
character sequence.
Such an instance is called interned.
10/17/2015
Example
String s1 = "Welcome to Java";
String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java";
Display:
s1 == s2 is false
s1 == s3 is true
A new
String Comparisons
10/17/2015
String Comparisons
String s1 = new String("Welcome");
String s2 = Welcome";
if (s1.equals(s2)){
// s1 and s2 have the same contents
}
if (s1 == s2) {
// s1 and s2 have the same reference
}
7
String Comparisons
compareTo(Object object)
String s1 = new String("Welcome");
String s2 = Welcome";
if (s1.compareTo(s2) > 0) {
// s1 is greater than s2
}
else if (s1.compareTo(s2) == 0) {
// s1 is less than s2
}
10/17/2015
Retrieving Individual
Characters in a String
Do not use message[0]
Use message.charAt( index )
Index starts from 0
Indices
message
W e
m e
message.charAt(0)
message.length() is 15
10 11 12 13 14
J
message.charAt(14)
10
10/17/2015
String Concatenation
String s3 = s1.concat( s2 );
String s3 = s1 + s2;
s1 + s2 + s3 + s4 + s5
same as
(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);
11
Extracting Substrings
12
10/17/2015
Extracting Substrings
You can extract a single character from a string using
the charAt method.
You can also extract a substring from a string using the
substring method in the String class.
String s1 = "Welcome to Java";
String s2 = s1.substring(0, 11)
Indices
message
+
8
message.substring(0, 11)
"HTML";
10 11 12 13 14
J
message.substring(11)
13
14
10/17/2015
Examples
"Welcome".toLowerCase()
returns a new string, welcome
"Welcome".toUpperCase()
returns a new string, WELCOME
" Welcome ".trim()
returns a new string, Welcome
"Welcome".replace('e', 'A')
returns a new string, WAlcomA
"Welcome".replaceFirst("e", "AB")
returns a new string, WABlcome
"Welcome".replaceAll("e", "AB")
returns a new string, WABlcomAB
15
Splitting a String
String s1 = "Java#HTML#Perl;
String[] tokens = s1.split( "#" , 0);
for (int i = 0; i < tokens.length; i++)
System.out.println( tokens[i] );
Displays:
Java
HTML
Perl
16
10/17/2015
expression.
"Java".matches("Java")
"Java".equals("Java")
"Java is fun".matches("Java.*")
"Java is cool".matches("Java.*")
17
10/17/2015
Finding a Character or a
Substring in a String
20
10
10/17/2015
Finding a Character or a
Substring in a String
String s = "Welcome to Java;
s.indexOf('W')
returns 0
s.indexOf('x')
returns -1
s.indexOf('o', 5)
returns 9
s.indexOf("come")
returns 3
s.indexOf("Java", 5)
returns 11
s.indexOf("java", 5)
returns -1
s.lastIndexOf('a')
returns 14
21
11
10/17/2015
23
Examples
Character c = new Character('b');
c.compareTo(new Character('a'))
returns 1
c.compareTo(new Character('b'))
returns 0
c.compareTo(new Character('c'))
returns -1
c.compareTo(new Character('d')
returns -2
c.equals(new Character('b'))
returns true
c.equals(new Character('d'))
returns false
24
12
10/17/2015
StringBuilder Constructors
26
13
10/17/2015
27
Examples
StringBuilder sb = new StringBuilder(Welcome to );
sb.append("Java");
sb.insert(11, "HTML and ");
sb.delete(8, 11) ;
// changes the builder to Welcome Java
sb.deleteCharAt(8) ;
// changes the builder to Welcome o Java
sb.reverse() ;
// changes the builder to avaJ ot emocleW
sb.replace(11, 15, "HTML") ;
// changes the builder to Welcome to HTML
sb.setCharAt(0, 'w') ;
// sets the builder to welcome to Java
28
14
10/17/2015
29
15
10/24/2015
Thinking
in Objects
By: Mamoun Nawahdah (PhD)
2015/2016
Class
Class Contract
(Signatures of public
methods and public
constants)
10/24/2015
Object Composition
Aggregation models has-a relationships and represents
an ownership relationship between two objects.
The owner object is called an aggregating object and
its class an aggregating class.
The subject object is called an aggregated object and
its class an aggregated class.
Composition is actually a special case of the aggregation
relationship.
10/24/2015
Class Representation
An aggregation relationship is usually
represented as a data field in the aggregating class.
For example, the relationship in the previous
Figure can be represented as follows:
10/24/2015
10/24/2015
Designing a Class
(Coherence) A class should describe a
single entity, and all the class operations
should logically fit together to support a
coherent purpose.
You can use a class for students, for
example, but you should not combine
students and staff in the same class, because
students and staff have different entities.
9
10/24/2015
10/24/2015
Wrapper Classes
Boolean
Character
Short
Byte
Integer
Long
Float
Double
NOTE:
(1) The wrapper classes do not
have no-arg constructors.
(2) The instances of all wrapper
classes are immutable, i.e.,
their internal values cannot be
changed once the objects are
created.
13
14
10/24/2015
10/24/2015
Conversion Methods
Each numeric wrapper class implements
the abstract methods doubleValue,
floatValue, intValue, longValue, and
shortValue, which are defined in the Number
class.
These methods convert objects into
primitive type values.
17
10/24/2015
10
10/24/2015
21
11
10/30/2015
Inheritance and
Polymorphism
Motivations
Suppose you will define classes to
model circles, rectangles, and triangles.
These classes have many common
features.
What is the best way to design these
classes so to avoid redundancy?
10/30/2015
-filled: boolean
-dateCreated: java.util.Date
+GeometricObject()
Creates a GeometricObject.
Creates a GeometricObject with the specified color and filled
values.
+GeometricObject(color: String,
filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): java.util.Date
+toString(): String
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Circle(radius: double, color: String,
filled: boolean)
+Rectangle()
+Rectangle(width: double, height: double)
+getRadius(): double
+setRadius(radius: double): void
+getArea(): double
+getPerimeter(): double
+getDiameter(): double
+getHeight(): double
+setHeight(height: double): void
+printCircle(): void
+getArea(): double
+getPerimeter(): double
Superclass
Subclass
10/30/2015
super keyword.
10/30/2015
Caution
You must use the keyword super to
call the superclass constructor.
Invoking a superclass constructors name
in a subclass causes a syntax error.
10/30/2015
Constructor Chaining
Constructing an instance of a class invokes all the superclasses constructors
along the inheritance chain. This is called constructor chaining.
Super();
Super();
Super();
10/30/2015
Defining a Subclass
A subclass inherits from a superclass.
You can also:
super.getDateCreated() +
" and the radius is " + radius);
}
12
10/30/2015
-filled: boolean
-dateCreated: java.util.Date
+GeometricObject()
Creates a GeometricObject.
Creates a GeometricObject with the specified color and filled
values.
+GeometricObject(color: String,
filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): java.util.Date
+toString(): String
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Circle(radius: double, color: String,
filled: boolean)
+Rectangle()
+Rectangle(width: double, height: double)
+getRadius(): double
+setRadius(radius: double): void
+getArea(): double
+getPerimeter(): double
+getDiameter(): double
+getHeight(): double
+setHeight(height: double): void
+printCircle(): void
+getArea(): double
+getPerimeter(): double
13
toString() {
}
}
10/30/2015
Note
An instance method can be
overridden only if it is accessible.
Thus a private method cannot be
overridden, because it is not accessible
outside its own class.
If a method defined in a subclass is
private in its superclass, the two methods
are completely unrelated.
15
Note cont.
Like an instance method, a static method
can be inherited.
However, a static method cannot be
overridden.
If a static method defined in the
superclass is redefined in a subclass, the
method defined in the superclass is
hidden.
16
10/30/2015
Overriding
17
vs. Overloading
18
10/30/2015
java.lang.Object class.
If no inheritance is specified when a class
is defined, the superclass of the class is
Object.
19
10
10/30/2015
Circle@15037e5
This message is not very helpful or informative.
Usually you should override the toString method
so that it returns an informative string representing
the object.
21
11
10/30/2015
Polymorphism
public class Demo {
public static void main(String[] a) {
m(new Object());
m(new Person());
m(new Student());
m(new GraduateStudent());
}
public static void m(Object x){
System.out.println(x.toString());
}
Method m takes a
parameter of the
Object type.
You can invoke it with
any object.
Dynamic Binding
public class Demo {
public static void main(String[] a) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Object x) {
toString()
());
System.out.println(x.toString
}
}
dynamic binding.
12
10/30/2015
Dynamic Binding
Dynamic binding works as follows:
Suppose an object o is an instance of
classes C1, C2, ..., Cn-1, and Cn, where C1 is a
subclass of C2, C2 is a subclass of C3, ..., and
Cn-1 is a subclass of Cn.
That is, Cn is the most general class, and
C1 is the most specific class.
Cn
C n-1
.....
C2
C1
C n-1
.....
C2
C1
13
10/30/2015
Generic Programming
public class Demo {
public static void main(String[] a) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Object x){
System.out.println(x.toString());
}
}
generic programming
Casting Objects
Casting can also be used to convert an object of one
class type to another within an inheritance hierarchy.
m( new Student() );
assigns the object new Student() to a parameter of the
Object type. This statement is equivalent to:
Object o = new Student(); // Implicit casting
m( o );
The statement Object o = new Student(), known as
implicit casting, is legal because an instance of
Student is automatically an instance of Object.
28
14
10/30/2015
15
10/30/2015
31
if (myObject
instanceof
Circle) {
(Circle)myObject).getDiameter()
);
}
32
16
10/30/2015
Note
The == comparison operator is used for
comparing two primitive data type values
or for determining whether two objects
have the same references.
The equals method is intended to test
whether two objects have the same
contents, provided that the method is
modified in the defining class of the objects.
34
17
10/30/2015
18
10/30/2015
38
19
10/30/2015
Shuffling an ArrayList
Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5};
ArrayList<Integer> list = new
ArrayList<>(Arrays.asList(array));
java.util.Collections.shuffle(list);
System.out.println(list);
40
20
10/30/2015
Visibility increases
private, none (if no modifier is used), protected, public
41
Accessibility Summary
42
21
10/30/2015
Visibility Modifiers
43
22
10/30/2015
Note
The modifiers are used on classes
and class members (data and
methods), except that the final modifier
can also be used on local variables in a
method.
A final local variable is a constant
inside a method.
46
23
1/2/2014
Abstract Classes
and Interfaces
By: Mamoun Nawahdah (PhD)
2013/2014
Objectives
To design and use abstract classes.
To specify common behavior for objects using
interfaces.
To define interfaces and define classes that implement
interfaces.
To define a natural order using the Comparable
interface.
To make objects cloneable using the Cloneable
interface.
To explore the similarities and differences among
concrete classes, abstract classes, and interfaces.
2
1/2/2014
1/2/2014
Abstract class
-color: String
-filled: boolean
The # sign indicates
protected modifie r
-dateCreated: java.util.Date
#Geo metricObject()
#Geo metric Object(color: string,
filled: boolean)
+getColor(): St ring
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled : boolean): void
+getDateCreated(): java.util.Date
+toString(): String
+getArea(): double
Abstract methods
are ita licized
+getPerimeter(): double
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Rectangle()
+getRadius(): double
+getWidth(): double
1/2/2014
1/2/2014
1/2/2014
Interfaces
An interface is a way to describe what classes
should do, without specifying how they should do it.
It is not a class but a set of requirements for
classes that want to conform to the interface
12
1/2/2014
What is an interface?
An interface is a class-like construct that
contains only constants and abstract methods.
In many ways, an interface is similar to an
abstract class, but the intent of an interface is to
specify common behavior for objects.
For example, you can specify that the objects
are comparable, edible, cloneable using
appropriate interfaces.
13
Define an Interface
To distinguish an interface from a class, Java uses the
following syntax to define an interface:
public interface InterfaceName {
// constant declarations;
// method signatures;
}
Example:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}
14
1/2/2014
Example
You can now use the Edible interface to specify whether
an object is edible.
This is accomplished by letting the class for the object
implement this interface using the implements keyword. For
example, the classes Chicken and Fruit implement the Edible
interface
Animal
interface.
Edible
+howToEat(): String
Fruit
Chicken
Orange
-
Apple
-
+sound(): String
Tiger
-
16
1/2/2014
Equivalent
public interface T1 {
int K = 1;
void p();
package java.lang;
public interface Comparable<E> {
public int compareTo(E o);
}
18
1/2/2014
@Override
public int compareTo(Integer o) {
// Implementation omitted
}
@Override
public int compareTo(BigInteger o) {
// Implementation omitted
}
@Override
public int compareTo(String o) {
// Implementation omitted
}
}
@Override
public int compareTo(Date o) {
// Implementation omitted
}
}
19
Examples
System.out.println( new Integer(3).compareTo( new Integer(5) ));
System.out.println( "ABC".compareTo("ABE" ) );
java.util.Date date1 = new java.util.Date(2013, 1, 1);
java.util.Date date2 = new java.util.Date(2012, 1, 1);
System.out.println(date1.compareTo(date2));
s instanceof String
s instanceof Object
s instanceof Comparable
d instanceof java.util.Date
d instanceof Object
d instanceof Comparable
20
10
1/2/2014
Extending Interfaces
Interfaces support multiple inheritance an
interface can extend more than one interface.
Superinterfaces and subinterfaces.
Example:
public interface SerializableRunnable extends
java.io.Serializable, Runnable {
...
}
11
1/2/2014
12
1/2/2014
13
1/2/2014
Examples
Many classes (e.g., Date and Calendar) in the Java library
implement Cloneable. Thus, the instances of these classes
can be cloned. For example:
Calendar calendar = new GregorianCalendar(2003, 2, 1);
Calendar calendarCopy = (Calendar)calendar.clone();
System.out.println("calendar == calendarCopy is " +
(calendar == calendarCopy));
System.out.println("calendar.equals(calendarCopy) is " +
calendar.equals(calendarCopy));
calendar == calendarCopy is false
calendar.equals(calendarCopy) is true
27
28
14
1/2/2014
}
public int getId() {
return id;
30
15
1/2/2014
house1: House
id = 1
area = 1750.5 0
wh enBuilt
1
1750.50
reference
Memory
id = 1
area = 1750 .5 0
whenBuilt
1
1750 .5 0
reference
31
Constructors
Methods
Abstract
class
No restrictions
No restrictions.
Interface
All variables
must be public
static final
16
1/2/2014
Interface1_1
Object
Interface2_2
Interface1
Class1
Interface2_1
Class2
17
11/23/2015
ExceptionHandling
and
TextIO
By:MamounNawahdah(Ph.D.)
2015/2016
RuntimeError?
11/23/2015
FixitUsinganif Statement
ExceptionHandling
Exceptionhandlingtechniqueenablesa
methodtothrow anexceptiontoitscaller.
Withoutthiscapability,amethodmust
handletheexceptionorterminatethe
program.
11/23/2015
ExceptionTypes
SystemErrors
SystemerrorsarethrownbyJVM andrepresentedinthe
Error class.TheErrorclassdescribesinternalsystemerrors.
11/23/2015
Exceptions
Exception describeserrorscausedbyyourprogramand
externalcircumstances.
Theseerrorscanbecaughtandhandledbyyourprogram.
RuntimeExceptions
RuntimeException iscausedbyprogrammingerrors,
suchasbadcasting,accessinganoutofboundsarray,and
numericerrors.
11/23/2015
CheckedExceptionsvs.
UncheckedExceptions
RuntimeException,Error andtheir
subclassesareknownasunchecked
exceptions.
Allotherexceptionsareknownaschecked
exceptions,meaningthatthecompilerforces
theprogrammertocheckanddealwiththe
exceptions.
9
UncheckedExceptions
Inmostcases,uncheckedexceptionsreflectprogramming
logicerrorsthatarenotrecoverable.
Forexample:
aNullPointerException isthrownifyouaccessan
objectthroughareferencevariablebeforeanobjectis
assignedtoit.
anIndexOutOfBoundsException isthrownifyouaccess
anelementinanarrayoutsidetheboundsofthearray.
Thesearethelogicerrorsthatshouldbecorrectedinthe
program.
10
11/23/2015
Declaring,Throwing,and
Catching Exceptions
11
Declaring Exceptions
Everymethodmust statethetypesof
checkedexceptionsitmightthrow.
Thisisknownasdeclaringexceptions.
publicvoidx()throws IOException
publicvoidy()throws IOException,OtherException
12
11/23/2015
Throwing Exceptions
Whentheprogramdetectsanerror,the
programcancreateaninstance ofanappropriate
exceptiontypeandthrowit.
Thisisknownasthrowinganexception.
throw newTheException();
TheException ex=newTheException();
throw ex;
13
ThrowingExceptionsExample
publicvoidsetRadius(doublenewRadius)
throwsIllegalArgumentException {
if(newRadius >=0)
radius=newRadius;
else
throw newIllegalArgumentException(
"Radiuscannotbenegative");
}
14
11/23/2015
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
15
CatchorDeclareCheckedExceptions
Javaforcesyoutodealwithcheckedexceptions.
Youmustinvokeitinatrycatch blockor declareto
throw theexceptioninthecallingmethod.
Forexample,supposethatmethodp1 invokesmethod
p2 andp2 maythrowacheckedexception(e.g.,
IOException),youhavetowritethecodeasfollow:
16
11/23/2015
throwsIllegalArgumentException
11/23/2015
Rethrowing Exceptions
try{
statements;
}
catch(TheException ex){
performoperationsbeforeexits;
throwex;
}
20
10
11/23/2015
Thefinally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
21
TraceaProgramExecution
try{
statements;
}
catch(TheException ex){
handlingex;
}
finally{
finalStatements;
}
Supposeno
exceptionsin
thestatements
Nextstatement;
22
11
11/23/2015
TraceaProgramExecution
try{
statements;
}
catch(TheException ex){
handlingex;
}
finally{
finalStatements;
}
Thefinalblock
isalways
executed
Nextstatement;
23
TraceaProgramExecution
try{
statements;
}
catch(TheException ex){
handlingex;
}
finally{
finalStatements;
}
Nextstatement;
Nextstatement
inthemethod
isexecuted
24
12
11/23/2015
TraceaProgramExecution
try{
statement1;
statement2;
statement3;
}
catch(Exception1ex){
handlingex;
}
finally{
finalStatements;
}
Supposean
exceptionof
typeException1
isthrownin
statement2
Nextstatement;
25
TraceaProgramExecution
try{
statement1;
statement2;
statement3;
}
catch(Exception1ex){
handlingex;
}
finally{
finalStatements;
}
Theexceptionis
handled.
Nextstatement;
26
13
11/23/2015
TraceaProgramExecution
try{
statement1;
statement2;
statement3;
}
catch(Exception1ex){
handlingex;
}
finally{
finalStatements;
}
Thefinalblock
isalways
executed.
Nextstatement;
27
TraceaProgramExecution
try{
statement1;
statement2;
statement3;
}
catch(Exception1ex){
handlingex;
}
finally{
finalStatements;
}
Thenext
statementinthe
methodisnow
executed.
Nextstatement;
28
14
11/23/2015
TraceaProgramExecution
try{
statement1;
statement2;
statement3;
}
catch(Exception1ex){
handlingex;
}
catch(Exception2ex){
handlingex;
throwex;
}
finally{
finalStatements;
}
statement2
throwsan
exceptionof
typeException2.
Nextstatement;
29
TraceaProgramExecution
try{
statement1;
statement2;
statement3;
}
catch(Exception1ex){
handlingex;
}
catch(Exception2ex){
handlingex;
throwex;
}
finally{
finalStatements;
}
Handling
exception
Nextstatement;
30
15
11/23/2015
TraceaProgramExecution
try{
statement1;
statement2;
statement3;
}
catch(Exception1ex){
handlingex;
}
catch(Exception2ex){
handlingex;
throwex;
}
finally{
finalStatements;
}
Executethe
finalblock
Nextstatement;
31
TraceaProgramExecution
try{
statement1;
statement2;
statement3;
}
catch(Exception1ex){
handlingex;
}
catch(Exception2ex){
handlingex;
throwex;
}
finally{
finalStatements;
}
Rethrowthe
exceptionand
controlis
transferredtothe
caller
Nextstatement;
32
16
11/23/2015
CautionsWhenUsingExceptions
Exceptionhandlingseparateserrorhandling
codefromnormalprogrammingtasks,thus
makingprogramseasier toreadandtomodify.
Beaware,however,thatexceptionhandling
usuallyrequiresmoretimeandresources
becauseitrequiresinstantiatinganew
exceptionobject,rollingbackthecallstack,and
propagatingtheerrorstothecallingmethods.
33
WhentoThrowExceptions
Anexceptionoccursinamethod.
Ifyouwanttheexceptiontobeprocessed
byitscaller,youshouldcreatean
exceptionobjectandthrowit.
Ifyoucanhandletheexceptioninthe
methodwhereitoccurs,thereisnoneed
tothrowit.
34
17
11/23/2015
WhentoUseExceptions
Youshoulduseittodealwithunexpected
errorconditions.
Donotuseittodealwithsimple,expected
situations.Forexample,thefollowingcode:
try{
System.out.println(refVar.toString());
}
catch(NullPointerException ex){
System.out.println("refVar isnull");
}
35
WhentoUseExceptions
isbettertobereplacedby:
if(refVar !=null)
System.out.println(refVar.toString());
else
System.out.println("refVar isnull");
36
18
11/23/2015
DefiningCustomExceptionClasses
UsetheexceptionclassesintheAPI
wheneverpossible.
Definecustomexceptionclassesifthe
predefinedclassesarenotsufficient.
Definecustomexceptionclassesby
extendingExceptionorasubclassof
Exception.
37
CustomExceptionClassExample
38
19
11/23/2015
TheFile Class
TheFile classisintendedtoprovide
anabstractionthatdealswithmostof
themachinedependentcomplexities
offilesandpathnamesinamachine
independentfashion.
Thefilenameisastring.
TheFile classisawrapperclassfor
thefilenameanditsdirectorypath.
39
File class
40
20
11/23/2015
File class
41
TextI/O
AFile objectencapsulatesthepropertiesofafileora
path,butdoesnotcontainthemethodsfor
reading/writingdatafrom/toafile.
InordertoperformI/O,youneedtocreateobjects
usingappropriateJavaI/Oclasses.
Theobjectscontainthemethodsforreading/writing
datafrom/toafile.
Thissectionintroduceshowtoread/writestringsand
numericvaluesfrom/toatextfileusingtheScanner
andPrintWriter classes.
42
21
11/23/2015
PrintWriter class
43
Scanner class
44
22
11/29/2015
JavaFX
Basics
By:MamounNawahdah(Ph.D.)
2015/2016
Motivations
JavaFX isanewframeworkfordevelopingJava
graphicaluserinterface(GUI) programs.
TheJavaFX API isanexcellent exampleofhow
theOO principleisapplied.
Thischapterservestwopurposes:
First,itpresentsthebasicsofJavaFX programming.
Second,itusesJavaFX todemonstrateOOP.
Specifically,thischapterintroducesthe
frameworkofJavaFX anddiscussesJavaFX GUI
componentsandtheirrelationships.
2
11/29/2015
JavaFX vsSwingandAWT
WhenJavawasintroduced,theGUI classeswere
bundledinalibraryknownastheAbstractWindows
Toolkit (AWT).
AWT isfinefordevelopingsimplegraphicaluser
interfaces,butnotfordevelopingcomprehensiveGUI.
Inaddition,AWT ispronetoplatformspecificbugs.
TheAWT componentswerereplacedbyamorerobust,
versatile,andflexiblelibraryknownasSwing.
Swing componentsdependlessonthetargetplatform
anduselessofthenativeGUI resource.
WiththereleaseofJava8,Swing isreplacedbya
completelynewGUI platformknownasJavaFX.
3
BasicStructureofJavaFX
Application
Overridethestart(Stage)method
Stage,Scene,andNodes
11/29/2015
Extend Application
Override start
Create a button
Create a scene
Set a scene
Display stage
Launch application
11/29/2015
11/29/2015
Panes,UIControls,andShapes
DisplayaShape
10
11/29/2015
BindingProperties
JavaFX introducesanewconceptcalledbinding
property thatenablesatargetobject tobeboundtoa
sourceobject.
Ifthevalueinthesourceobjectchanges,thetarget
propertyisalsochangedautomatically.
Thetargetobjectissimplycalledabindingobject ora
bindingproperty.
11
BindingProperties
12
11/29/2015
BindingProperty:
getter,setter,andpropertygetter
13
BindingProperty
JavaFX definesbindingpropertiesfor
primitivetypesandstrings.
Foradouble/float/long/int/boolean value,
itsbindingpropertytypeis
DoubleProperty/FloatProperty/
LongProperty/IntegerProperty/
BooleanProperty.
ForaString,itsbindingpropertytypeis
StringProperty.
14
11/29/2015
CommonPropertiesand
MethodsforNodes
TheabstractNode classdefinesmany
propertiesandmethodsthatare
commontoallnodes.
style:setaJavaFXCSSstyle
rotate:Rotateanode
16
11/29/2015
TheColor Class
17
TheFont Class
18
11/29/2015
TheImage,ImageView Class
LayoutPanes
JavaFX providesmanytypesofpanesfor
organizingnodesinacontainer.
20
10
11/29/2015
FlowPane
21
GridPane
22
11
11/29/2015
BorderPane
23
Hbox ,VBox
24
12
11/29/2015
Shapes
JavaFX providesmany
shapeclassesfordrawing
texts,lines,circles,
rectangles,ellipses,arcs,
polygons,andpolylines.
25
Text
26
13
11/29/2015
Line
27
Rectangle
28
14
11/29/2015
Circle,Ellipse
29
Ellipse
30
15
11/29/2015
Arc
31
Polygon andPolyline
32
16
12/21/2015
JavaFXUIControls
By:MamounNawahdah(Ph.D.)
2015/2016
FrequentlyUsedUIControls
Throughoutthisbook,theprefixeslbl,bt,chk,rb,tf,pf,ta,cbo,lv,
scb,sld,andmp areusedtonamereferencevariablesforLabel,
Button,CheckBox,RadioButton,TextField,PasswordField,
TextArea,ComboBox,ListView,ScrollBar,Slider,andMediaPlayer.
2
12/21/2015
Labeled
A label isadisplayareaforashorttext,anode,orboth.
Itisoftenusedtolabelothercontrols(usuallytextfields).
Labelsandbuttonssharemanycommonproperties.These
commonpropertiesaredefinedintheLabeled class.
Label
TheLabel classdefineslabels.
12/21/2015
ButtonBase andButton
Abutton isacontrolthattriggersanactioneventwhen
clicked.
JavaFXprovidesregularbuttons,togglebuttons,check
boxbuttons,andradiobuttons.
Thecommonfeaturesofthesebuttonsaredefinedin
ButtonBase andLabeled classes.
CheckBox
ACheckBox isusedfortheusertomakeaselection.
LikeButton,CheckBox inheritsallthepropertiessuch
asonAction,text,graphic,alignment,graphicTextGap,
textFill,contentDisplay fromButtonBase andLabeled.
12/21/2015
RadioButton
Radiobuttons,alsoknownasoptionbuttons,enableyouto
chooseasingleitemfromagroupofchoices.
Inappearanceradiobuttonsresemblecheckboxes,butcheck
boxesdisplayasquarethatiseithercheckedorblank,whereas
radiobuttonsdisplayacirclethatiseitherfilled(ifselected)or
blank(ifnotselected).
TextField
Atextfieldcanbeusedtoenterordisplaya
string.TextField isasubclassofTextInputControl.
12/21/2015
TextArea
ATextArea enablestheusertoenter
multiplelinesoftext.
ComboBox
Acombobox,alsoknownasachoicelistordrop
downlist,containsalistofitemsfromwhichthe
usercanchoose.
10
12/21/2015
ListView
Alistview isacomponentthatperforms
basicallythesamefunctionasacombo
box,butitenablestheusertochoosea
singlevalueormultiplevalues.
11
ScrollBar
Ascrollbar isacontrolthat
enablestheusertoselect
fromarangeofvalues.The
scrollbarappearsintwo
styles:horizontal andvertical.
12
12/21/2015
Slider
Slider issimilarto
ScrollBar,butSliderhas
morepropertiesandcan
appearinmanyforms.
13
CaseStudy:TicTacToe
14
12/21/2015
CaseStudy:TicTacToe cont.
TicTacToe
15
Media
YoucanusetheMedia classtoobtainthesource
ofthemedia,theMediaPlayer classtoplayand
controlthemedia,andtheMediaView classto
displaythevideo.
16
12/21/2015
MediaPlayer
TheMediaPlayer classplayes andcontrolsthemedia
withpropertiessuchasautoPlay,currentCount,
cycleCount,mute,volume,andtotalDuration.
17
MediaView
TheMediaView classisasubclassofNode that
providesaviewoftheMedia beingplayedbya
MediaPlayer.TheMediaView classprovidesthe
propertiesforviewingthemedia.
18
12/21/2015
EventDriven
Programming
By:MamounNawahdah(Ph.D.)
2015/2016
Proceduralvs.Event
DrivenProgramming
Proceduralprogramming isexecuted
inproceduralorder.
Ineventdrivenprogramming,codeis
executeduponactivationofevents.
12/21/2015
HandlingGUIEvents
Sourceobject(e.g.,button)
Listenerobjectcontainsamethodfor
processingtheevent.
Events
Anevent canbedefinedasatypeof
signaltotheprogramthatsomething
hashappened.
Theeventisgeneratedbyexternal
useractionssuchasmouse
movements,mouseclicks,or
keystrokes.
4
12/21/2015
Event Classes
EventInformation
Aneventobjectcontainswhateverpropertiesare
pertinenttotheevent.
Youcanidentifythesourceobjectoftheevent
usingthegetSource()instancemethodinthe
EventObject class.
ThesubclassesofEventObject dealwithspecial
typesofevents,suchasbuttonactions,window
events,componentevents,mousemovements,
andkeystrokes.
6
12/21/2015
SelectedUserActionsand
Handlers
TheDelegationModel
12/21/2015
TheDelegationModel:Example
ButtonbtOK =newButton("OK");
OKHandlerClass handler=newOKHandlerClass();
btOK.setOnAction(handler);
window
and display it
OKHandlerClass handler1 = new OKHandlerClass();
btOK.setOnAction(handler1);
CancelHandlerClass handler2 = new CancelHandlerClass();
btCancel.setOnAction(handler2);
2. Click OK
10
12/21/2015
Example:ControlCircle
Nowletusconsidertowriteaprogram
thatusestwobuttonstocontrolthesizeof
acircle.
11
InnerClassListeners
Alistenerclassisdesignedspecificallyto
createalistenerobjectforaGUI
component(e.g.,abutton).
Itwillnotbesharedbyotherapplications.
So,itisappropriatetodefinethelistener
classinsidetheframeclassasaninner
class.
12
12/21/2015
InnerClasses
Innerclass:Aclassisamemberofanotherclass.
Advantages:Insomeapplications,youcanuse
aninnerclasstomakeprogramssimple:
Aninnerclasscanreferencethedataand
methodsdefinedintheouterclassinwhichit
nests,soyoudonotneedtopassthe
referenceoftheouterclasstotheconstructor
oftheinnerclass.
13
InnerClassescont.
14
12/21/2015
InnerClassescont.
Innerclassescanmakeprogramssimpleand
concise.
Aninnerclasssupportstheworkofits
containingouterclassandiscompiledintoa
classnamed
OuterClassName$InnerClassName.class.
Forexample,theinnerclassInnerClass in
OuterClass iscompiledinto
OuterClass$InnerClass.class.
15
InnerClassescont.
Aninnerclasscanbedeclaredpublic,
protected,orprivate subjecttothesame
visibilityrulesappliedtoamemberoftheclass.
Aninnerclasscanbedeclaredstatic.
Astatic innerclasscanbeaccessedusingthe
outerclassname.
Astatic innerclasscannotaccessnonstatic
membersoftheouterclass
16
12/21/2015
AnonymousInnerClasses
Ananonymousinnerclassmust alwaysextenda
superclassorimplementaninterface,but itcannothaveanexplicit
extends orimplements clause.
Ananonymousinnerclassmust implementalltheabstract
methodsinthesuperclassorintheinterface.
Ananonymousinnerclassalwaysusesthenoarg constructor
fromitssuperclasstocreateaninstance.Ifananonymousinner
classimplementsaninterface,theconstructorisObject().
Ananonymousinnerclassiscompiledintoaclassnamed
OuterClassName$n.class.
Forexample,iftheouterclassTest hastwoanonymousinner
classes,thesetwoclassesarecompiledintoTest$1.class and
Test$2.class.
17
AnonymousInnerClassescont.
Innerclasslistenerscanbeshortenedusinganonymous
innerclasses.
Ananonymousinnerclass isaninnerclasswithouta
name.
Itcombinesdeclaringaninnerclassandcreatingan
instanceoftheclassinonestep.
Ananonymousinnerclassisdeclaredasfollows:
new SuperClassName/InterfaceName(){
//Implementoroverridemethodsinsuperclassorinterface
//Othermethodsifnecessary
}
18
12/21/2015
AnonymousInnerClassescont.
19
SimplifyingEventHandingUsing
LambdaExpressions
Lambdaexpression isanewfeatureinJava8.
Lambdaexpressionscanbeviewedasananonymous
methodwithaconcisesyntax.
Forexample,thefollowingcodein(a)canbegreatly
simplifiedusingalambdaexpressionin(b)inthreelines.
20
10
12/21/2015
BasicSyntaxforaLambdaExpression
Thebasicsyntaxforalambdaexpressioniseither:
(type1param1,type2param2,...)>expression
or
(type1param1,type2param2,...)>{statements;}
Thedatatypeforaparametermaybeexplicitly
declaredorimplicitlyinferredbythecompiler.
Theparenthesescanbeomittedifthereisonly
oneparameterwithoutanexplicitdatatype.
21
SingleAbstractMethodInterface(SAM)
Thestatementsinthelambdaexpressionisall
forthatmethod.
Ifitcontainsmultiplemethods,thecompilerwill
notbeabletocompilethelambdaexpression.
So,forthecompilertounderstandlambda
expressions,theinterfacemust containexactly
oneabstractmethod.
Suchaninterfaceisknownasafunctional
interface,oraSingleAbstractMethod (SAM)
interface.
22
11
12/21/2015
MouseEvent
23
TheKeyEvent Class
24
12
12/21/2015
TheKeyCode Constants
25
CaseStudy:BouncingBall
BallPane
BounceBallControl
26
13