Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
402 views

Slides of Java Programming

This document outlines the syllabus for the COMP231 Advanced Programming course. It will cover object-oriented programming concepts in Java like classes, objects, inheritance and polymorphism. The course aims to help students understand true object-oriented design. It will be taught by Dr. Mamoun Nawahdah and uses the Java textbook by Daniel Liang. Students will be evaluated based on exams, assignments, quizzes and a final practical exam. The course also provides a schedule and topics to be covered each week in both lectures and labs.

Uploaded by

samah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
402 views

Slides of Java Programming

This document outlines the syllabus for the COMP231 Advanced Programming course. It will cover object-oriented programming concepts in Java like classes, objects, inheritance and polymorphism. The course aims to help students understand true object-oriented design. It will be taught by Dr. Mamoun Nawahdah and uses the Java textbook by Daniel Liang. Students will be evaluated based on exams, assignments, quizzes and a final practical exam. The course also provides a schedule and topics to be covered each week in both lectures and labs.

Uploaded by

samah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 227

9/21/2015

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.

Java is the Internet


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!

public class Welcome{


public static void main(String[]args){
System.out.println("WelcometoJava!");
}
}
25

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);

System.out.println("1.0F / 3.0F is " + 1.0F / 3.0F);

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

var++, var-+, - (Unary plus and minus), ++var,--var


(type) Casting
! (Not)
*, /, % (Multiplication, division, and remainder)
+, - (Binary addition and subtraction)
<, <=, >, >= (Comparison)
==, !=; (Equality)
^ (Exclusive OR)
&& (Conditional AND) Short-circuit AND
|| (Conditional OR) Short-circuit OR
=, +=, -=, *=, /=, %= (Assignment operator)

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).

long round(double x) Return (long)Math.floor(x+0.5).


13

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];

for(int i =0;i <sourceArrays.length;i++)


targetArray[i]=sourceArray[i];

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

ONLY IF no constructors are


explicitly defined in the class.
10

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:

null forareference type


0 foranumeric type
false foraboolean type
'\u0000'forachar type
However,Javaassigns

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

methods, use the static modifier.


24

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.

private:Thedata ormethods canbeaccessedonly


bythedeclaringclass.

Theget andset methodsareusedtoreadandmodify


privateproperties.
30

15

10/3/2015

The private modifier restricts access to within a class.


The default modifier restricts access to within a package.
The public modifier enables unrestricted access.

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

public double getArea() {


return this.radius * this.radius * Math.PI;
}
}
Everyinstancevariablebelongstoaninstance
representedbythis,whichisnormallyomitted
48

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:

String message = "Welcome to Java";


2

10/17/2015

Strings Are

Immutable

A String object is immutable; its contents


cannot be changed.
Does the following code change the contents of
the string s?
String s = "Java";
s = "HTML";

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";

System.out.println("s1 == s2 is " + (s1 == s2));


System.out.println("s1 == s3 is " + (s1 == s3));

Display:
s1 == s2 is false
s1 == s3 is true

A new

object is created if you use


the new operator.
If you use the string initializer, no
new object is created if the
interned object is already created.
5

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 and s2 have the same contents


}
else {

// s1 is less than s2
}

10/17/2015

String Length, Characters,


and Combining Strings

Finding String Length


Finding string length using the length() method:

message = "Welcome to Java";


message.length(); // returns 15
9

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

Converting, Replacing, and


Splitting Strings

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

Matching, Replacing and


Splitting by Patterns
You can match, replace, or split a string by
specifying a pattern.
This is an extremely useful and powerful feature,
commonly known as regular

expression.

"Java".matches("Java")
"Java".equals("Java")
"Java is fun".matches("Java.*")
"Java is cool".matches("Java.*")
17

Matching, Replacing and


Splitting by Patterns
The replaceAll, replaceFirst, and split methods can be used
with a regular expression.
For example, the following statement returns a new string
that replaces $, +, or # in "a+b$#c" by the string NNN.

