Cs 401
Cs 401
(with Java)
• These notes are intended for use by students in
CS0401 at the University of Pittsburgh and no one
else
• These notes are provided free of charge and may
not be sold in any shape or form
• Material from these notes is obtained from various
sources, including, but not limited to, the
following:
4 Starting Out with Java, From Control Structures through
Data Structures, Fourth Edition, by Gaddis and Muganda
4 Starting Out with Java, From Control Structures through
Objects, Third to Seventh Editions by Gaddis
4 Java Software Solutions, Fourth and Fifth Editions by
Lewis and Loftus
4 Java By Dissection by Pohl and McDowell
4 The Java Tutorial (click for link)
4 The Java home page and its many sub-links:
http://www.oracle.com/technetwork/java/index.html
2
Lecture 1: Prerequisites
7
Lecture 1: Goals of Course
• Java
4 Java is a (bytecode) interpreted, platform-
independent, object-oriented language
• Interpreted, platform-independent:
– Source .java code is compiled into intermediate
(byte) code
– Byte code is executed in software via another
program called an interpreter (JRE)
– Benefits:
> More safety features and run-time checks can be
built into the language – discuss
> Code can be platform-independent
> As long as the correct JRE is installed, the same
byte code can be executed on any platform
9
Lecture 1: Why Java?
Java Java
JRE for Linux
Source Byte
Code Java Compiler Code
(.java) (.class)
10
Lecture 1: Why Java?
– Drawback:
> Interpreted code executes more slowly than
regular compiled code
> Since program is run in software rather than
hardware, it cannot match the execution times of
code that is compiled for specific hardware
> Ex: C, C++ code
> No language is best for every application
> However, Java implementations can use JIT
compilation of bytecode to execute faster
• Object-oriented
– Primary mode of execution is interaction of
objects with each other
– We will discuss object-oriented programming in
much more detail soon
11
Lecture 1: Getting Started with Java
12
Lecture 1: Getting Started with Java
– It is free!
• More on the basics of using the Java software
development kit is shown in Lab 1
– See the Lab Info link on the CS 0401 site for
details
• But let’s look at an ex.
13
and talk more about Java
Lecture 1: Getting Started with Java
14
Lecture 1: Getting Started with Java
18
Lecture 2: Java Basics
4 Predefined Identifiers
• Identifiers that were written as part of some
class / package that are already integrated into
the language
– Ex: System, Applet, JFrame – class names
– Ex: println, start, close – method names
– Ex: E, PI – constant names
• Programmers can use these within the context
in which they are defined
• In Java there are a LOT because Java has a
large predefined class library
20
Lecture 2: Java Basics
4 Other Identifiers
• Defined by programmer
• used to represent names of variables, methods,
classes, etc
• Cannot be keywords
• We could redefine predefined identifiers if we
wanted to, but this is generally not a good idea
• Java IDs must begin with a letter, followed by
any number of letters, digits, _ (underscore) or
$ characters
– Similar to identifier rules in most programming
langs
21
Lecture 2: Java Basics
• Important Note:
– Java identifiers are case-sensitive – this means that
upper and lower case letters are considered to be
different – be careful to be consistent!
– Ex: ThisVariable and thisvariable are NOT the same
• Naming Convention:
– Many Java programmers use the following
conventions:
> Classes: start with upper case, then start each word
with an upper case letter
> Ex: StringBuffer, BufferedInputStream,
ArrayIndexOutOfBoundsException
> Methods and variables: start with lower case,
then start each word with an upper case letter
> Ex: compareTo, lastIndexOf, mousePressed
22
Lecture 2: Java Basics
4 Literals
• Values that are hard-coded into a program
– They are literally in the code!
• Different types have different rules for literal
values
– They are fairly intuitive and similar across most
programming languages
– Ex: Integer
> An optional +/- followed by a sequence of digits
> Ex: 234 -4566
– Ex: String
> A sequence of characters contained within double
quotes
> Ex: “Hello” “My name is Inigo Montoya”
• See Section 2.3 for more details on literals
23
Lecture 2: Java Basics
24
Lecture 2: Java Basics
• Statements
• Units of declaration or execution
• A program execution can be broken down into
execution of the program’s individual
statements
• Every Java statement must be terminated by
a semicolon (;)
• Ex: Variable declaration statement
int var1, var2;
• Ex: Assignment statement
var1 = 100;
• Ex: Method call
System.out.println(“Answer is “ + var1);
• We will see many more statements later
25
Lecture 2: Java Basics
• Variables
• Memory locations that are associated with
identifiers
• Values can change throughout the execution of a
program
• In Java, must be specified as a certain type or
class
– The type of a variable specifies its properties: the
data it can store and the operations that can be
performed on it
> Ex: int type: discuss
– Java is fairly
incompatible strict about
types: String enforcing data typeto
cannot be converted values
int
int i = "hello";
> You will get a compilation error if you assign an
^
incorrect type to a variable: Ex: int i = “hello”;
26
Lecture 2: Java Basics
– Note: For numeric types, you even get an error if
the value assigned will “lose precision” if placed
into the variable
> Generally speaking this means we can place
“smaller” values into “larger” variables but we
cannot place “larger” values into “smaller”
variables
> Ex: byte < int < long < float < double
– Ex: int i = 3.5;
incompatible types: possible lossy conversion from double to int
int i = 3.5;
^
27
Lecture 2: Java Basics
– Floating point literals in Java are by default
double
> If you assign one to a float variable, you will get a
“loss of precision error” as shown in the previous
slide
– If you want to assign a “more precise” value to a
“less precise” variable, you must explicitly cast
the value toint
that ivariable
= 5; type
int j = 4.5;
float x = 3.5;
float y = (float) 3.5;
Error check each of the
double z = 100;
statements in the box to
i = z;
the right
y = z;
z = i;
j = (long) y;
j = (byte) y;
28
Lecture 3: Data and Expressions
var1 100
29
Lecture 3: Data and Expressions
s
Hello There
30
Lecture 3: Data and Expressions
32
Lecture 3: Data and Expressions
• Input
4 Java has a predefined object called
System.in
• Analogous to System.out discussed previously
• Allows data to be input from the standard input
stream
– Recall that System.out accessed the standard
output stream
4 By default this object allows us to read
data from the console / keyboard
36
Lecture 3: Input and the Scanner Class
• Java Statements
4 We already discussed some Java
statements
• Declaration statement
• Assignment statement
• Method call
4 One of the most important types of
statements in programming is the control
statement
• Allows 2 very important types of execution
– Conditional execution
> Statements may or may not execute
– Iterative execution
> Statements may 39
execute more than one time
Lecture 4: Control Statements
40
Lecture 4: Boolean Expressions
expressions are
more complicated true true false true true
than just a simple
relational operation true false false false true
• These expressions
require logical false true true false true
operators
– Operate on false false true false false
boolean values,
generating a new
boolean value as a
result
! && ||
– Recall their values
from a truth table
42
Lecture 4: Boolean Expressions
(i / 3) == y
(x / 3) == y
!(x != i)
43
Lecture 5: if statement
• Nested ifs
4 Since both <true option> and <false
option> can be any Java statement, they
can certainly be if statements
4 This allows us to create nested if
statements
• We can nest on <true option>, on <false
option> or both
– Show on board
• Enables us to test multiple conditions and to
have a different result for each possibility
45
Lecture 5: if statement
4 Dangling else
• The structure of a Java if statement allows for
an interesting special case:
if (grade >= 95) // condition1
if (extraCredit) // condition2
System.out.println(“A+”);
else
System.out.println(“?”);
• Question: is the <false option> for condition1
or condition2?
– As shown above it will ALWAYS be for condition2
– Rule is that an else will always be associated
with the “closest” unassociated, non-
terminated if
46
Lecture 5: if statement
49
Lecture 5: Example
50
Lecture 6: for loop
51
Lecture 6: for loop
• init_expr
– Any legal Java statement expression
– Evaluated one time, when the loop is FIRST
executed
• go_expr
– Java Boolean expression
– Evaluated PRIOR to each execution of the for
loop body
> If true, body is executed
> If false, loop terminates
• inc_expr
– Any legal Java statement expression
– Evaluated AFTER each execution of the for loop
body
4 These expressions make the for loop
52
extremely flexible
Lecture 6: for loop
55
Lecture 6: switch statement
switch (int_expr)
{
case constant_expr:
…
case constant_expr:
…
default: // this is optional
}
4 int_expr is initially evaluated
4 constant_expr are tested against int_expr
from top to bottom
• First one to match determines where execution
within the switch body BEGINS
– However, execution will proceed from there to
the END of the block
56
Lecture 6: switch statement
57
Lecture 7: Methods and Method Calls
60
Lecture 7: Functional Abstraction
67
Lecture 7: Writing Static Methods
Ex:
public static double area(double radius)
{
double ans = Math.PI * radius * radius;
return ans;
} parameter
… argument
double rad = 2.0;
double theArea = area(rad);
68
Lecture 7: Parameters
4 Parameters in Java are passed by value
• The parameter is a copy of the evaluation of
the argument
• Any changes to the parameter do not affect the
argument answer calculated
method completed answer returned
72
Lecture 7: Local variables and scope
74
Lecture 8: References and Reference Types
Foo F;
F = new Foo(10); F
Foo reference
78
Lecture 8: More References
80
Lecture 8: More References
82
Lecture 8: More References
• Why?
– The method calls are associated with the OBJECT
that is being accessed, NOT with the variable
– If there is no object, there are no methods
available to call
– Result is NullPointerException – common
error so remember it!
4 Let's take a look at ex8.java
4 Side note: speaking of common errors
• Take another look at debug.ppt – it has some of
the things we just mentioned
85
Lecture 9: Intro. to Object-Oriented Programming (OOP)
4 Inheritance
• Properties of a data type can be passed down
to a sub-type – we can build new types from old
ones
• We can build class hierarchies with many levels
of inheritance
• We will discuss this more in Chapter 11
4 Polymorphism
• Operations used with a variable are based on
the class of the object being accessed, not the
class of the variable
• Parent type and sub-type objects can be
accessed in a consistent way
• We will discuss this more in Chapter 11
87
Lecture 9: Encapsulation and Data Abstraction
X 10
+
Y 5
88
Lecture 9: Encapsulation and Data Abstraction
P P2
addPoint() addPoint()
contains() contains()
translate() translate()
93
Lecture 9: Encapsulation and Data Abstraction
98
Lecture 9: Class Methods vs. Instance Methods
• In summary:
4 Objects allow us to encapsulate data and
operations together into a single entity
• Instance variables define the data within the
object
• Instance methods define the operations to be
used by the object
4 The instance variables and methods are
specified in the class definition
• Which variables / methods can be "seen" by a
user of the object can be restricted by private
declarations
4 Objects are instances of class which
contain the specified
101 data and methods
Lecture 9: Encapsulation / Abstraction Summary
103
Lecture 10: Constructors, Accessors and Mutators
4 Accessors
– Also called getters
• These methods are used to access the object in
some way without changing it
• Usually used to get information from it
• No special syntax – categorized simply by their
effect
StringBuilder B = new StringBuilder(“hello there”);
char c = B.charAt(4); // c == ‘o’
String S = B.substring(3, 9); // S == “lo the”
// note that end index is NOT
inclusive
int n = B.length(); // n == 11
– These methods give us information about the
StringBuilder without revealing the implementation
details 104
Lecture 10: Constructors, Accessors and Mutators
4 Mutators
– Also called setters
• Used to change the object in some way
• Since the instance variables are usually private,
we use mutators to change the object in a
specified way without needing to know the
instance variables
B.setCharAt(0, ‘j’); // B == “jello there”
B.delete(6,7); // B == “jello here”
B.insert(6, “is “); // B == “jello is here”;
– These methods change the contents or
properties of the StringBuilder object
4 We use accessors and mutators to
indirectly access the data, since we don’t
have direct access 105
– see ex9.java
Lecture 10: Simple Class Example
• Classes
4 Define the nature and properties of
objects
• Objects
4 Instances of classes
108
Lecture 11: Developing Another Example
109
Lecture 11: Testing Your Classes
• So far
4 Our programs have read input from the
keyboard and written output to the
monitor
• This works fine in some situations, but
is not so good in others:
4 What if we have a large amount of output
that we need to save?
4 What if we need to initialize a database
that is used in our program?
4 What if output from one program must be
input to another?
111
Lecture 11: Java Text Files
113
Lecture 11: Java Text Files
114
Lecture 11: Java Text Files
115
Lecture 12: Arrays
117
Lecture 12: Arrays
118
Lecture 12: Java Arrays
• Java Arrays
4 In Java, arrays are objects, with certain
properties
• Like other reference types
4 Simply put, an array is logically a
single variable name that allows
access to multiple variable locations
4 In Java, the locations also must be
contiguous and homogeneous
• Each directly follows the previous in memory
• All references in the array are of the same type
119
Lecture 12: Java Arrays
• Syntax:
4 First, consider only PRIMITIVE TYPE data
4 We create a Java array in 2 steps:
prim_type [] var_name;
• where prim_type is any primitive type
• where var_name is any legal identifier
• This creates array variable, but NOT an actual
array
var_name = new prim_type[arr_size]
• where arr_size is the number of elements that
will be in the array
• Indexing in Java always starts at 0
• This creates the array object
120
Lecture 12: Java Arrays
4 Ex:
int [] myArray;
myArray = new int[20]; // size can be a variable
// or expression
4 These two steps can be done as one if
we’d like
int [] myArray = new int[20];
4 Once we have created the array, we now
need to put values into it
• Numeric types are initialized to 0
• Booleans are initialized to false
– This is because the locations within an array are
considered as instance variables within the array
object
121
• We can change these values via indexing
Lecture 12: Java Arrays
• Indexing an array
4 An array variable gives us access to the
“beginning” of the array
4 To access an individual location in the
array, we need to index, using the []
operator
4 Ex:
myArray[5] = 250;
myArray[10] = 2 * myArray[5];
myArray[11] = myArray[10] – 1;
• Show on board
• Discuss
122
Lecture 12: Java Arrays
s
Hello
• With reference types, values are There
references to
objects that are stored elsewhere in memory
125
Lecture 12: Arrays as Reference Types
126
Lecture 12: Arrays as Parameters
129
Lecture 13: Sequential Search
• Sequential Search
4 Start at the beginning of the array and
check each item in sequence until the end
of the array is reached or the item is found
• Note that we have two conditions here
– One stops the loop with failure (get to end)
– The other stops the loop with success (found
item)
• We should always consider all possible
outcomes when developing algorithms
4 Q: What kind of loop is best for this?
• Think about what needs to be done
4 Let’s look at an example: ex12a.java
130
Lecture 13: Arrays of Objects
131
Lecture 13: Arrays of Objects
0
names
1 Herb
2
3 Madge
4 Mort
133
Lecture 13: Instance Data and Composition
136
Lecture 13: Arrays as Instance Data
• Exam One
4 All material from Lecture 1 to Lecture 13,
inclusive
4 See review sheet and practice questions
on Online Materials link of web site
138
Lecture 15: Resizing an array
4 Idea:
• Data is maintained in two parts:
– an array to actually store the information
– an int to keep track of the number of elements
being stored
• Most of our operations are concerned with the
logical size of the array
– Number of actual elements being stored
• The physical size of the array is abstracted out
of our view
– This changes as necessary but we never need to
know what it actually is in order to use the
ArrayList
– Remember previous discussion on resizing
144
Lecture 15: Array Based Data Structures
145
Lecture 15: 2-D Arrays
147
Lecture 16: Simple Sorting
• How do we sort?
4 There are MANY ways of sorting data
• Sorting has been widely studied in computer
science
4 Some algorithms are better than others
• The most useful measure of “better” here is
how long it takes to run
• The better algorithms run a lot more quickly
than the poorer algorithms
4 However, some very simple algorithms are
ok if N is not too large
• We will look at a simple algorithm here
– In CS 0445 you will see other, better ways of
sorting 148
Lecture 16: SelectionSort
150
Lecture 16: Sorting
– We could write a version of SelectionSort (or
InsertionSort) for each
– Lots of typing, where everything other than the
types involved is the same for each one
> This is a key issue – the only difference in the
sorts of different types is the data values and how
they are compared
> The sorting algorithm is the same
– Is there a way we can do this without having to
write the method so many times?
– Yes!
> Java Generics
> We will discuss this later after we discuss
polymorphism and interfaces
151
Lecture 16: Binary Search
153
Lecture 16: Binary Search
154
Lecture 16: Binary Search
• Notes:
4 As with the version of SelectionSort we
saw previously, this version of Binary
Search only works for arrays of ints
• If we want to generalize it we need to write it in
a slightly different way, using Java generics
• We will look at this later once we have
discussed inheritance and interfaces
155
Lecture 16: Binary Search
156
Lecture 17: Contiguous Memory Data Structures
data
data
data data
161
Lecture 17: Linked Data Structures
164
Lecture 17: Node As an Inner Class
4 For example:
public class SimpleLList
{
private class Node
{
private T data;
private Node next;
…
}
private Node front; // front of list
// SimpleLList methods go here
// These methods can access Node and its
// data but outside of SimpleLList Node
// cannot be accessed
165
Lecture 17: Linked List Operations
166
Lecture 17: Linked List Operations
167
Linked List Operations
168
Linked List Operations
169
Linked List Operations
170
Lecture 18: Additional OO Notes
4 static variables
• Variables that are associated with the class itself
rather than individual objects
• Can be accessed through the class using
– ClassName.variableName
• or through the objects using
– variableName from within an object
– objectName.variableName from outside an object
• Show logic of this on the board
• To access from class or from outside of an object,
the data must be public
• Used when variables are shared amongst all
objects
– See StaticDemo.java
171
Lecture 18: Additional OO Notes
4 Copying objects
• Sometimes, for various reasons, we need to
make a copy of an object
• In Java there are two primary ways of doing
this:
– Using a “copy constructor” for the class
> This method takes an argument of the same class
type and makes a copy of the object
> Ex: String newString = new String(oldString);
– Using the “clone” method for a class
> This allows an object to “make a copy of itself”
> It is a bit more complicated to use
> We will defer it to CS 0445
173
Lecture 18: Misc OO Notes
177
Lecture 19: Misc OO Notes
179
Lecture 19: Misc OO Notes
4 Garbage Collection
• When a reference to an object is reassigned,
the original object can no longer be accessed
through that reference
• If there is no other reference to that object,
then it cannot be accessed, period
• In this case the object has become garbage
– An object sitting in memory that can no longer
be an active part of the program
• If a program produces a lot of garbage it can
consume a lot of memory
180
Lecture 19: Misc OO Notes
181
Independent Work: Wrappers
183
Independent Work: Wrappers
184
Independent Work: Wrappers and Casting
185
Independent Work: Wrappers
188
Independent Work: Character class
189
Lecture 19: Inheritance
190
Lecture 19: Inheritance and “is a”
AbstractList
is a is a
is a
is a • AbstractSequentialList, ArrayList
and Vector are all AbstractLists
LinkedList 4 LinkedList “is a” AbstractSequentialList
193
Lecture 19: private, public and protected
• As another example
4 Compare MixedNumber class and
MixedNumber2 class
4 Both utilize the RationalNumber class from
the Lewis & Loftus text to do most of the
"work"
4 Both also have the same functionality, but
MixedNumber uses composition and
MixedNumber2 uses inheritance
• Note simplicity of MixedNumber2 methods
• Read over the comments carefully!
• See ex16.java, RationalNumber.java,
MixedNumber.java and MixedNumber2.java
195
RationalNumber
Lecture 20: Inheritance Example
int numerator
int denominator Composition: MixedNumber
-------------- MixedNumber class
add(), subtract(), utilizes a RationalNumber int whole
multiply(), object. Methods in RationalNumber frac
divide(), etc. MixedNumber must
--------------
manipulate the
RationalNumber object as add(), subtract(),
a "client", since it has no multiply(),
special relationship to divide(), etc.
RationalNumber
Inheritance:
RationalNumber MixedNumber2 class is a
MixedNumber2 extends RationalNumber, but with
RationalNumber modifications. Ex: The
int numerator
numerator in MixedNumber2
int denominator is that defined in
add(), subtract(), -------------- RationalNumber. Methods in
multiply(), add(), subtract(), RationalNumber can be used
divide(), etc. multiply(), directly, and new versions
divide(), etc. are only needed where the
return type must be
MixedNumber2.
196
Lecture 20: Inheritance Example
197
Lecture 21: Java Class Hierarchy
• Idea of polymorphism
4 See internet definition:
• On Google type “definition polymorphism” and
see the results
– This search works for many CS terms that you may
be curious about
• http://www.webopedia.com/TERM/P/polymorphism.
html
• Subclassing Polymorphism
4 Sometimes called “true polymorphism”
4 Consists basically of two ideas:
1) Method overriding
• A method defined in a superclass is redefined
in a subclass with an identical method
signature
• Since the signatures are identical, rather than
overloading the method, it is instead
overriding the method
– For subclass objects, the definition in the
subclass replaces the version in the superclass
– See OverrideDemo.java, SimpleAList.java,
SortAList.java
202
Lecture 21: Polymorphism
4 Ex:
• Suppose class Fish contains a new instance
variable waterType and a new method
getWaterType()
Fish F = new Fish();
Animal A = new Fish();
System.out.println(F.getWaterType()); // ok
System.out.println(A.getWaterType()); // NO!
– The above is NOT legal, even though the method
exists for class Fish. The reason is that the
method is not visible from the reference’s point of
view (A is an Animal reference so it can only “see”
the data and methods defined in class Animal)
System.out.println(((Fish) A).getWaterType());
– This is ok, since we have now cast the reference to
the Fish type, which CAN access the method
206
Lecture 21: Object, Method and Instance Variable Access
207
Lecture 21: Object, Method and Instance Variable Access
• To summarize:
• Superclass references CAN BE used to
reference subclass objects
• Subclass references CANNOT BE used to
reference superclass objects
• The type of the reference determines what
public data and methods are ACCESSIBLE / can
be seen
• The type of the object determines what data
and methods EXIST
– Methods and data initially defined within a
subclass CANNOT BE accessed via a superclass
reference
– The type of the object also determines which
VERSION of an overridden method is called
208
Lecture 22: Abstract Classes
• Abstract classes
4 Sometimes in a class hierarchy, a class
may be defined simply to give cohesion to
its subclasses
• No objects of that class will ever be defined
• But instance data and methods will still be
inherited by all subclasses
4 This is an abstract class
• Keyword abstract used in declaration
• One or more methods may be declared to be
abstract and are thus not implemented
• No objects may be instantiated
209
Lecture 22: Abstract Classes
210
Lecture 22: Java Interfaces
211
Lecture 22: Java Interfaces
212
Lecture 22: Intro. to Interfaces
4 Ex:
public interface Laughable
{
public void laugh();
}
• Ex:
public class Comedian implements Laughable, Booable
{
// various methods here (constructor, etc.)
public void laugh()
{
System.out.println(“Ha ha ha”);
}
public void boo()
{
System.out.println(“You stink!”);
}
}
• Note that in the class header we must declare that the
interfaces are implemented
215
Lecture 22: Intro. to Interfaces
4 Ex:
Laughable [] funny = new Laughable[3];
funny[0] = new Comedian();
funny[1] = new SitCom(); // implements Laughable
funny[2] = new Clown(); // implements Laughable
for (int i = 0; i < funny.length; i++)
funny[i].laugh();
221
Lecture 23: “Generic” Operations
4 Consider the Comparable interface:
• It contains one method:
int compareTo(Object r);
• Returns a negative number if the current object is
less than r, 0 if the current object equals r and a
positive number if the current object is greater
than r
• Look at Comparable in the API
4 Consider what we need to know to sort data:
• is A[i] less than, equal to or greater than A[j]
– That's it – nothing else!
4 Thus, we can sort Comparable data
without knowing anything else about it
222
Lecture 23: "Generic" operations
public static void selectionSort(Comparable [] array) Parameter is array of
{ Comparable
int startScan, index, minIndex;
Comparable minValue; minValue is
Comparable
for (startScan = 0; startScan < (array.length-1); startScan++)
{
minIndex = startScan;
minValue = array[startScan];
for(index = startScan + 1; index < array.length; index++)
{
if (array[index].compareTo(minValue) < 0) Values compared using
{ the compareTo() method
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
– Same algorithm but now will work for any type that
implements Comparable
223
Lecture 23: “Generic” Operations
226
Lecture 23: Parameterized Types
• Idea:
4 Consider a collection of data (ex: array list
but there are many others)
4 Allow an argument to be passed into the
collection type itself
• This argument will be another Java type, which
will indicate the "base type" for the collection
4 For example, rather than saying
• An array list (where it could store any Java
objects)
4 we instead say
• An array list OF T, where T is some Java type
227
Lecture 23: Parameterized Types
231
Lecture 24: Graphical Interfaces
• JavaFX is a
“Set of graphics and media packages that
enables developers to design, create, test,
debug and deploy rich client applications
that operate consistently across diverse
platforms”
-- from Oracle JavaFX docs
4 As more programming moves toward Web
interfaces, JavaFX will gain in popularity
4 Can be used with Swing as well, so
learning Swing is still a good thing
235
Lecture 24: JavaFX vs. Swing
239
Lecture 24: Simple Example
4 Note that this example does not really do
much
• No interaction with the user
4 But it does show us some of the basic
setup for graphical applications
4 Let’s now add a bit more functionality
• Add a button that user can click to change the
color of the label text
240
Lecture 24: JButtons
241
Lecture 24: Event-Driven Programming
– Thus any class that implements
actionPerformed() can be an ActionListener
• This causes the actionPerformed method within
the ActionListener to execute
– It is the actionPerformed method that is doing
the actual response to the button click
4 This idea is called event-driven
programming
• As program executes, user generates events in
various ways
– Ex: click a button, move the mouse, edit text
• Programmer writes code to respond to the
various events that may occur
• See trace on next slide (run as a presentation
to see effects)
242
Lecture 24: Event-Driven Programming
1) JButton is clicked
2) ActionEvent (AE)
generated public void
3) Event passed to actionPerformed( )
ActionListener {
4) actionPerformed // code to execute
executed
}
Note that because the
ActionEvent is passed to the
actionPerformed method, the
method can get information
from the ActionEvent through its 243
accessor methods
Lecture 24: Event-Driven Programming
245
Lecture 24: Multiple Components
253
Independent Material: Extending JPanels
258
Independent Material: Touch Events
259
Lecture 25: Intro. to Exceptions in Java
260
Lecture 25: Intro. to Exceptions in Java
• Exception:
4 An occurrence of an erroneous, unusual or
unexpected event in a program execution
4 In older languages
• Code the handling of exceptions into each area
of the program that needed it, typically with if
statements
• Some exceptions could not even be handled by
the HLL
– ex. standard Pascal cannot handle I/O errors or
division by 0
> We can still "handle" by extensive testing – but
only to prevent the error not to actually handle it
> Discuss
261
Lecture 25: Intro. to Exceptions in Java
4 In newer languages
• Exception handling built into the language
• We can separate exception handling from the
"main line" code
4 Java uses an exception handling model
similar to that used in C++
finally
{ // code to "clean up" before leaving try block
}
263
Lecture 25: Exceptions in Java
4 If an exception is handled
• Execution resumes immediately AFTER
try/catch block in which it was handled, and
does NOT return to throw point
• termination model of exception handling
– As opposed to a resumption model, where
execution resumes from where the exception
occurred
4 If an exception is propagated
• A handler is searched for by backing up
through the call chain on the run-time stack
(discuss)
• This is dynamic exception propagation
• If no handler is ever found
– Console applications crash and report
exception
– GUI applications will
265 continue to execute, but
Lecture 25: Exceptions in Java
• Catching exceptions
4 Catching a superclass of an exception will
catch subclass exception objects
catch (Exception e)
> "catch all" if no other exceptions match
4 Should list exceptions in order of most
specific to most general
– If catch above is first NO OTHER catches in the
block could ever execute
4 It is better style to be as specific as
possible with the exceptions that are
caught
• See ex23.java
267
Lecture 26: Exceptions in GUIs
269
Lecture 26: Defining Exception Classes
270
Lecture 26: Recursion
N!now
4 This = N *allows
(N-1)! us to
when N>0
complete our
N! = 1
algorithm: when N = 0
273
Lecture 26: Recursion
274
Lecture 26: More Recursion
275
Lecture 26: Implementing Recursion
276
Lecture 26: Implementing Recursion
N = 1
N <= 1? YES fact(1)
return 1
N = 2
N <= 1? NO 1 fact(2)
return (2 * fact(1)) = 2
N = 3
N <= 1? NO 2
fact(3)
return (3 * fact(2)) = 6
N = 4
N <= 1? NO 6
fact(4)
return (4 * fact(3)) = 24
24
278
Lecture 26: Recursion vs. Iteration
283
Lecture 27: More Recursion
public boolean add(T val) // same public spec (must be since)
{ // it must satisfy interface
Node curr = front;
if (curr == null) // Special case for front node
{ // Don't need to recurse in this case
front = new Node(val);
size++;
return true;
}
else // Recursively add to end of list. Note the extra
// parameter in this call for the current Node.
return addAtEnd(curr, val);
}
284
Lecture 27: More Recursion
private boolean addAtEnd(Node curr, T val)
{
if (curr.next == null) // Base case -- current Node is
{ // last node in the list. Add new Node after
// it.
curr.next = new Node(val);
size++;
return true;
}
else // We are not yet at end, recursively add to the
// next Node
return addAtEnd(curr.next, val);
}
4 See code for rest of the implementation
285
Lecture 28: Exam Two
286
Bonus Material: File Types
2) Binary Files
4 Data in the file is stored in the same way
(or in a “serialized” version) that it is
stored in the program
• We can store arbitrary bytes or we can store
“whole” data types, including primitive types
(int, double, etc.) and objects (String, any
other Serializable object type)
– We will discuss Serializable more shortly
288
Bonus Material: File Types
4 Advantages:
• Since data is already in its binary form,
reading and writing require little if any
conversion and is faster than for text files
• Non-string data can often be stored more
efficiently in its binary form than in ASCII form
4 Disadvantage:
• Data in the files is not readable except via a
specific computer program
– Ex: A Java object in a file can only be read in by
a Java program
4 There are reasons to use both of these
types of files in various applications
289
Bonus Material: IO Streams
290
Bonus Material: IO Streams
292
Bonus Material: Text vs. Binary Files
295
Extra Material: Preview of Data Structures
297
Extra Material: Preview of Data Structures
298