String s = "a+b$#c".replaceAll("[$+#]", "NNN");


System.out.println(s);
Here the regular expression [$+#] specifies a pattern that
matches $, +, or #.
So, the output is aNNNbNNNNNNc
18

10/17/2015

Matching, Replacing and


Splitting by Patterns
The following statement splits the string into an
array of strings delimited by some punctuation
marks:
String[] tokens = "Java,C?C#,C++".split("[.,:;?]");
for (int i = 0; i < tokens.length; i++)
Java
System.out.println(tokens[i]);
C
C#
C++
19

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

Convert Character and


Numbers to Strings
The String class provides several static valueOf
methods for converting a character, an array of
characters, and numeric values to strings.
These methods have the same name valueOf
with different argument types char, char[],
double, long, int, and float.
For example, to convert a double value to a
string, use String.valueOf(5.44). The return value
is string consists of characters 5, ., 4, and 4.
22

11

10/17/2015

The Character Class

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 and StringBuffer


The StringBuilder/StringBuffer class is an
alternative to the String class.
In general, a StringBuilder/StringBuffer can be
used wherever a String is used.
StringBuilder/StringBuffer is more flexible
than String.
You can add, insert, or append new
contents into a string buffer, whereas the value of
a String object is fixed once the string is created.
25

StringBuilder Constructors

26

13

10/17/2015

Modifying Strings in the Builder

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

The toString, capacity, length,


setLength, and charAt Methods

29

15

10/24/2015

Thinking
in Objects
By: Mamoun Nawahdah (PhD)
2015/2016

Class Abstraction and Encapsulation


Class abstraction means to separate class
implementation from the use of the class.
The creator of the class provides a description of the
class and let the user know how the class can be used.
The user of the class does not need to know how the
class is implemented.
The detail of implementation is encapsulated and
hidden from the user.
Class implementation is
like a black box hidden
from the clients

Class

Class Contract
(Signatures of public
methods and public
constants)

Clients use the


class through
the contract of
the class

10/24/2015

Case Study: The BMI Class

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:

Aggregation Between Same Class


Aggregation may exist between objects of the
same class.
For example, a person may have a supervisor:

public class Person {


// The type for the data is the class itself

private Person supervisor;


...

10/24/2015

Aggregation Between Same Class


What happens if a person has several
supervisors?

public class Person {


private Person[ ] supervisors;
...

Example: The Course Class

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

Designing a Class cont.


(Separating responsibilities) A single entity
with too many responsibilities can be broken into
several classes to separate responsibilities.
Example: the classes String, StringBuilder, and
StringBuffer all deal with strings, for example, but have
different responsibilities:
String class deals with immutable strings.
StringBuilder class is for creating mutable strings.
StringBuffer class is similar to StringBuilder except that
StringBuffer contains synchronized methods for updating strings.
10

10/24/2015

Designing a Class cont.


Classes are designed for reuse.
Users can incorporate classes in many different
combinations, orders, and environments. Therefore,
you should design a class that imposes no
restrictions on what or when the user can do with it:
Design the properties to ensure that the user can set
properties in any order, with any combination of
values.
Design methods to function independently of their
order of occurrence.
11

Designing a Class cont.


Follow standard Java programming style

and naming conventions:


Choose informative names for classes, data
fields, and methods.
Always place the data declaration before the
constructor, and place constructors before
methods.
Always provide a constructor and initialize
variables to avoid programming errors.
12

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

The Integer and Double Classes

14

10/24/2015

Numeric Wrapper Class Constructors


You can construct a wrapper object either from
a primitive data type value or from a string
representing the numeric value.
The constructors for Integer and Double are:
public Integer(int value)
public Integer(String s)
public Double(double value)
public Double(String s)
15

Numeric Wrapper Class Constants


Each numerical wrapper class has the constants
MAX_VALUE and MIN_VALUE.
MAX_VALUE represents the maximum value of
the corresponding primitive data type.
For Byte, Short, Integer, and Long, MIN_VALUE
represents the minimum byte, short, int, and long
values.
For Float and Double, MIN_VALUE represents
the minimum positive float and double values.
16

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

The Static valueOf Methods


The numeric wrapper classes have a
useful class method, valueOf(String s).
This method creates a new object
initialized to the value represented by the
specified string.
For example:
Double doubleObject = Double.valueOf("12.4");
Integer integerObject = Integer.valueOf("12");
18

10/24/2015

The Methods for Parsing Strings into Numbers

You have used the parseInt method in the


Integer class to parse a numeric string into
an int value and the parseDouble method in
the Double class to parse a numeric string
into a double value.
Each numeric wrapper class has two
overloaded parsing methods to parse a
numeric string into an appropriate numeric
value.
19

Automatic Conversion Between Primitive


Types and Wrapper Class Types
JDK 1.5 allows primitive type and wrapper classes
to be converted automatically. For example, the
following statement in (a) can be simplified as in (b):

Integer[] arr = {1, 2, 3};


System.out.println(arr[0] + arr[1] + arr[2]);
Unboxing

10

10/24/2015

BigInteger and BigDecimal


If you need to compute with very
large integers or high precision floatingpoint values, you can use the BigInteger
and BigDecimal classes in the java.math
package.
Both are immutable.

21

BigInteger and BigDecimal


BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);
BigDecimal a = new BigDecimal(1.0);
BigDecimal b = new BigDecimal(3);
BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);
System.out.println(c);
22

11

10/30/2015

Inheritance and
Polymorphism

By: Mamoun Nawahdah (Ph.D.)


2015/2016

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?

The answer is to use inheritance.


2

10/30/2015

Superclasses and Subclasses


GeometricObject
-color: String

The color of the object (default: white).

-filled: boolean

Indicates whether the object is filled with a color (default: false).

-dateCreated: java.util.Date

The date when the object was created.

+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

Returns the color.


Sets a new color.
Returns the filled property.

+getDateCreated(): java.util.Date

Sets a new filled property.


Returns the dateCreated.

+toString(): String

Returns a string representation of this object.

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

+Rectangle(width: double, height: double


color: String, filled: boolean)
+getWidth(): double

+getArea(): double

+setWidth(width: double): void

+getPerimeter(): double
+getDiameter(): double

+getHeight(): double
+setHeight(height: double): void

+printCircle(): void

+getArea(): double
+getPerimeter(): double

Superclass

Subclass

10/30/2015

Are Superclasss Constructor Inherited?


No. Unlike properties and methods, a superclass's
constructors are not inherited in the subclass.
They are invoked explicitly or implicitly.
Explicitly using the

super keyword.

They can only be invoked from the subclasses'


constructors, using the keyword super.

If the keyword super is not explicitly used,


the superclass's nono-arg constructor is
automatically invoked.
5

Superclasss Constructor is Always Invoked


A constructor may invoke an overloaded constructor or
its superclasss constructor.
If none of them is invoked explicitly, the compiler puts
super() as the first statement in the constructor.
For example:

10/30/2015

Using the Keyword super


The keyword super refers to the
superclass of the class in which super
appears.

super keyword can be used in two ways:


To call a superclass constructor.
To call a superclass method.
7

Caution
You must use the keyword super to
call the superclass constructor.
Invoking a superclass constructors name
in a subclass causes a syntax error.

Java requires that the statement that


uses the keyword super appear first in
the constructor.
8

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();

public class Faculty extends Employee {


public static void main(String[] args) {
Faculty f = new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employees overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
9

Example on the Impact of a Superclass


without no-arg Constructor
Find out the errors in the following program:
public class Apple extends Fruit {
}
public class Fruit {
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}
}
10

10/30/2015

Defining a Subclass
A subclass inherits from a superclass.
You can also:

Add new properties.


Add new methods.

Override the methods of the


superclass.
11

Calling Superclass Methods


You could rewrite the printCircle() method
in the Circle class as follows:
public void printCircle() {
System.out.println("The circle is created " +

super.getDateCreated() +
" and the radius is " + radius);
}
12

10/30/2015

Superclasses and Subclasses


GeometricObject
-color: String

The color of the object (default: white).

-filled: boolean

Indicates whether the object is filled with a color (default: false).

-dateCreated: java.util.Date

The date when the object was created.

+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

Returns the color.


Sets a new color.
Returns the filled property.

+getDateCreated(): java.util.Date

Sets a new filled property.


Returns the dateCreated.

+toString(): String

Returns a string representation of this object.

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

+Rectangle(width: double, height: double


color: String, filled: boolean)
+getWidth(): double

+getArea(): double

+setWidth(width: double): void

+getPerimeter(): double
+getDiameter(): double

+getHeight(): double
+setHeight(height: double): void

+printCircle(): void

+getArea(): double
+getPerimeter(): double

13

Overriding Methods in the Superclass


Sometimes it is necessary for the subclass to
modify the implementation of a method defined in
the superclass.
This is referred to as method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted
/** Override the toString method defined in GeometricObject */
public String
return

toString() {

super.toString() + "\n radius is " + radius;

}
}

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 vs. Overloading


public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class A extends B {
// This method overrides the method in B
public void p(double i) {
System.out.println(i);
}
}

Overriding

17

vs. Overloading

public class Test {


public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class A extends B {
// This method overloads the method in B
public void p(int i) {
System.out.println(i);
}
}

18

10/30/2015

The Object Class


Every class in Java is descended from the

java.lang.Object class.
If no inheritance is specified when a class
is defined, the superclass of the class is
Object.

19

The toString() method in Object


The toString() method returns a
string representation of the object.
The default implementation returns a
string consisting of:
A class name of which the object is an
instance.
The at sign (@
@).
A number representing this object.
20

10

10/30/2015

The toString() method in Object


Circle c = new Circle();
System.out.println(c.toString());
The code displays something like:

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

class GraduateStudent extends Student {


}
class Student extends Person {
public String toString() {
return "Student";
}
}
class Person extends Object {
public String toString() {
return "Person";
}
}

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.

An object of a subtype can be used wherever its


supertype value is required.
This feature is known as polymorphism.

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
}
}

This capability is known as

dynamic binding.

When the method m(Object x) is executed, the argument


xs toString method is invoked. x may be an instance of
GraduateStudent, Student, Person, or Object.
Classes GraduateStudent, Student, Person, and Object
have their own implementation of the toString method.
Which implementation is used will be determined
dynamically by the JVM at runtime.
24

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

Since o is an instance of C1, o is also an


Object

instance of C2, C3, , Cn-1, and C25n

Dynamic Binding cont.


Dynamic binding works as follows:
If o invokes a method p, the JVM searches the
implementation for the method p in C1, C2, ...,
Cn-1 and Cn, in this order, until it is found.
Once an implementation is found, the search
stops and the first-found implementation is
invoked.
Cn

C n-1

.....

C2

C1

Since o is an instance of C1, o is also an


Object

instance of C2, C3, , Cn-1, and C26n

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());
}
}

Polymorphism allows methods


to be used generically for a wide
range of object arguments.
This is known as:

generic programming

If a methods parameter type is a superclass (e.g., Object), you


may pass an object to this method of any of the parameters
subclasses (e.g., Student).
When an object (e.g., a Student object) is used in the method,
the particular implementation of the method of the object that is
invoked (e.g., toString) is determined dynamically.
27

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

Why Casting is Necessary?


Suppose you want to assign the object reference o to a
variable of the Student type using the following statement:
Student b = o ; // A compile error would occur.
Why does the statement Object o = new Student() work
and the statement Student b = o doesnt?

This is because a Student object is always an


instance of Object, but an Object is not
necessarily an instance of Student.
Even though you can see that o is really a
Student object, the compiler is not so clever to
know it.
29

Why Casting Is Necessary?


To tell the compiler that o is a Student
object, use an explicit casting.
casting
The syntax is similar to the one used for
casting among primitive data types.
Enclose the target object type in
parentheses and place it before the object to
be cast, as follows:

Student b = (Student) o ; // Explicit casting


30

15

10/30/2015

Casting from Superclass to Subclass


Explicit casting must be used when casting an
object from a superclass to a subclass.
Fruit fruit = new Apple();
Apple a = (Apple) fruit;
Orange o = (Orange) fruit;

This type of casting may not always succeed.

31

The instanceof Operator


Use the instanceof operator to test
whether an object is an instance of a class:
Object myObject = new Circle();
:

// Perform casting if myObject is an instance of Circle

if (myObject

instanceof

Circle) {

System.out.println("The circle diameter is " +


(

(Circle)myObject).getDiameter()

);

}
32

16

10/30/2015

The equals Method


The equals() method compares the contents of two
objects.
The default implementation of the equals method in
the Object class is as follows:
public boolean equals (Object obj) {
return ( this == obj );
}
For example, the equals
method is overridden in
the Circle class.

public boolean equals(Object o) {


if (o instanceof Circle) {
return radius == ((Circle)o).radius;
}
else
return false;
}
33

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

The ArrayList Class


You can create an array to store
objects.
But the arrays size is fixed once the
array is created.
Java provides the ArrayList class
that can be used to store an unlimited
number of objects.
35

The ArrayList Class

18

10/30/2015

Generic Type <E>


ArrayList is known as a generic class with a
generic type E.
You can specify a concrete type to replace E
when creating an ArrayList.
For example, the following statement creates an
ArrayList and assigns its reference to variable cities.
This ArrayList object can be used to store strings:
ArrayList<String> cities = new ArrayList<String>();
ArrayList<String> cities = new ArrayList<>();
37

Differences and Similarities


between Arrays and ArrayList

38

19

10/30/2015

ArrayLists from/to Arrays


Creating an ArrayList from an array of objects:

String[] array = {"red", "green", "blue"};


ArrayList<String> list = new
ArrayList<>(Arrays.asList(array));
Creating an array of objects from an ArrayList:

String[] array1 = new String[list.size()];


list.toArray(array1);
39

max and min in an ArrayList


java.util.Collections.max(list)
java.util.Collections.min(list)

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

The protected Modifier


The protected modifier can be applied on
data and methods in a class.
A protected data/method in a public class can be
accessed by any class in the same package or its
subclasses, even
different package.

if the subclasses are in a

Visibility increases
private, none (if no modifier is used), protected, public

41

Accessibility Summary

42

21

10/30/2015

Visibility Modifiers

43

A Subclass Cannot Weaken the Accessibility


A subclass may override a protected
method in its superclass and change its
visibility to public.
However, a subclass cannot weaken the
accessibility of a method defined in the
superclass.
For example, if a method is defined as
public in the superclass, it must be defined as
public in the subclass.
44

22

10/30/2015

The final Modifier


The final class cannot be extended:
final class Math {
...
}
The final variable is a constant:
final static double PI = 3.14159;
The final method cannot be

overridden by its subclasses.


45

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

Abstract Classes and Methods


Abstract classes: some
methods are only declared, but
no concrete implementations are
provided. They need to be
implemented by the extending
classes.

abstract class Person {


protected String name;
...
public abstract String getDescription() ;
...
}
Class Student extends Person {
private String major;
...
pulic String getDescription() {
return a student major in + major;
}
}
Class Employee extends Person {
private float salary;
...
pulic String getDescription() {
return an employee with a salary of $ + salary;
}
}

1/2/2014

Abstract Classes and Abstract Methods


GeometricObject

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

Methods getArea and getPerimeter are overridden in


Circle and Rectangle. Superclass methods are generally
omitted in the UML d iagram for subclasses.

Rectangle

Circle
-radius: double

-width: double

+Circle()

-height: double

+Circle(radius: double)

+Rectangle()

+Circle(radius: double, color: string,


filled: boolean)

+Rectangle(width: double, height: double)

+getRadius(): double

+Rectangle(width: double, height: double,


color: string, filled: boolean)

+setRadius(radius: double): void

+getWidth(): double

+getDia meter(): double

+setWidth(width: double): void


+getHeight(): double
+setHeight(height: double): void

Abstract Method in Abstract Class


An abstract method cannot be contained in a
nonabstract class.
If a subclass of an abstract superclass does
not implement all the abstract methods, the
subclass must be defined abstract.
In other words, in a nonabstract subclass
extended from an abstract class, all the
abstract methods must be implemented, even if
they are not used in the subclass.
6

1/2/2014

Object Cannot be Created from Abstract Class


An abstract class cannot be
instantiated using the new operator, but
you can still define its constructors,
which are invoked in the constructors of
its subclasses.
For instance, the constructors of
GeometricObject are invoked in the
Circle class and the Rectangle class.
7

Abstract Class Without Abstract Method


A class that contains abstract methods must
be abstract.
However, it is possible to define an abstract
class that contains no abstract methods. In this
case, you cannot create instances of the class
using the new operator.
This class is used as a base class for
defining a new subclass.
8

1/2/2014

Superclass of Abstract Class may be Concrete


A subclass can be abstract even if its
superclass is concrete.
For example, the Object class is
concrete, but its subclasses, such as
GeometricObject, may be abstract.

Concrete Method Overridden to be Abstract


A subclass can override a method
from its superclass to define it abstract.
This is rare, but useful when the
implementation of the method in the
superclass becomes invalid in the
subclass. In this case, the subclass must
be defined abstract.
10

1/2/2014

Abstract Class as Type


You cannot create an instance from an
abstract class using the new operator, but
an abstract class can be used as a data
type.
Therefore, the following statement,
which creates an array whose elements
are of GeometricObject type, is correct:
GeometricObject[] geo = new GeometricObject[10];
11

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

Interface is a Special Class


An interface is treated like a special class in Java.
Each interface is compiled into a separate
bytecode file, just like a regular class.
Like an abstract class, you cannot create an
instance from an interface using the new operator,
but in most cases you can use an interface more or
less the same way you use an abstract class.
For example, you can use an interface as a data
type for a variable, as the result of casting, and so
on.
15

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

Omitting Modifiers in Interfaces


All data fields are public final static and all
methods are public abstract in an interface.
For this reason, these modifiers can be omitted,
as shown below:
public interface T1 {
public static final int K = 1;

Equivalent

public interface T1 {
int K = 1;
void p();

public abstract void p();


}

A constant defined in an interface can be accessed


using syntax InterfaceName.CONSTANT_NAME.
17

Example: The Comparable Interface


// This interface is defined in
// java.lang package

package java.lang;
public interface Comparable<E> {
public int compareTo(E o);
}

18

1/2/2014

Integer and BigInteger Classes


public class Integer extends Number
implements Comparable<Integer> {
// class body omitted

public class BigInteger extends Number


implements Comparable<BigInteger> {
// class body omitted

@Override
public int compareTo(Integer o) {
// Implementation omitted
}

@Override
public int compareTo(BigInteger o) {
// Implementation omitted
}

String and Date Classes


public class String extends Object
implements Comparable<String> {
// class body omitted

public class Date extends Object


implements Comparable<Date> {
// class body 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));

Let n be an Integer object, s be a String object, and d be


a Date object. All the following expressions are true:
n instanceof Integer
n instanceof Object
n instanceof Comparable

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

Instantiation Properties of Interfaces


You can not use the new operator to instantiate an interface:
public interface C { }
C c = new C ( );
You can still declare interface variables:
C c;
But they must refer to an object of a class that implements the
interface:
class E implements C {
...
}
C c = new E ( );

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

Extending Interfaces Constants


An extended interface inherits all the constants
from its superinterfaces:
interface A {
int val = 1;
}
interface B {
int val = 2;
}
interface C extends A, B {
System.out.println( A.val = + A.val );
System.out.println( B.val = + B.val );
}

Extending Interfaces Constants


If a superinterface and a subinterface contain two
constants with the same name, then the one
belonging to the superinterface is hidden:
interface X {
int val = 1;
}
interface Y extends X{
int val = 2;
int sum = val + X.val;
}

12

1/2/2014

Extending Interfaces Methods


If a declared method in a subinterface
has the same signature as an inherited
method and the same return type, then
the new declaration overrides the
inherited method in its superinterface.
If the only difference is in the return type,
then there will be a compile-time error.

The Cloneable Interfaces


A class that implements the Cloneable interface is
marked cloneable, and its objects can be cloned
using the clone() method defined in the Object class.
clone method returns a new object whose initial
state is a copy of the current state of the object on
which clone was invoked.
Subsequent changes to the new clone object
should not affect the state of the original object.
package java.lang;
public interface Cloneable {
}
26

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

Implementing Cloneable Interface


To define a custom class that implements the
Cloneable interface, the class must override the clone()
method in the Object class.
The following code defines a class named House that
implements Cloneable and Comparable.

28

14

1/2/2014

public class House implements Cloneable, Comparable<House> {


private int id;
private double area;
private java.util.Date whenBuilt;
public House(int id, double area) {
this.id = id; this.area = area;

whenBuilt = new java.util.Date();

}
public int getId() {

return id;

public double getArea() { return area; }


public java.util.Date getWhenBuilt() { return whenBuilt; }
29

@Override // Override the clone method defined in the Object class


public Object clone() {
return super.clone();
}
@Override // Implement the compareTo method defined in Comparable
public int compareTo(House o) {
if (area > o.area)
return 1;
else if (area < o.area)
return -1;
else
return 0;
}
}

30

15

1/2/2014

Shallow vs. Deep Copy


House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone();
Memory

house1: House

id = 1
area = 1750.5 0
wh enBuilt

1
1750.50
reference

date object contents

house2 = house1.clo ne()


House2: House

Memory

id = 1
area = 1750 .5 0
whenBuilt

when Built: Date

1
1750 .5 0
reference

31

Interfaces vs. Abstract Classes


In an interface, the data must be constants; an abstract
class can have all types of data.
Each method in an interface has only a signature
without implementation; an abstract class can have
concrete methods.
Variables

Constructors

Methods

Abstract
class

No restrictions

Constructors are invoked by subclasses


through constructor chaining. An
abstract class cannot be instantiated
using the new operator.

No restrictions.

Interface

All variables
must be public
static final

No constructors. An interface cannot


be instantiated using the new operator.

All methods must be


public abstract
instance methods
32

16

1/2/2014

Interfaces vs. Abstract Classes cont.


All classes share a single root, the Object class,
but there is no single root for interfaces.
Like a class, an interface also defines a type. A
variable of an interface type can reference any
instance of the class that implements the interface.
If a class extends an interface, this interface plays
the same role as a superclass.
You can use an interface as a data type and cast a
variable of an interface type to its subclass, and vice
versa.
33

Interfaces vs. Abstract Classes cont.


Interface1_2

Interface1_1

Object

Interface2_2

Interface1

Class1

Interface2_1

Class2

Suppose that c is an instance of Class2.


c is also an instance of Object, Class1,
Interface1, Interface1_1, Interface1_2,
Interface2_1, and Interface2_2.
34

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);

public class HandleEvent extends Application {


1. Start from the main
public void start(Stage primaryStage) {
method to create a

window
and display it
OKHandlerClass handler1 = new OKHandlerClass();
btOK.setOnAction(handler1);
CancelHandlerClass handler2 = new CancelHandlerClass();
btCancel.setOnAction(handler2);

primaryStage.show(); // Display the stage


}
}
class OKHandlerClass implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent e) {
System.out.println("OK button clicked");
}
}
3. Click OK. The JVM invokes
the listeners handle method

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

You might also like