PowerPoint slides - University of Pittsburgh

advertisement
Course Notes for
CS 0401
Intermediate Programming
(with Java)
By
John C. Ramirez
Department of Computer Science
University of Pittsburgh
• 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:
 Starting Out with Java, From Control Structures
through Objects, Third to Sixth Editions by Gaddis
 Java Software Solutions, Fourth and Fifth Editions by
Lewis and Loftus
 Java By Dissection by Pohl and McDowell
 The Java Tutorial (click for link)
 The Java tech home page and its many sub-links:
http://www.oracle.com/technetwork/java/index.html
2
Lecture 1: Prerequisites
• Students taking CS401 should already
have some programming background:
Previous experience with Java (ex: CS 0007)
is recommended, but Python, C, C++ and VB
are also acceptable
Concepts that you are expected to be familiar
with and have used in programs include:
• Basic program structure and syntax
– How do we build programs and how do we get them
to run
• Primitive types and expressions
– Numbers, characters, operators, precedence
3
Lecture 1: Prerequisites
• Control Statements and Decisions
– Boolean expressions
– if and switch (or case) statements
– Loops (for and while)
• Methods (or functions) and parameters
– Calling methods and flow of execution
– Arguments and parameters
• Arrays and their uses
– One-dimensional only
If you do not have this background, you should
consider taking CS 0007 before taking CS0401
4
Lecture 1: Goals of the Course
• Goals for CS 0401 Course:
To (quickly) cover the basics of the Java language
(including items mentioned in the previous slide)
• These will be covered more from a Java implementa-
•
tion point of view than from a conceptual point of view
You should already be familiar with (most of) the
concepts, so learning the Java implementations should
be fairly straightforward
– Also will touch on the foundations of object-oriented
programming
• This includes Chapters 1-5 of the Gaddis text
• Those who have had CS 0007 should consider this to be
an extended review!
5
Lecture 1: Goals of Course
To learn the principles of object-oriented
programming and to see Java from an objectoriented point of view
• Objects, methods and instance variables
– References and their implications
• Creating new classes
– Syntax and logic required
• Inheritance and composition
– Building new classes from old classes
• Polymorphism and dynamic binding
– Accessing different objects in a uniform way
• Chapters 6, 8-10 of Gaddis
• We will focus a lot of attention on these chapters
6
Lecture 1: Goals of Course
Note that we are covering OOP concepts using
Java as our language
• However, the general principles of object-oriented
programming apply to any object-oriented language
– Ex: C++, Objective-C, C#, Smalltalk, etc.
• The more important goal here is to learn to program
effectively in an object-oriented way
– Understand why it is good and how to do it
7
Lecture 1: Goals of Course
To cover additional useful programming
techniques and features of Java in order to
become proficient programmers (using the Java
language)
• Array use and algorithms (sorting, searching) (Chapter
•
•
•
•
7)
Reading and Writing Files (Chapters 4, 11 + Notes)
Exception Handling (Chapter 11)
Graphical User Interfaces and Applications (Chapters
12, 13, 14, 15)
Introduction to recursion (Chapter 16)
8
Lecture 2: Why Java?
• Java
Java is an 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
– 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 interpreter is installed, the same
byte code can be executed on any platform
9
Lecture 2: Why Java?
JRE for Windows
Java
Source
Code
(.java)
Java Compiler
Java
Byte
Code
(.class)
JRE for Linux
JRE for Solaris
The same .class file can execute on any platform, as
long as the JRE is installed there
JRE for Mac
10
Lecture 2: 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 2: Getting Started with Java
• How do we execute Java programs?
First we must compile our source (.java) code
into the intermediate (.class) code
• We do this with the Java Compiler
• javac program
Next we must interpret our .class code to see
the result
• We do this with the Java Interpreter, or Java Run-time
•
Environment (JRE)
java program
12
Lecture 2: Getting Started with Java
Both programs come with the Java Development
Kit (JDK)
• This is installed on all of the lab PCs other CS machines
• The most recent version (SE 8) can be easily
downloaded and installed from the Oracle Web site:
– http://www.oracle.com/technetwork/java/index.html
– It is free!
• More on the basics of using the Java software
development kit is shown in Lab 1
– Look for it online soon -- you will do it next week
• But let’s look at an ex. and talk more about Java basics
– See ex1.java – Carefully read the comments!
13
Lecture 2: Getting Started with Java
• When you have a chance, try the following:
– Download ex1.java from the Web site onto a PC that
has the JDK installed (yours or a lab PC)
– Open a terminal (command prompt) window
– Change to the correct directory
– Compile the program: javac ex1.java
– Execute the program: java ex1
> Adding the .class extension is optional – it is assumed
even if you don’t put it there
– Show the directory to see that the .class file is now
there
• Also try the same thing from one of the Lab
workstations during your first lab session
14
Lecture 2: Getting Started with Java
Note: Most developers use an IDE (integrated
development environment) for program devel.
• Here are two possibilities:
– http://www.netbeans.org/
– http://www.eclipse.org/
> Both are available free
• These allow you to edit, compile and debug Java
•
•
programs in an easy, integrated way
However, you should realize that the final program
does NOT depend on the IDE, and you should be able
to compile and run Java programs without the IDE
I will not be emphasizing these in lecture, but you are
free to use one if you wish
15
Lecture 2: Java Basics
• What fundamental entities / abilities do we
need for any useful Java program?
A way to get data into and out of our program
• I/O
A way to create / name / variables and
constants to store our data
• Identifiers and variables
A way to manipulate / operate on the data
• Statements and Expressions
A way to make decisions and control our flow of
execution
• Control structures
16
Lecture 2: Java Basics – I/O
• (I)/O (we will defer input until after we discuss variables)
Java has a predefined object called System.out
This object has the ability to output data to the
standard output stream, which is usually the
console (display)
• This ability is via methods (procedures)
– Ex: print, println
• We pass information to the System.out object through
•
methods and parameters, and the information is then
shown on the display
For example:
System.out.println(“Hello Java Students!”);
17
Lecture 2: Java Basics – I/O
• We can output strings, values of variables and
•
•
expressions and other information using System.out
We will see more on this once we discuss variables
We will understand how System.out works more
precisely after we have discussed classes and objects
later in the term
18
Lecture 2: Java Basics – Identifiers and Variables
• Lexical elements – groups of characters
used in program code
 These form all of the parts of the program code
• Ex: keywords, identifiers, literals, delimiters
 We will discuss some of these in the Java language
Keywords
• Lexical elements that have a special, predefined
meaning in the language
• Cannot be redefined or used in any other way in a
program
• Ex: program, if, class, throws
• See p. 10 in Gaddis for complete list
19
Lecture 2: Java Basics – Identifiers and Variables
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 – Identifiers and Variables
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 – Identifiers and Variabls
• 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 – Identifiers and Variables
• 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 [we will revisit this idea often]
– Java is fairly strict about enforcing data type values
> You will get a compilation error if you assign an incorrect
type to a variable: Ex: int i = “hello”;
incompatible types
found: java.lang.String
required: int
int i = "hello";
^
23
Lecture 2: Java Basics – Identifiers and Variables
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: 1235
Ex: -39841
– Ex: String
> A sequence of characters contained within double quotes
> Ex: "Hello there CS 0401 Students!"
• See Section 2.3 for more details on literals
24
Lecture 2: Java Basics – Statements and Expressions
• 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 – Statements and Expressions
– Note: For numeric types, you 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 < short < int < long < float < double
– Ex: int i = 3.5;
possible loss of precision found
: double
required: int
int i = 3.5;
^
– Ex: double x = 100;
> This is ok
26
Lecture 3: Java Basics – Statements and Expressions
– 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 to
that variable type
Error check each of the
statements in the box to
the right
int i = 5;
int j = 4.5;
float x = 3.5;
float y = (float) 3.5;
double z = 100;
i = z;
y = z;
z = i;
j = (long) y;
j = (byte) y;
27
Lecture 3: Data and Expressions
In Java, variables fall into two categories:
Primitive Types
– Simple types whose values are stored directly in the
memory location associated with a variable
– Ex: int var1 = 100;
var1
100
– There are 8 primitive types in Java:
byte, short, int, long, float, double, char, boolean
– See Section 2.4 and ex3.java for more details on the
primitive numeric types
28
Lecture 3: Data and Expressions
Reference Types (or class types)
– Types whose values are references to objects that are
stored elsewhere in memory
– Ex: String s = new String(“Hello There”);
s
Hello There
– There are many implications to using reference types,
and we must use them with care
– Different objects have different capabilities, based on
their classes
– We will discuss reference types in more detail later
when we start looking at Objects
29
Lecture 3: Data and Expressions
Rules for declaration and use
• In Java, all variables must be declared before they can
be used Ex: x = 5.0;
> This will cause an error unless x has previously been
declared as a double variable
cannot resolve symbol
symbol : variable x
location : class classname
x = 5.0;
^
• Java variables can be initialized in the same statement
in which they are declared
– Ex: double x = 5.0;
– However, keep in mind that two things are being done
here – declaration AND initialization
30
Lecture 3: Data and Expressions
• Multiple variables of the same type can be declared
and initialized in a single statement, as long as they
are separated by commas
– Ex: int i = 10, j = 20, k = 45;
• Multiple variables of different types cannot be
•
declared within a single declaration statement
See ex2.java
31
Lecture 3: Data and Expressions
• Operators and Expressions
• Numeric operators in Java include
+, –, *, /, %
– These are typical across most languages
– A couple points, however:
> If both operands are integer, / will give integer division,
always producing an integer result – discuss implications
> The % operator was designed for integer operands and
gives the remainder of integer division
> However, % can be used with floating point as well
int i, j, k, m;
i = 19; j = 7;
k = i / j;
// answer?
m = i % j;
// answer?
32
Lecture 3: Data and Expressions
Precedence and Associativity
• What do these mean?
• Recall that the precedence indicates the order in
which operators are applied in an expression
– See Table 2-8
• Recall that the associativity indicates the order in
•
which operands are accessed given operators of the
same precedence
General guidelines to remember for arithmetic
operators:
*, /, %
same precedence, left to right associativity
+, –
same (lower) precedence, also L to R
- See Table 2-9
33
Lecture 3: More Operators
• Java has a number of convenience operators
Allow us to do operations with less typing
Ex:
X = X + 1;
Y = Y – 5;
X++;
Y –= 5;
See Section 2.6 for more details
One point that should be emphasized is the
difference between the prefix and postfix
versions of the unary operators
• What is the difference between the statements:
X++;
++X;
– Discuss
– See ex3.java
34
Lecture 4: Input and the Scanner Class
• Input
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
By default this object allows us to read data
from the console / keyboard
35
Lecture 4: Input and the Scanner Class
• In JDK releases up to 1.4
Console text input was fairly complicated to use
Objects had to be created and exceptions had to
be handled
Made it difficult to show students learning Java
simple input and output
• Consequently, textbook authors often created their
•
own classes to make console I/O easier
But they weren't standard Java, so students would not
find them useful after their courses ended
• In JDK 1.5, the Scanner class was added
36
Lecture 4: Input and the Scanner Class
Scanner is a class that reads data from the
standard input stream and parses it into tokens
based on a delimiter
• A delimiter is a character or set of characters that
•
•
distinguish one token from another
A token is all of the characters between delimiters
By default the Scanner class uses white space as the
delimiter
The tokens can be read in either as Strings
• next()
Or they can be read as primitive types
• Ex: nextInt(), nextFloat(), nextDouble()
37
Lecture 4: Input and the Scanner Class
If read as primitive types, an error will occur if the
actual token does not match what you are trying to
read
• Ex:
Please enter an int: hello
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ex3.main(ex3.java:39)
• These types of errors are run-time errors and in Java are
called exceptions
Java has many different exceptions
We'll look at exceptions in more detail later
•
•
Let's look at ex4.java
38
Lecture 4: Control Statements
• Java Statements
We already discussed some Java statements
• Declaration statement
• Assignment statement
• Method call
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 execute more than one time
39
Lecture 4: Control Statements
Linear Execution
Conditional Execution
40
Iterative Execution
Lecture 4: Boolean Expressions
• Key to many control statements in Java are
boolean expressions
Expressions whose result is true or false
• true and false are predefined literals in Java
Can be created using one or more relational
operators and logical operators
• Relational operators
– Used to compare (i.e. relate) two primitive values
– Result is true or false based on values and the
comparison that is asserted
Ex:
6 < 10 -- true because 6 IS less than 10
7 != 7 -- false because 7 IS NOT not equal to 7
41
Lecture 4: Boolean Expressions
• Java has 6 relational
operators
< <= > >= == !=
 Some boolean
expressions are more
complicated than just
a simple relational
operation
• These expressions
require logical
operators
– Operate on boolean
values, generating a
new boolean value as
a result
! && ||
– Recall their values
from a truth table
A
B
!A
A&&B
A||B
true
true
false
true
true
true
false
false
false
true
false
true
true
false
true
false
false
true
false
false
42
Lecture 4: Boolean Expressions
• Let’s look at some examples
int i = 10, j = 15, k = 20;
double x = 10.0, y = 3.333333, z = 100.0;
i < j || j < k && x <= y
(i / 3) == y
(x / 3) == y
!(x != i)
43
Lecture 4: if statement
• The if statement is very intuitive:
if (booleanexpression)
<true option>;
else
<false option>;
Each of <true option> and <false option> can
be any Java statement, including a block
• Java blocks are delimited by { } and can contain any
number of statements
else + <false option> is optional
Note parens around booleanexpression -
required
44
Lecture 5: if statement
• Nested ifs
Since both <true option> and <false option>
can be any Java statement, they can certainly
be if statements
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
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
• Thus, there is no problem for the computer
– Problem is if the programmer does not understand the
rule
– Result is a LOGIC ERROR
> Logic errors can be very problematic and difficult to
correct
> Unlike a syntax error, which prevents the program from
being compiled, with a logic error the program may run
and may seem fine
> However, one or more errors in the programmer’s logic
cause the result will be incorrect!
– Compare on board: SYNTAX ERROR, RUN-TIME
ERROR, LOGIC ERROR
• Luckily, in this case the problem is easy to correct
– How?
47
Lecture 5: while loop
• The while loop is also intuitive
while (booleanexpression)
<loop body>;
where <loop body> can be any Java statement
Logic of while loop:
• Evaluate (booleanexpression)
• If result is true, execute <loop body>, otherwise skip to
next statement after loop
• Repeat
while loop is called an entry loop, because a
condition must be met to get IN to the loop body
• Implications of this?
48
Lecture 5: Example
• Let’s now use if and while in a simple
program:
User will enter some scores and the program will
calculate the average
Let’s do this together, trying to come up with a
good solution
Consider some questions / issues:
• What is the acceptable range for the scores?
– What do we do if a score is unacceptable?
• How many scores are there?
– Do we even know this in advance?
– What to do if we do not know this in advance?
49
Lecture 5: Example
• Are there any special cases that we need to consider?
• What variables will we need to use?
– And what will be their types?
Let’s look at two possible solutions
• ex5a.java and ex5b.java
• Note that for many programming problems, there are
MANY possible solutions
50
Lecture 6: for loop
• The for loop is more complicated
Its obvious use is as a counting loop
• Goes through a specified number of iterations
for (int i = 0; i < max; i++)
{ // will iterate max times }
However it is much more general than that
for (init_expr; go_expr; inc_expr)
{
// loop body
}
• Let’s talk about this a bit
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
These expressions make the for loop extremely
flexible
52
Lecture 6: for loop
Try some examples:
• For loop to sum the numbers from N to M
N + (N+1) + … + (M-1) + M
• For loop to output powers of 2 less than or equal to K
• See forexamples.java
In effect we can use a for loop as if it were a
while loop if we’d like
However, it is more readable and less prone to
logic errors if you use it as a counting loop
Let’s look at the programs from Example 5, but
now with a for loop: ex5c.java and ex5d.java
53
Lecture 6: for loop
Since Java 1.5+, there is an additional version of
the for loop:
for (type var : iterator_obj)
<loop body>;
This version is called the "foreach" loop
• In a lot of scripting languages such as Perl and PHP,
so it was adopted into Java
However, to use it we need to understand
something about objects and iterators
This version is really cool!
We will come back and talk about this later
54
Lecture 7: switch statement
• We know that if can be used in a multiple
alternative form
If we nest statements
• Sometimes choices are simple, integral
values
In these cases, it is easier and more efficient to
use a more specialized statement to choose
• This is where switch comes in handy
• However it is kind of wacky so be careful to use it
correctly!
55
Lecture 7: switch statement
switch (int_expr)
{
case constant_expr:
…
case constant_expr:
…
default: // this is optional
}
 int_expr is initially evaluated
 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 7: switch statement
• If we want the execution of the different cases to be
exclusive of each other, we need to stop execution
prior to the next case
– We can do this using the break statement
• Switch is actually passed down to Java from C – it
•
doesn’t really fit too well with the spirit of the Java
language, but it is there and can be used
Let’s look at an example using switch
– Program to rate movies
– User enters a “star” value from 1-4 and the program
comments back on the movie quality
– See ex6.java
> Handout also shows some formatting
> See also ex6b.java
57
Lecture 7: Methods and Method Calls
• If programs are short
We can write the code as one contiguous
segment
• The logic is probably simple
• There are not too many variables
• Not too likely to make a lot of errors
• As programs get longer
Programming in a single segment gets more and
more difficult
• Logic is more complex
• Many variables / expressions / control statements
58
Lecture 7: Methods and Method Calls
• Chances of “bugs” entering code is higher
– Isolating and fixing is also harder
• If multiple people are working on the program, it is
•
•
difficult to “break up” if written as one segment
If parts need to be modified or added, it is difficult
with one large segment
If similar actions are taken in various parts of the
program, it is inefficient to code them all separately
– And can also introduce errors
– Ex: Draw a rectangle somewhere in a window
Most of these problems can be solved by
breaking our program into smaller segments
• Ex: Break some sticks!
59
Lecture 7: Methods and Method Calls
• Method (or function or subprogram)
A segment of code that is
logically separate from
the rest of the program
When invoked (i.e. called) control jumps from
main to the method and it executes
• Usually with parameters (arguments)
When it is finished, control reverts to the next
statement after the method call
• Show on board
60
Lecture 7: Functional Abstraction
• Methods provide us with functional (or
procedural) abstraction
We do not need to know all of the impl. details
of the methods in order to use them
• We simply need to know
– What arguments (parameters) we must provide
– What the effect of the method is (i.e. what does it do?)
• The actual implementation could be done in several
•
different ways
Ex: Predefined method: sort(Object [] a)
– There are many ways to sort!
• This allows programmers to easily use methods that
they didn't write
61
Lecture 7: Return Value vs. Void
• Java methods have two primary uses:
To act as a function, returning a result to the
calling code
• In Java these methods are declared with return types,
and are called within an assignment or expression
Ex:
X = inScan.nextDouble();
Y = (Math.sqrt(X))/2;
To act as a subroutine or procedure, executing
code but not explicitly returning a result
• In Java these methods are declared to be void, and are
called as separate stand-alone statements
Ex:
System.out.println(“Wacky”);
Arrays.sort(myData);
62
Lecture 7: Predefined Methods
• There are MANY predefined methods in Java
Look in the online API
These are often called in the following way:
ClassName.methodName(param_list)
• Where ClassName is the class in which the method is
defined
• Where methodName is the name of the method
• Where param_list is a list of 0 or more variables or
expressions that are passed to the method
Ex: Y = Math.sqrt(X);
• These are called STATIC methods or CLASS methods
– They are associated with a class, not with an object
63
Lecture 7: Predefined Methods
 Some
way
methods are also called in the following
ClassName.ObjectName.methodName(param_list)
• Where ObjectName is the name of a static, predefined
object that contains the method
Ex: System.out.println(“Hello There”);
• System is a predefined class
• out is a predefined PrintStream object within System
• println is a method within PrintStream
These are instance methods – associated with
an object – we will discuss these shortly
• For now we will concentrate on static methods
64
Lecture 7: Writing Static Methods
• What if we need to use a method that is not
•
•
predefined?
We will have to write it ourselves
Syntax:
public static void methodName(param_list)
{ // method body
}
public static retval methodName(param_list)
{ // method body
}
• Where retval is some Java type
• When method is not void, there MUST be a return
statement
65
Lecture 7: Writing Static Methods
Really simple example:
public static void sayWacky()
{
System.out.println(“Wacky”);
}
Now in our main program we can have:
sayWacky();
sayWacky();
for (int i = 0; i < 5; i++)
sayWacky();
• Note we are not using any parameters in this example
66
Lecture 7: Writing Static Methods
So what about the param_list?
• It is a way in which we pass values into our methods
• This enables methods to process different information
at different points in the program
– Makes them more flexible
• In the method definition:
– List of
type identifier
pairs, separated by
commas
– Called formal parameters, or parameters
• In the method call:
– List of variables or expressions that match 1-1 with the
parameters in the definition
– Called actual parameters, or arguments
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);
 Note: If method is called in same class in which it
was defined, we don’t need to use the class name
in the call
68
Lecture 7: Parameters
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
area method
Main Class
rad
answer returned
2.0
theArea 12.566…
double theArea
= area(rad);
value passed from
arg. to parameter
result returned to
main
main calls area
method
69
radius
2.0
ans
12.566…
double ans =
Math.PI * radius
* radius;
return ans;
Lecture 7: More on Parameters
• Effect of value parameters:
Arguments passed into a method cannot be
changed within the method, either intentionally
or accidentally
• Good result: Prevents accidental side-effects from
•
methods
Bad result: What if we want the arguments to be
changed?
– Ex: swap(A, B)
> Method swaps the values in A and B
> But with value parameters will be a “no-op”
- Discuss
– We can get around this issue when we get into objectoriented programming
70
Lecture 8: Local variables and scope
• Variables declared within a method are local
to that method
They exist only within the context of the method
This includes parameters as well
• Think of a parameter as a local variable that is
initialized in the method call
We say the scope of these variables is point in
the method that they are declared up to the end
of the method
• Show on board
71
Lecture 8: Local variables and scope
• However, Java variables can also be
declared within blocks inside of methods
In this case the scope is the point of the
declaration until the end of that block
• Show on board
Be careful that you declare your variables in the
correct block
• See Java Debug Help slides for more details
– debug.ppt
72
Lecture 8: Local variables and scope
• Note that either way, local variables cannot
be shared across methods
In other words, a local variable declared in one
method cannot be accessed in a different
method
We can still get data from one method to
another
• How?
To share variables across methods, we need to
use object-oriented programming
• We will see this soon!
• See ex7.java
73
Lecture 8: References and Reference Types
• Recall from Slides 28-29 that Java has
primitive types and reference types
Also recall how they are stored
• With primitive types, data values are stored directly in
the memory location associated with a variable
var1
100
• With reference types, values are references to
objects that are stored elsewhere in memory
s
Hello There
74
Lecture 8: References and Reference Types
What do we mean by “references”?
• The data stored in a variable is just the “address” of
the location where the object is stored
– Thus it is separate from the object itself
> Ex: If I have a Contacts file on my PC, it will have the
address of my friend, Joe Schmoe (stored as Schmoe, J.)
> I can use that address to send something to Joe or to go
visit him if I would like
> However, if I change that address in my Contacts file, it
does NOT in any way affect Joe, but now I no longer know
where Joe is located
• However, I can indirectly change the data in the Joe
Schmoe object through the reference
– Knowing his address, I can go to Joe’s house and steal
his Curved 105 inch 4K Ultra HD LED TV
75
Lecture 8: Classes and Objects
• What do we mean by "objects"?
Let's first discuss classes, then objects, since the
two are related
• Classes are blueprints for our data
The class structure provides a good way to
encapsulate the data and operations of a new
type together
• Instance data and instance methods
• The data gives us the structure of the objects and the
•
operations show us how to use them
Ex: A String
– Discuss
76
Lecture 8: Classes and Objects
User of the class knows the general nature of
the data, and the public methods, but NOT the
implementation details
• But does not need to know them in order to use
the class
– Ex: BigInteger
We call this data abstraction
• Compare to functional abstraction discussed
previously
Java classes determine the structure and
behavior of Java objects
To put it another way, Java objects are
instances of Java classes
77
Lecture 8: Classes and Objects
class Foo
{
int x;
void f();
…
}
Class Foo
definition
Foo object
x = 10
f()
Declaring Foo variable
Creating Foo object
Foo F;
F = new Foo(10);
F
Foo reference
78
Lecture 8: More References
• Back to references, let's now see some of
the implications of reference variables
Declaring a variable does NOT create an object
• We must create objects separately from declaring
variables
StringBuilder S1, S2;
– Right now we have no actual StringBuilder objects
– just two variables that could access them
– To get objects we must use the new operator or call a
method that will create an object for us
S1 = new StringBuilder("Hello");
– S1 now references an instance of a StringBuilder object
but S2 does not
79
Lecture 8: More References
• So what value does S2 have?
– For now we will say that we should not count on it to
have any value – we must initialize it before we use it
– If we try to access it without initializing it, we will get
an error
Multiple variables can access and alter the same
object
S2 = S1;
• Now any change via S1 or S2 will update the same
object
S1
Hello
S2
80
Lecture 8: More References
Properties of objects (public methods and public
instance variables) are accessed via "dot" notation
S1.append(" there Java maestros!");
• S2 will also access the appended object
Comparison of reference variables using ==
compares the references, NOT the objects
StringBuilder S3 =
new StringBuilder("Hello there Java maestros!");
if (S1 == S2) System.out.println("Equal"); // yes
if (S1 == S3) System.out.println("Equal"); // no
– S1 and S3 reference different objects, so they have
different addresses, regardless of the object contents
• What if we want to compare the object contents?
81
Lecture 8: More References
• We use the equals() method
– This is generally defined for many Java classes to
compare data within objects
– We will see how to define it for our own classes soon
– However, the equals() method is not (re)defined for the
StringBuilder class, so we need to convert our
StringBuilder objects into Strings in order to compare
them:
if (S1.toString().equals(S3.toString()))
System.out.println("Same value"); // yes
– We will also use the compareTo() method later
• It seems complicated but it will make more sense when
we get into defining new classes
82
Lecture 8: More references
• Note the difference in the tests:
– The == operator shows us that it is the same object
– The equals method show us that the values are in some
way the same (depending on how it is defined)
References can be set to null to initialize or
reinitialize a variable
• Null references cannot be accessed via the "dot"
•
notation
If it is attempted a run-time error results
S1 = null;
S1.append("This will not work!");
83
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!
Let's take a look at ex8.java
Side note: speaking of common errors
• Take another look at debug.ppt – it has some of the
things we just mentioned
84
Lecture 9: Intro. to Object-Oriented Programming (OOP)
• Object-Oriented Programming consists of 3
primary ideas:
Encapsulation and Data Abstraction
• Operations on the data are considered to be part of
the data type
• We can understand and use a data type without
knowing all of its implementation details
– Neither how the data is represented nor how the
operations are implemented
– We just need to know the interface (or method
headers) – how to “communicate” with the object
– Compare to functional abstraction with methods
• We discussed this somewhat already
85
Lecture 9: Intro. to OOP
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
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
86
Lecture 9: Objects and Data Abstraction
• Consider primitive types
Each variable represents a single, simple data
value
Any operations that we perform on the data are
external to that data
X+Y
X
10
Y
5
+
87
Lecture 9: Objects and Data Abstraction
• Consider the data
In many applications, data is more complicated than
just a simple value
Ex: A Polygon – a sequence of connected points
• The data here are actually:
– int [] xpoints – an array of x-coordinates
– int [] ypoints – an array of y-coordinates
– int npoints – the number of points actually in the Polygon
• Note that individually the data are just ints
– However, together they make up a Polygon
• This is fundamental to object-oriented programming (OOP)
88
Lecture 9: Objects and Data Abstraction
• Consider the operations
Now consider operations that a Polygon can do
• Note how that is stated – we are seeing what a Polygon
CAN DO rather than WHAT CAN BE DONE to it
• This is another fundamental idea of OOP – objects are
ACTIVE rather than PASSIVE
• Ex:
– void addPoint(int x, int y) – add a new point to Polygon
– boolean contains(double x, double y) – is point (x,y)
within the boundaries of the Polygon
– void translate(int deltaX, int deltaY) – move all points in
the Polygon by deltaX and deltaY
89
Lecture 9: Objects and Data Abstraction
These operations are actually (logically) PART of
the Polygon itself
int [] theXs = {0, 4, 4};
int [] theYs = {0, 0, 2};
int num = 3;
Polygon P = new Polygon(theXs, theYs, num);
P.addPoint(0, 2);
if (P.contains(2, 1))
System.out.println(“Inside P”);
else
System.out.println(“Outside P”);
P.translate(2, 3);
• We are not passing the Polygon as an argument, we
are calling the methods FROM the Polygon
90
Lecture 9: Objects and Data Abstraction
Objects enable us to combine the data and
operations of a type together into a single
entity: encapsulation
P
xpoints [0,4,4,0]
ypoints [0,0,2,2]
npoints 4
Thus, the operations
are always implicitly
acting on the
object’s data
Ex: translate means
translate the points
that make up P
addPoint()
contains()
translate()
91
Lecture 9: Objects and Data Abstraction
For multiple objects of the same class, the
operations act on the object specified
int [] moreXs = {8, 11, 8};
int [] moreYs = {0, 2, 4};
Polygon P2 = new Polygon(moreXs, moreYs, 3);
P
Both objects have
the same blueprint
P2
…but they are
distinct instances
xpoints [0,4,4,0]
ypoints [0,0,2,2]
npoints 4
xpoints [8,11,8]]
ypoints [0,2,4]
npoints 3
addPoint()
contains()
translate()
addPoint()
contains()
translate()
92
Lecture 9: Encapsulation and Data Abstraction
• Recall that we previously discussed data
abstraction
We do not need to know the implementation
details of a data type in order to use it
• This includes the methods AND the actual data
representation of the object
This concept is exemplified through objects
• We can think of an object as a container with data
and operations inside
– We can see some of the data and some of the
operations, but others are kept hidden from us
– The ones we can see give us the functionality of the
objects
93
Lecture 9: Encapsulation and Data Abstraction
• As long as we know the
method names, params
and how to use them, we
don't need to know how
the actual data is stored
 Note that I can use a
Polygon without knowing
how the data is stored OR
how the methods are
implemented
• I know it has points but I
don't know how they are
stored
• Data Abstraction!
94
P
xpoints [0,4,4,0]
ypoints [0,0,2,2]
npoints 4
addPoint()
contains()
translate()
Lecture 9: Instance Variables
• Let us look again at StringBuilder
Instance Variables
• These are the data values within an object
– Used to store the object’s information
• As we said previously, when using data abstraction we
•
don't need to know explicitly what these are in order
to use a class
For example, look at the API for StringBuilder
– Note that the instance variables are not even shown
there
• In actuality it is a variable-length array with a counter
to keep track of how many locations are being used
and is actually inherited from AbstractStringBuilder
– See source in StringBuilder.java and
AbstractStringBuilder.java – cool!!!
95
Lecture 9: Instance Variables
Many instance variables are declared with the
keyword private
• This means that they cannot be directly accessed
•
outside the class itself
Instance variables are typically declared to be private,
based on the data abstraction that we discussed
earlier
– Recall that we do not need to know how the data is
represented in order to use the type
– Therefore why even allow us to see it?
• In AbstractStringBuilder the value variable has no
keyword modifier
– This makes it private to the package
96
Lecture 9: Class Methods vs. Instance Methods
Recall that methods we discussed before were
called class methods (or static methods)
• These were not associated with any object
Now, however in this case we WILL associate
methods with objects (as shown with Polygon)
These methods are called instance methods
because they are associated with individual
instances (or objects) of a class
• These are the operations within an object
StringBuilder B = new StringBuilder(“this is “);
B.append(“really fun stuff!”);
System.out.println(B.toString());
97
Lecture 9: Class Methods vs. Instance Methods
Class methods have no implicit data to act on
• They are not associated with individual objects
• All data must be passed into them using arguments
• Class methods are called using:
ClassName.methodName(param list)
Instance methods have implicit data
associated with an Object
• Other data can be passed as arguments, but there is
•
always an underlying object to act upon
Instance methods are called using:
variableName.methodName(param list)
where variableName is a reference to an object
98
Lecture 9: Constructors, Accessors and Mutators
• Instance methods can be categorized by
what they are designed to do:
Constructors
• These are special instance methods that are called
when an object is first created
• They are the only methods that do not have a
return value (not even void)
• They are typically used to initialize the instance
variables of an object
StringBuilder B = new StringBuilder(“hello there”);
B = new StringBuilder(); // default constructor
B = new StringBuilder(10); // capacity 10
99
Lecture 9: Constructors, Accessors and Mutators
Accessors
• 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
100
Lecture 9: Constructors, Accessors and Mutators
Mutators
• 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
We use accessors and mutators to indirectly
access the data, since we don’t have direct
access – see ex9.java
101
Lecture 10: Simple Class Example
• We can use these ideas to write our own
classes
Let’s look at a VERY simple example:
• IntCircle
– Instance variable: private int radius
> Cannot directly access it from outside the class
– Constructor: take an int argument and initialize a new
circle with the given radius
– Accessors:
public double area();
public double circumference();
public String toString();
– Mutator:
public void setRadius(int newRadius);
• See IntCircle.java and ex10.java (note COMMENTS!!!)
102
Lecture 10: More on Classes and Objects
• Classes
Define the nature and properties of objects
• Objects
Instances of classes
• Let's learn more about these by developing
•
another example together
Goal:
Write a class that represents a playlist (group of
songs)
Write a simple driver program to test it
103
Lecture 10: Developing Another Example
• Remember the things we need for a class:
Instance variables
• Fill in ideas from board
Constructors
• Fill in ideas from board
Accessors
• Fill in ideas from board
Mutators
• Fill in ideas from board
104
Lecture 10: Developing Another Example
Once we have the basic structure of the class
we can start writing / testing it
A good approach is to do it in a modular, stepby-step way
• Ex: Determine some instance variables, a constructor
•
or two and an accessor to “output” the data in the
class
Write a simple driver program to test these features
– Once a method has been written and tested we don’t
have to worry about it anymore!
• Add more to the class, testing it with additional
statements in the driver program
Let's look at one example
105
Lecture 11: Intro. to Java Files
• So far
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:
What if we have a large amount of output that
we need to save?
What if we need to initialize a database that is
used in our program?
What if output from one program must be input
to another?
106
Lecture 11: Java Text Files
• In these situations we need to use files
 Most files can be classified into two groups:
Text Files and Binary Files
• We will focus on Text Files now and come back to
Binary Files later
• A text file is simply a sequence of ASCII characters
stored sequentially
• Any “larger” data types are still stored as characters
and must be “built” when they are read in
– Ex: Strings are sequences of characters
– Ex: ints are also sequences of characters, but
interpreted in a different way
107
Lecture 11: Java Text Files
– To create an actual int we need to convert the
characters into an integer – this is what the nextInt()
method in the Scanner class does
> We will discuss the conversion procedure more later
– If we want to read data into an object with many
instance variables, we can read each data value from
the file then assign the object via a constructor or via
mutators
> See PlayListTest.java
– If we want to fill an array, we can read in as many
values as we need
> We may first need to read in how many values there
are, then create the array and read in the actual data
> See PlayListTest.java and another example soon
108
Lecture 11: Java Text Files
Similarly, if we have data in our program that
we wish to save to a text file, we need to first
convert it into a sequence of characters (i.e. a
String)
• Ex: the toString() method for a class
However, now we need a different class that has
the ability to write data to a file
• There are several classes in Java that have this ability
• For now we will focus on the PrintWriter
– A PrintWriter allows us to write primitive types and
Strings to a text file
– See API
109
Lecture 11: Java Text Files
• It is fairly simple to use
– See FileTest.java
• However, when creating the file an Exception can
occur
– We will see how to handle this later
– For now we will “pass the buck”
– We do this via the “throws” clause in the method
header
> States that we are not handling the exception
> Must be stated in a method where the exception could
occur or in any method that calls a method … (since the
exception is passed on)
– See FileTest.java
110
Lecture 11: Arrays
• So far (for the most part) we have stored
data in a 1:1 fashion
1 variable : 1 value (or object)
• This works fine if we know exactly how
•
many values we will need to store, and if
there are few of them
However, consider the following scenario:
We want to input the test scores of a given
number of students, then 1) find the maximum,
2) minimum, 3) average and 4) list them in
sorted order
111
Lecture 11: Arrays
We can do the first three things using only a few
variables
• Read in current score
• Add it to the sum
• If it is less than the minimum score, make it the
•
minimum score
If it is greater than the maximum score, make it the
maximum score
Repeat until all scores have been read
Divide sum by number of scores to get average
•
•
However, what about listing them in sorted
order?
112
Lecture 11: Arrays
We can’t know the final order until all scores
have been read
• Last value could be smallest, largest or anywhere in
between
Thus, we need to store all of the values as they
are being read in, THEN sort them and print
them out
To do this we need a good way to store an
arbitrary number of values, without requiring the
same number of variables
• This is a good example of where an array is
necessary
113
Lecture 11: Java Arrays
• Java Arrays
In Java, arrays are objects, with certain
properties
• Like other reference types
Simply put, an array is logically a single
variable name that allows access to
multiple variable locations
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
114
Lecture 11: Java Arrays
• Syntax:
First, consider only PRIMITIVE TYPE data
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
115
Lecture 11: Java Arrays
Ex:
int [] myArray;
myArray = new int[20]; // size can be a variable
// or expression
These two steps can be done as one if we’d like
int [] myArray = new int[20];
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
• We can change these values via indexing
116
Lecture 11: Java Arrays
• Indexing an array
An array variable gives us access to the
“beginning” of the array
To access an individual location in the array, we
need to index, using the [] operator
Ex:
myArray[5] = 250;
myArray[10] = 2 * myArray[5];
myArray[11] = myArray[10] – 1;
• Show on board
• Discuss
117
Lecture 12: Java Arrays
• Iterating through an array
We can easily iterate through an entire array
using a loop (often a for loop)
To know “when to stop” we access the length
attribute of the array variabe – note the syntax
for (int i = 0; i < myArray.length; i++)
{
System.out.print(“Value “ + i + “ = “ + myArray[i]);
}
• Or we can iterate on the values without a counter
for (int value : myArray)
{
System.out.println(“Next value is : “ + value);
}
118
Lecture 12: Direct Access and Sequential Access
• The previous two slides demonstrate the
two basic ways of accessing arrays:
Direct Access
• Arbitrary items are accessed by providing the
appropriate index of the item
Sequential Access
• Items are accessed in index order from beginning to
end (or from end to beginning)
The usefulness of arrays comes from allowing
access in both of these ways
Let’s see both direct and sequential access of
arrays with a file example
119
Lecture 12: References and Reference Types
• Recall from previous discussions that Java
has primitive types and reference types
Also recall (once again!) how they are stored
• With primitive types, data values are stored directly in
the memory location associated with a variable
var1
100
• With reference types, values are references to objects
that are stored elsewhere in memory
s
Hello There
120
Lecture 12: Arrays as Reference Types
• Java arrays are reference types
 The array variable is a reference to the actual array
• If I assign the variable (as a whole) it does not change the
array object
 But I can alter the contents of the array through indexing
 Ex:
int [] A = new int[5];
for (int i = 0; i < 5; i++)
A[i] = 2*i;
int [] B = A;
A[3] = 5;
A = new int[4];
A[1] = 3;
A[3] = 7;
121
A
B
0
0
0
0
1
0
1
2
2
0
2
4
3
0 7
3
6 5
4
8
3
Lecture 12: Arrays as Parameters
• Recall that all Java parameters are value
A copy of the argument is passed to the param
Changes to the parameter do not affect the
argument
• What about arrays?
Still passed by value, but now what is copied is
the reference (i.e. the variable), NOT the object
• Thus the effect is that the parameter is another
•
reference to the same object that the argument is a
reference to
We cannot change the argument variable in the
method but we CAN mutate the array object!
122
Lecture 12: Arrays as Parameters
See ex11.java
Sounds confusing, right?
• Not so much once you picture it!
• Show example on board
• We will also see an example shortly
This allows us to change arrays within methods
• Ex: Read data into an array
• Ex: Remove data from an array
• Ex: Sort an array
123
Lecture 12: Searching an Array
• Often we may want to see if a value is
stored in an array or not:
“Is this book in the library?”
“Is Joe Schmoe registered for classes?”
• There are many searching algorithms
•
available, some simple and some quite
sophisticated
We will start off simple here with Sequential
Search
124
Lecture 12: Sequential Search
• Sequential Search
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
Q: What kind of loop is best for this?
• Think about what needs to be done
Let’s look at an example: ex12a.java
125
Lecture 13: Arrays of Objects
• We have now seen how to create and use
Java arrays of primitive types:
int [] data; // declare variable (reference)
data = new int[20]; // create array object
…
data[4] = 77; // index array to access locations
• How does it differ if we want arrays of
objects?
The first two steps are the same
• Declare variable
• Create array object
126
Lecture 13: Arrays of Objects
• However, remember that objects are accessed by
•
reference types
Thus, when we create the array, we have an array of
references, with no objects yet
– All of the locations are initialized to null
– We need to create objects to store in the array separately
• For example:
String [] names;
names = new String[5];
names[1] = new String(“Herb”);
names[3] = new String(“Madge”);
names[4] = new String(“Mort”);
– names[0] and names[2] are still null
– Show on board
127
Lecture 13: Arrays of Objects
• Note that we have two levels of references here
names
0
1
Herb
2
3
Madge
4
Mort
• See PlayListTest.java for another example
128
Lecture 13: Arrays as Instance Data and Composition
• When we create a new class we can have
arbitrary instance variables within it
If the instance variables are reference types (i.e.
other classes) we say we are building a new class via
composition
• We are “composing” the new class from pieces that
•
•
•
already exist, putting them together in an appropriate way
We briefly discussed this already with the PlayList class
Also sometimes called aggregation
Our use of these classes is limited to the functionality
provided as public
– We are building new classes using “off the shelf”
components, so we may have to compromise based on what
the “off the shelf” components can do
129
Lecture 13: Arrays as Instance Data and Composition
As a simple example, consider the Player class
from Assignment 2
• Inside Player you have a String for the name plus
•
•
some primitive types for the rounds and money
Thus you are composing your Player class out of the
existent String class (plus some primitives)
From within Player:
– We are a client of String, having access to the public
methods in the String class
• From outside Player:
– User may not even know a String is used since it is a
private instance variable
– String is abstracted out of the user’s view
130
Lecture 13: Arrays as Instance Data
For another example, if an array is used as an
instance variable
• We have the same access to the array within our class
•
as we would anywhere else in our program
However, from outside the class, we may not even
know the array is being used
– Encapsulation and data hiding
• See ex12b.java and Scores.java
Yet another example of composition is seen in
our previous example PlayList.java
• From outside PlayList we do not even necessarily
know that class Song is being used within PlayList
131
Lecture 13: Resizing an array
• Java array objects can be of any size
However once created, they cannot be resized
This is fine if we know how many items we will
need in advance:
System.out.println("How many integers?");
int size = inScan.nextInt();
int [] theInts = new int[size];
However, we don't always know this in advance
• User may have an arbitrary amount of data and
doesn't know how much until he/she has entered it
• Amount may vary over time
– Ex: Students in a university
132
Lecture 13: Resizing an array
So what do we do if we fill our array?
• Logically, we must "resize" it
• Physically, we must do the following:
– Create a new, larger array object
– Copy the data from the old array to the new
– Assign our reference to the new object
> Show on board
• This is not difficult syntactically, but it is important to
•
•
realize that this takes time, especially if the array is large
Clearly we don't want to do this too often
A typical approach is to double the size, so we have a lot
of free locations after the resizing
– For the "why" of this, take CS 0445!
133
Lecture 13: Resizing an array
What if we don’t have enough data to fill all of
those new slots?
• We must keep track of the number of locations that
are actually being used in the array
– i.e. we need an additional variable besides the array
data itself
• This way we can “add” elements to the end of the
•
•
•
array until it fills – only then will we have to resize
Note that the array size and number of elements
being stored in the array are not necessarily the same
This is what is done in the predefined ArrayList class
See ResizeDemo.java
134
Lecture 14: Exam One
• Exam One
135
Lecture 15: 2-D Arrays
• Two-D arrays in Java are actually arrays of
arrays
int [][] A = new int[4][8];
The first index gives us a "row", which is an
array of items
• We say this is "row major order"
The second index gives us the "column", which
is the specific item within the row
• Demonstrate on board
• To iterate through all locations we typically use nested
•
loops
See ex13.java
136
Lecture 15: ArrayLists
• Programmers can use arrays in arbitrary ways
However, many applications require a common
set of array operations
• Ex: Add an object to the end of an array
• Ex: Find an object in an array
• Ex: Iterate through an array
Rather than making the programmer implement
these operations each time they are needed, the
developers of Java have included a standard class
that already does them
ArrayList
137
Lecture 15: ArrayLists
Remember data abstraction?
• We can use an ArrayList effectively without having to
know how it is implemented
– We don’t need to know the internal data
representation
– We don’t need to know the method implementation
• We simply need to look up its functionality in the Java
API
However, it is useful for computer scientists to
understand how the ArrayList is implemented
• Helps us to better understand programming in general
• Helps us to implement similar types if necessary
Look at a simple example: ArrayL.java
138
Lecture 15:ArrayLists
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
139
Lecture 15: ArrayLists
We can also implement this type of variable size
array ourselves if we want to
• We may want to do this if our needed functionality is
•
•
very different from that of the ArrayList
We simply need to keep an array and an int to keep
track of the number of used locations
You will do a simple example of this in Lab 7
140
Lecture 16: Simple Sorting
• What does it mean to sort our data?
Consider an array, A of N items:
A[0], A[1], A[2], …, A[N-1]
A is sorted in ascending order if
A[i] < A[j] for all i < j
A is sorted in descending order if
A[i] > A[j] for all i < j
Q: What if we want non-decreasing or non-
increasing order?
• What does it mean and how do we change the
definitions?
141
Lecture 16: Simple Sorting
• How do we sort?
There are MANY ways of sorting data
• Sorting has been widely studied in computer science
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
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
142
Lecture 16: SelectionSort
• SelectionSort is very intuitive:
Idea:
Find the smallest item and swap it into index 0
Find the next smallest item and swap it into index 1
Find the next smallest item and swap it into index 2
…
Find the next smallest item and swap it into index N-2
• What about index N-1?
Let’s trace it on the board for the following
data:
0
1
2
3
4
5
6
7
35
50
20
40
75
10
15
60
143
Lecture 16: SelectionSort
Let’s look at the code
• SortInt.java and ex14.java (also see text handout)
• Note 1:
– Done in a modular way utilizing methods
– Trace it on the example from previous slide
– See result on board
• Note 2: The code shows another simple sorting
•
algorithm, InsertionSort. Look over that as well
Note 3: The sorts here are done in terms of only one
type – int
– What if we want to sort different types of data?
144
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
145
Lecture 16: Binary Search
• Consider Sequential Search again
– See Slides 124-125 and ex12a.java
Note that in the worst case we look at every
item in the array
• We say this is a linear run-time – or time proportional
to N, the number of items in the array
Can we do better?
• If the data is unsorted, no
– It could be any item, so in the worst case we’ll have to
try them all
• What if we sort the data? Will that help?
Consider example: Guess number from 1-1000
146
Lecture 16: Binary Search
• Idea of Binary Search:
Searching for a given key, K
Guess middle item, A[mid] in array
• If A[mid] == K, we found it and are done
• If A[mid] < K then K must be on right side of the array
• If A[mid] > K then K must be on left side of the array
– Either way, we eliminate ~1/2 of the remaining items
with one guess
– Show on board for a search for 40
0
1
2
3
4
5
6
7
10
15
20
35
40
50
60
75
147
Lecture 16: Binary Search
• What if item is not in array? We need a stopping
condition in the “not found” case
Think about what is happening with each test
• Either we move left index to the right or
• We move right index to the left
• Eventually they will “cross” – in this case the item is
not found
– Idea is there is “nothing left” in the array to search
– Search previous array for 25
How to code this? Not difficult!
• We can do it with a simple while loop
• See author's code: BinarySearchDemo.java
148
Lecture 16: Binary Search
• Notes:
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
149
Lecture 16: Binary Search
So is Binary Search really an improvement over
Sequential Search?
• Each “guess” removes ~½ of the remaining items
• Thus the total number of guesses cannot exceed the
number of times we can cut the array in half until we
reach 0 items
– Ex: 32
16
8
4
2
1 => 6
– Generally speaking, for N items in the array, in the
worst case we will do ~log2N guesses
– This is MUCH better than Sequential Search, which has
~N guesses in the worst case
– You will discuss this more in CS 0445 and CS 1501
150
Lecture 17: Additional OO Notes
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 should be shared amongst all
objects
151
Lecture 17: Additional OO Notes
When should I use a variable and when should
I use a method?
• Variables should be used to store the basic properties
of an object
– Can be changed through mutators but should not
become "obsolete"
• Methods should be used to calculate / determine
values using variables
– We don't want to waste time calculating something that
is set
– However, if a value may change over time, it should be
calculated
• Ex: Age for a person – variable or method?
Look again PlayList.java and PlayListTest.java
152
Lecture 17: Misc OO Notes
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
153
Lecture 17: Misc OO Notes
When copying objects, we always need to be
aware of exactly WHAT is being copied:
• Shallow copy: Assign each instance variable in the old
object to the corresponding instance variable in the
new object
– If the instance variables are themselves references to
objects, those objects will be shared
> See ex12b.java and Scores.java
• Deep copy:
– Copy primitive types normally
– For reference types, do not assign the reference; rather
“follow the reference” and copy that object as well
> Note that this process could proceed through many levels
> See ex12b.java and Scores.java
154
Lecture 17: Misc OO Notes
– Deep copies tend to be more difficult to implement than
shallow copies, due to the somewhat indefinite number
of references that will have to be “followed” for the
copy to be made
> Ex: A linked list, which you will see in CS 0445
• Neither shallow nor deep is necessarily correct or
•
•
incorrect
It depends on the needs for a given class
The important thing is to be AWARE of how your
copies are being made and the implications thereof
155
Lecture 17: Misc OO Notes
Returning references from methods
• We know a method can return only a single value
• However, that value can be a reference to an object
which can contain an arbitrary amount of data
• We already discussed composition / aggregation, so
we know an object can contain references to other
objects within it
• Question: If an instance method is to return a
reference to an object within another object, do we
– Return a reference to the actual object
– Return a reference to a copy of the object
• Answer: It depends
156
Lecture 17: Misc OO Notes
What access do we need?
• Are we just looking at the object, or do we need to
mutate it?
• If we want to mutate it, do we want the mutation to
be local (i.e. in the copy) or should it impact the
encompassing object?
• Text suggests returning copies, but, again, it depends
on the goals
– What do we want to do with it?
– What if we need to update the data?
> A reference gives us access to do this easily
157
Lecture 17: Misc OO Notes
– The alternative is to return a copy, delete the original,
update the copy, then reinsert it
– This is possible but a lot more work
• However, keep in mind that returning references to
the “originals” is more dangerous than returning
copies
– If we accidentally modify the object via the returned
reference, that will impact the original encompassing
object
– It could even invalidate the encompassing object in
some cases
> Ex: Maintaining a sorted collection of data
> If a reference to an item within the collection is returned,
the value could be changed and the overall collection
may no longer be sorted
158
Lecture 17: Misc OO Notes
The this reference
• Often in instance methods you are accessing both
instance variables and method variables
• If a method variable has the same name as an
instance variable, updates will change the method
variable, NOT the instance variable
– This is a common programming mistake!!!
• this is a pseudo-instance variable that is a selfreference to an object
– It allows disambiguation between instance variables
and method variables
• See example on board
159
Lecture 17: Misc OO Notes
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
160
Lecture 17: Misc OO Notes
• The garbage collector runs when needed to deallocate
•
the memory taken up by garbage so that it can be
reused
The details of how it works are very interesting, but
beyond the scope of this course
161
Lecture 18: Graphical Interfaces
• So far all of our programs have used
Input from the keyboard (or file)
Output to the console (or file)
• This is effective but in today’s world is not
so user-friendly
Users want to use the mouse (or a finger)
Users want windows with dialog boxes and
buttons
Users need maximum guidance with minimum
room for error
162
Lecture 18: Graphical Interfaces
• Java has all of the tools for us to design and
implement complex graphical interfaces
Graphical output and use of a mouse and other
graphical components for input
• Ex: Windows with buttons, textfields, pulldown
menus, radiobuttons, labels, and more
• To use these tools we need to learn some
Java classes and some programming theory
But once we learn how to do it we will typically
prefer it over console applications
163
Lecture 18: AWT and Swing
• The AWT (Abstract Windowing Toolkit) was
developed for the first versions of Java
Created components such as Frame, Panel,
Button, TextField, Label
• However, the look and feel of the AWT
varied on different windowing systems
The same AWT Java program looks different
when run on MS Windows machines, MACs and
Sun Workstations
• This is because the underlying windowing systems on
those machines differ
164
Lecture 18: AWT and Swing
• Since a goal of Java is to be platform
•
independent, its look and feel should also be
platform independent
Swing was developed from Java v. 1.2 to be
more consistent in its look and feel across all
platforms
It also adds some extra features that did not
exist in the AWT
Many Swing components are similar to AWT in
name, but with a “J” in front
• Ex: JFrame, JPanel, JButton, JTextField, JLabel
165
Lecture 18: JavaFX
• 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
As more programming moves toward Web
interfaces, JavaFX will gain in popularity
Can be used with Swing as well, so learning
Swing is still a good thing
166
Lecture 18: JavaFX
JavaFX is covered in the text, and I encourage
you to explore it
• However, the text discussion requires a software
download which is not currently in our labs
We may discuss JavaFX a bit more later if we
have time
For now we will focus on Swing
• Much of the approach is the same, as we will discuss
167
Lecture 18: JFrames and JApplets
• JFrames are objects that will be the
windows in graphical applications
We can draw/paint graphics within them
We can place and manipulate graphical
components within them
• JApplets are similar in their functionality to
JFrames
However, they are run within the context of
another program (i.e. a Web browser)
Used to be very popular, but not so much any
more
168
Lecture 18: JFrames
• We will focus on JFrames
To use them we:
• Create a JFrame object
• Size it as desired
• Show it on the display
Once we have a JFrame we can do a LOT with it
• Draw graphics within it
• Store and organize other components
• React to events such as mouse movement and
clicking
• We will gradually be looking at all of these things
169
Lecture 18: JLabels
• JLabels are simple components to show
formatted text on the display
We can set the font type, size and color
We can set and change the text itself as desired
throughout program execution
• Let’s look at a very simple example:
Create a JFrame, then put a JLabel in it and
display it
See ex15a.java
• See the comments to determine how the various
objects are created and set up properly
170
Lecture 18: Simple Example
Note that this example does not really do much
• No interaction with the user
But it does show us some of the basic setup for
graphical applications
Let’s now add a bit more functionality
• Add a button that user can click to change the color of
the label text
171
Lecture 18: JButtons
• JButtons are simple components that can also
show text on the display
However, in addition to showing text, they also
respond to clicks of the mouse
• If a user clicks the mouse within a JButton, an
•
ActionEvent object is generated in response
This object is passed automatically to an ActionListener
object
– The ActionListener must be registered to “listen” to the
JButton
– ActionListener is actually an interface with the single
method actionPerformed()
> We will discuss interfaces formally soon
172
Lecture 18: Event-Driven Programming
– 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
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)
173
Lecture 18: Event-Driven Programming
JButton
AE
ActionListener object
1) JButton is clicked
2) ActionEvent (AE)
generated
3) Event passed to
ActionListener
4) actionPerformed
executed
Note that because the ActionEvent is
passed to the actionPerformed
method, the method can get
information from the ActionEvent
through its accessor methods
public void
actionPerformed(
{
// code to execute
}
174
)
Lecture 18: Event-Driven Programming
There are many different types of events in Java
programs, but the basic idea for all of them is
similar to that shown in the previous slide:
• In some way an event is triggered
• Triggered object generates an event object
• Event object is passed to some event listener object
• Method in the event listener executes to handle the event
It is important that event handlers are linked to the
appropriate event generators
• Otherwise event will still be generated but will not be
responded to
Do example in class
•
See ex15b.java
175
Lecture 18: Event-Driven Programming
Note that ex15b.java has a single JButton and a
single listener
• If we have multiple buttons / event generators we
•
could share listeners amongst them or allocate
individual listeners for the generators
The choice is based on our goals and what we want
the program to do
See a simple example of this
• ex15b2.java
– 2 buttons, one listener
• ex15b3.java
– 2 buttons, two listeners
176
Lecture 19: Another Example
• Let’s look at another simple example:
Toggle Button
• Click it once and it does an action
• Click it again and it does a different action
– Each click it alternates between the two actions
The setup of this program is very similar to
ex15b.java
• Only difference is what the listener is doing
See ex15c.java
177
Lecture 19: Multiple Components
• If we want multiple components, we need to
determine how to lay them out
To do this we use a layout manager
• These determine how components appear in a
window and how much space is allocated for them
There are many layout managers in Java
• Two simple ones are:
– FlowLayout
> Places components as we read a book – left to right top
to bottom
– GridLayout
> Places components in an equally sized 2-dimensional
rectangular grid
178
Lecture 19: Multiple Components
• Multiple components may also need to
interact with each other
Listener for one component may need to access
the other component
• In this case we must allow the listener access to all
•
•
components involved -- so it must be different from
how we did it in ex15b.java and ex15c.java
In those programs the listener could access the
button that created the event through the getSource()
method
However, other than that the listener is isolated from
the variables in the main program
179
Lecture 19: Multiple Components
Ex: Consider a JTextField
• This is a component in which the user can enter text
• Once user hits “Enter”, the component generates an
ActionEvent
– Same event generated by a JButton
• We can use this to process input from a user
– For example to change the contents of a JButton
• However, in this case the listener must be able to
access both the object that generated the event (the
JTextField) and the object it needs to change (the
JButton)
– To do this the objects must be set up in a different way
so that the variables can be shared
180
Lecture 19: Multiple Components
• Let’s look at another example
Our JFrame will have a JButton and a JTextField
• The JButton will behave as in ex15b – clicking it will
change the color of the text
• The JTextField will allow us to enter new text for the
JButton
To allow the second option we must set up our
components and listeners in a different manner
See ex15d.java
181
Lecture 19: More on GUIs
• What if we want different parts of our
window laid out differently?
There is a GridBagLayout that allows for
arbitrary configurations, but it is quite
complicated to use
A simpler solution is to subdivide our window
We can do this with JPanels
• Have most of the functionality of JFrames, except
•
without the title/menu bar
Can store other components and lay them out using a
layout manager
182
Lecture 19: More on GUIs
So now we can use the layout manager of our
JFrame to store our JPanels
• We can then use our JPanels to store our other
components
See drawing on board
•
When doing this, a common way of laying out
our JFrame is BorderLayout
• BorderLayout subdivides our window into 5 areas
– NORTH, SOUTH, EAST, WEST, CENTER
• We can put a component in each area or just some of
•
them
If the component is a JPanel, we can then put our
other components within that
183
Lecture 19: More on GUIs
• How to terminate a graphical program?
So far we have set an option in the JFrame that
causes the program to stop when it closes:
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
However, we may want to quit in some other way
• Ex: A menu option or a "quit" button
• We can do this with the
System.exit(0);
method call
• However, we need to make sure the method is called
only when we really want to quit the program
– Use a listener (ex: ActionListener)
• See Counters.java
184
Lecture 20: More on JPanels
• What if we want to encapsulate data within
a JPanel?
The JPanel class contains instance variables and
methods, but these are geared toward its
graphical function
• We can attach components to it but this is solely for
display purposes
The variables are still outside the JPanel
•
What if we want it to also store and manipulate
our own data in the JPanel?
• We need to extend it using inheritance
185
Lecture 20: Extending JPanels
We will talk about inheritance formally soon
For now we just need the basics
• When we extend a class in Java, the new class has all
of the functionality of the original, plus any new
functionality that we give it via additional instance
variables and methods
So, we can do this:
class MyPanel extends JPanel
• We can then put whatever we’d like into our new
•
class
We can add new instance variables, methods or both
186
Lecture 20: Extending JPanels
Idea:
• A JPanel already encapsulates a component which can
be displayed and can store / manage other
components
• By extending it we can encapsulate any other data /
methods we would like and give it a new functionality
– We extend it, or add more to what was already there
Let’s look at two examples
• Counters2.java
– Same functionality as Counters.java, but done via
extending JPanel
• JPanelDemo.java and LabelButton.java
– Can help with Assignment 4
187
Lecture 20: Intro. to Interfaces
• In our graphical examples so far we have
used ActionListener objects to handle events
But ActionListener is not a class
And we use different classes, all of which we call
ActionListeners
How can this be?
• ActionListener is an interface
• This is different from a class
• But what is it and how does it work?
– To really understand interfaces, we need to understand
inheritance and polymorphism
– However, for now we will discuss them superficially
188
Lecture 20: Intro. to Interfaces
• A Java interface is a named set of methods
• However, no method bodies are given – just the
•
headers
Static constants are allowed, but no instance variables
are allowed
No static methods are allowed (changed in Java 8)
•
Any Java class (no matter what its inheritance)
can implement an interface by implementing the
methods defined in it
• Essentially an interface is stating an ABILITY of the
class
A given class can implement any number of
interfaces
189
Lecture 20: Intro. to Interfaces
Ex:
public interface Laughable
{
public void laugh();
}
public interface Booable
{
public void boo();
}
• Any Java class can implement Laughable by
implementing the method laugh()
• Any Java class can implement Booable by
implementing the method boo()
190
Lecture 20: Intro. to Interfaces
• 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
191
Lecture 21: Intro. to Interfaces
An interface variable can be used to reference any
object that implements that interface
• Note that the same method name (ex: laugh() below)
•
may in fact represent different code segments in
different classes
But only the interface methods are accessible
through the interface reference
• Thus, even though a single class may implement many
interfaces, if it is being accessed through an interface variable,
the methods in the other interfaces are not available
– The interface masks the object such that only the interface
methods are visible / callable
– If other methods are attempted to be accessed, a compilation
error will result
192
Lecture 21: Intro. to Interfaces
Ex:
Laughable L1, L2, L3;
L1 = new Comedian();
L2 = new SitCom(); // implements Laughable
L3 = new Clown(); // implements Laughable
L1.laugh(); L2.laugh(); L3.laugh();
L1.boo();
// illegal even though Comedian has
// the boo() method
((Booable)L1).boo(); // this is ok since we cast
• See ex16.java
Interfaces are closely related to inheritance and
polymorphism
• These are discussed in Chapter 10 of the text
• We will revisit interfaces in more detail soon
193
Lecture 21: Wrappers
• Much useful Java functionality relies on
classes / objects
Inheritance (Chapter 10)
Polymorphic access (Chapter 10)
Interfaces (Chapter 10)
• Unfortunately, the Java primitive types are
NOT classes, and thus cannot be used in
this way
If I make an array of Object or any other class,
primitive types cannot be stored in it
194
Lecture 21: Wrappers
Wrapper classes allow us to get around this
problem
• Wrappers are classes that “wrap” objects around
primitive values, thus making them compatible with
other Java classes
– We can't store an int in an array of Object, but we
could store an Integer
• Each Java primitive type has a corresponding wrapper
– Ex: Integer, Float, Double, Boolean
• Ex: Integer i, j, k;
i = new Integer(20);
j = new Integer(40);
195
Lecture 21: Wrappers
The wrapper classes also
provide extra useful
functionality for these
types
• Ex: Integer.parseInt() is a
•
static method that enables
us to convert from a String
into an int
Ex: Character.isLetter() is a
static method that tests if
a letter is a character or
not
See more in API
196
Integer
int
Double
double
Lecture 21: Wrappers and Casting
However, arithmetic operations are not defined
for wrapper classes
• So if we want to do any “math” with our wrappers,
•
•
we need to get the underlying primitive values
If we want to keep the wrapper, we then have to
wrap the result back up
Logically, to do the following:
k = i + j;
• The actual computation being done is
k = new Integer(i.intValue() + j.intValue());
– In words: Get the primitive value of each Integer
object, add them, then create a new Integer object
with the result
197
Lecture 21: Wrappers
In Java 1.4 and before:
• Programmer had to do the conversions explicitly
– Painful!
In Java 1.5 autoboxing was added
• This does the conversion back and forth automatically
• Saves the programmer some keystrokes
• However, the work STILL IS DONE, so from an efficiency
point of view we are not saving
• Should not use unless absolutely needed
We will see more on how wrappers are useful after
we discuss inheritance, polymorphism and
interfaces
198
Lecture 21: Parsing Primitive Types
One ability of the wrapper classes is static
methods to parse strings into the correct
primitive values
• Ex: Integer.parseInt(), Double.parseDouble(),
•
•
Boolean.parseBoolean()
These enable us to read data in as Strings, then
convert to the appropriate primitive type afterward
Ex: “12345” in a file is simply 5 ASCII characters:
49 50 51 52 53
• To convert it into an actual int requires processing the
characters (as we discussed previously)
– However, let’s now see the actual algorithm
199
Lecture 21: Parsing Primitive Types
– We know ‘0’ is ASCII 48
– So our integer is
(49-48)x104 + (50-48)x103 + (51-48)x102
+ (52-48)x101 + (53-48)x100
– This can be done “manually” in a nice efficient way
using a simple loop, and is what the parseInt() method
does
– Let’s do it ourselves to see how it can be done
– Any suggestions on how to start?
• See MyInteger.java and ex17.java
200
Lecture 21: Character class
• The Character wrapper class provides many
useful methods:
Ex:
• Case conversion, checking for letters, checking for
digits
Can be useful when we are parsing text files
ourselves
• The String class has some very useful
methods as well
See text for a lot of them (ex: split())
See ex18.java
201
Lecture 22: Inheritance
• Sometimes we want to build a new class
that is largely like one we already have
Much of the functionality we need is already
there, but some things need to be added or
changed
• We can achieve this in object-oriented
languages using inheritance
Attributes of a base class, or superclass are
passed on to a subclass
202
Lecture 22: Inheritance and “is a”
We can understand this better by considering the
“is a” idea
• A subclass object “is a” superclass object
• However, some extra instance variables and methods
may have been added and some other methods may
have been changed
Note that “is a” is a one way operation
• Subclass “is a” superclass (specific "is a" general)
– With modifications / additions
• Superclass is NOT a subclass (general not "is a"
specific)
– Missing some properties
Ex: Button “is a” Component
203
Lecture 22: Inheritance and “is a”
JComponent
is a
AbstractButton
is a
JButton
is a
is a
JPanel
JLabel
• AbstractButton, JLabel and JPanel are all
JComponents
 JButton “is a” AbstractButton
• However, a JComponent is not
necessarily an AbstractButton, JLabel or
JCheckbox
 “Is a” is a one way relationship
204
Lecture 22: Extending Classes
• Inheritance in Java is implemented by
extending a class
public class NewClass extends OldClass
{
…
We then continue the definition of NewClass as
normal
However, implicit in NewClass are all data and
operations associated with OldClass
• Even though we don’t see them in the definition
• We saw this already in Counters2.java, where our new
class extended JPanel
205
Lecture 22: private, public and protected
We already know what public and private
declarations mean
The protected declaration is between public and
private
• Protected data and methods are directly accessible in
the base class and in any subclasses (and in the current
package)
However, they are not directly accessible anywhere else
•
Note that private declarations are STILL PART of
subclasses, but they are not directly accessible
from the subclass’ point of view
• See SuperClass.java, SubClass.java, Subby.java and
ex19.java
206
Lecture 22: Inheritance Example
• As another example
Compare MixedNumber class and MixedNumber2
class
Both utilize the RationalNumber class from the
Lewis & Loftus text to do most of the "work"
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 ex20.java, RationalNumber.java,
MixedNumber.java and MixedNumber2.java
207
RationalNumber
int numerator
int denominator
-------------add(), subtract(),
multiply(),
divide(), etc.
MixedNumber2 extends
RationalNumber
add(), subtract(),
multiply(),
divide(), etc.
Lecture 22: Inheritance Example
Composition:
MixedNumber class utilizes a
RationalNumber object.
Methods in MixedNumber
must manipulate the
RationalNumber object as a
"client", since it has no
special relationship to
RationalNumber
RationalNumber
int numerator
int denominator
-------------add(), subtract(),
multiply(),
divide(), etc.
208
MixedNumber
int whole
RationalNumber frac
-------------add(), subtract(),
multiply(),
divide(), etc.
Inheritance: MixedNumber2
class is a RationalNumber, but
with modifications. Ex: The
numerator in MixedNumber2 is
that defined in RationalNumber.
Methods in RationalNumber can
be used directly, and new
versions are only needed where
the return type must be
MixedNumber2.
Lecture 23: Method Overriding
• In the previous examples, we used
inheritance to
Add some new functionality / methods utilizing
existing instance variables
Add some new functionality with additional
instance variables
• However, sometimes we want to extend a
class and change some of the things it does
In this case we may want to keep a method
header the same as it was
Yet we might want to change its body
209
Lecture 23: Method Overriding
Idea:
• The subclass type has the same basic structure as its
superclass, but has some different behaviors or
different ways of performing identically named tasks
Ex:
• Consider a simple array list to maintain data in
positional order
– Can add or remove an item from an arbitrary location
or just add at the end
– Can access or change the value at an existing location
– This is the basic functionality of the predefined
ArrayList class
– See MyAList.java
210
Lecture 23: Method Overriding
• Now consider an array list in which the data must be
•
maintained in some type of sorted order
What are the differences?
– Can no longer add in an arbitrary location
> Must be in the correct sorted order
– Can we change the data at a location?
> No? Maybe a way to go
> Yes? What should we do in this case
• We could implement this class from scratch but there
are a lot of things that MyAList does that we can use
–
–
–
–
Same basic data
Same get() method
Same remove(loc) method
Same resize() method
211
Lecture 23: Method Overriding
So what we want is
• A new class that fundamentally is a MyAList, but with
some differences
One way we can define this is using inheritance
and method overriding
Method Overriding
• A method defined in a superclass is redefined in a
•
•
subclass with an identical method signature
For subclass objects, the definition in the subclass
replaces the version in the superclass
See SortAList.java and Override.java
212
Lecture 23: Java Class Hierarchy
• In Java, class Object is the base class to all
other classes
If we do not explicitly say extends in a new class
definition, it implicitly extends Object
The tree of classes that extend from Object and
all of its subclasses is called the class hierarchy
All classes eventually lead back up to Object
This will enable consistent access of objects of
different classes, as we shall see shortly
213
Lecture 23: Polymorphism
• Idea of polymorphism
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
Generally, it allows us to mix methods and objects
of different types in a consistent way
Earlier in the text, one type of polymorphism was
already introduced
214
Lecture 23: Method Overloading
This is called ad hoc polymorphism, or method
overloading
• In this case different methods within the same class or
in a common hierarchy share the same name but have
different method signatures (name + parameters)
public static float max(float a, float b)
public static float max(float a, float b, float c)
public static int max(int a, int b)
– Note: The return value is not considered to be part of the
signature
• When a method is called, the call signature is matched
to the correct method version
– Note: This is done during program COMPILATION
215
Lecture 23: Method Overloading
• If an exact signature match is not possible, the one
that is closest via “widening” of the values is used
– “Widening” means that values of “smaller” types are
cast into values of “larger” types
> Ex: int to long
int to float
float to double
– Fewer widenings provides a "closer" match
• If two or more versions of the method are possible
with the same amount of “widening”, the call is
ambiguous, and a compilation error will result
See ex21.java
Note: This type of polymorphism is not
necessarily object-oriented – can be done in
non-object-oriented languages
216
Lecture 24: Polymorphism
• Subclassing Polymorphism
 Sometimes called “true polymorphism”
 Consists basically of two ideas:
1) Method overriding (as previously discussed)
• 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
217
Lecture 24: Polymorphism
2) Dynamic (or late) binding
• The code executed for a method call is associated
with the call during run-time
• The actual method executed is determined by the
type of the object, not the type of the reference
 Allows superclass and subclass objects to be
accessed in a regular, consistent way
• Array or collection of superclass references can be
•
used to access a mixture of superclass and subclass
objects
This is very useful if we want access collections of
mixed data types (ex: draw different graphical
objects using the same draw() method call for each)
218
Lecture 24: Polymorphism
• Ex. Each subclass
overrides the move()
method in its own way
Animal [] A = new Animal[3];
A[0] = new Bird();
A[1] = new Person();
A[2] = new Fish();
for (int i = 0; i < A.length; i++)
A[i].move();
move()
move()
• References are all the same,
but objects are not
• move() method invoked is that
associated with the OBJECT,
NOT with the reference
219
move()
Lecture 24: Object, Method and Instance Variable Access
• When mixing objects of difference classes,
some access rules are important to know:
Superclass references can always be used to
access subclass objects, but NOT vice versa
Animal A = new Bird(); // this is ok
Bird B = new Animal(); // this is an ERROR
Given a reference R of class C, only methods
and instance variables that are defined (initially)
in class C or ABOVE in the class hierarchy can be
accessed through R
• They still exist if defined in a subclass, but they are
not accessible through R
220
Lecture 24: Object, Method and Instance Variable Access
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
221
Lecture 24: Object, Method and Instance Variable Access
• Note that we can access these methods or instance
variables INDIRECTLY if an overridden method
accesses them
– So, for example, if the move() method as defined in
class Fish called the getWaterType() method, and we
called
A.move();
– It would work fine
• Also note that if we cast a reference to a different
type, and the object is not that type (or a subtype),
we will get ClassCastException
– If unsure, test using instanceof operator before casting
• See ex22.java for an example
222
Lecture 24: 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 data and
methods are ACCESSIBLE
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
223
Lecture 24: Abstract Classes
• Abstract classes
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
This is an abstract class
• Keyword abstract used in declaration
• One or more methods declared to be abstract and are
thus not implemented
• No objects may be instantiated
224
Lecture 24: Abstract Classes
Subclasses of an abstract class must implement
all abstract methods, or they too must be
declared to be abstract
Advantages
• Can still use superclass reference to access all
subclass objects in polymorphic way
– However, we need to declare the methods we will need
in the superclass, even if they are abstract
• No need to specifically define common data and
methods for each subclass - it is inherited
Helps to organize class hierarchy
•
See ex23.java
225
Lecture 24: Assignment 5 Help
We have already discussed using graphical
components such as JButtons, JLabels and
JPanels
We have also used ActionEvents and
ActionListeners to allow user interaction
Java also allows programmers to draw / render
images in a JFrame or a JPanel
Java also allows MouseEvents to handle mouse
actions and motion
• See Mousey.java
226
Lecture 24: Assignment 5 Help
Utilizing MouseEvents, a JPanel, some
predefined graphical classes and inheritance, we
can write programs to draw / manipulate figures
on the screen
• See MyRectangle2D.java and DrawDemo.java
In Assignment 5 you will extend the Polygon
class to enable it to be used in a simple program
to draw primitive graphical scenes
• See Assig5.java and the MyPoly.java outline
227
Lecture 25: More Interfaces
• Java allows only single inheritance
A new class can be a subclass of only one parent
(super) class
There are several reasons for this, from both the
implementation (i.e. how to do it in the compiler
and interpreter) point of view and the programmer
(i.e. how to use it effectively) point of view
However, it is sometimes useful to be able to
access an object through more than one
superclass reference
228
Lecture 25: More Interfaces
We may want to identify an object in multiple
ways:
• Based on its inherent nature (i.e. its inheritance chain)
– Ex: A Person
• Based on what it is capable of doing
– Ex: An athlete
– Ex: a pilot
• Recall from previous discussion that we can think of
an interface as an "ability"
– Classes that implement an interface have the ability
defined by the interface methods
– They can also be identified by this ability
229
Lecture 25: Interfaces
 Also recall our previous discussion of polymorphism
• This behavior also applies to interfaces – the interface acts as a
superclass and the implementing classes implement the actual
methods however they want
 An interface variable can be used to reference any object
that implements that interface
• However, only the interface methods are accessible through
the interface reference
 Recall our previous example:
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();
• Same polymorphic behavior we saw with Animal hierarchy
230
Lecture 25: "Generic" Operations
How does it benefit us to be able to access
objects through interfaces?
• Sometimes we are only concerned about a given
property of a class
– The other attributes and methods still exist, but we
don't care about them for what we want to do
• For example: Sorting
– We can sort a lot of different types of objects
>
>
>
>
Various numbers
People based on their names alphabetically
Movies based on their titles
Employees based on their salaries
– Each of these classes can be very different
– However, something about them all allows them to be
sorted
231
Lecture 25: “Generic” Operations
They all can be compared to each other
• So we need some method that invokes this
comparison
In order to sort them, we don't need to know or
access anything else about any of the classes
• Thus, if they all implement an interface that defines
the comparison, we can sort them all with a single
method that is defined in terms of that interface
Huh? ¿Qué?
• Perhaps it will make more sense if we develop an
example…but first we will need some background!
232
Lecture 25: “Generic” Operations
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
•
Consider what we need to know to sort data:
• is A[i] less than, equal to or greater than A[j]
Thus, we can sort Comparable data without
knowing anything else about it
• Awesome! Polymorphism allows this to work
233
Lecture 25: “Generic” Operations
Think of the objects we want to sort as “black
boxes”
• We know we can compare them because they
•
implement Comparable
We don’t know (or need to know) anything else
about them
– Show on board
Thus, a single sort method will work for an array
of any Comparable class
• Let’s write it now, altering the code we already know
•
from our simple sort method
See SortAll.java and ex24.java
– Also see SortAllT.java and ex24T.java
234
Lecture 26: Intro. to Exceptions in Java
• Run-time errors happen
User enters incorrect input
Resource is not available (ex. file)
Logic error (bug) that was not fixed
• For Production software
Having a program "crash" is a HIGHLY
UNDESIRABLE thing
• Users think software is no good
• Lose confidence
235
Lecture 26: Intro. to Exceptions in Java
• Exception:
An occurrence of an erroneous, unusual or
unexpected event in a program execution
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
> Ask for integer and user enters a text string – what do
you do?
> Discuss
236
Lecture 26: Intro. to Exceptions in Java
In newer languages
• Exception handling built into the language
• We can separate exception handling from the "main
line" code
Java uses an exception handling model similar to
that used in C++
Exceptions are objects that are
thrown …
and catched
Some exceptions are built into the language
Others can be created and thrown by the
programmer
237
Lecture 26: Exceptions in Java
• Java exception handling
Exceptions are handled using try-catch blocks
try
{
// code that will normally execute
}
catch (ExceptionType1 e)
{
// code to "handle" this exception
}
catch (ExceptionType2 e)
{
// code to "handle" this exception
}
... // can have many catches
finally
{
// code to "clean up" before leaving try block
}
238
Lecture 26: Exceptions in Java
If all goes well (no exceptions occur)
• Code in try block is executed, followed by code in
(optional) finally block
If an exception occurs anywhere in the try block
• Execution immediately jumps out of the try block (i.e.
the try block does not complete its execution)
• An exception handler is sought in a catch block
– If exception is handled in a catch block, that block
executes followed by the (optional) finally block
– If the exception is not handled in a catch block, the
(optional) finally block is executed and then the
exception is propagated
Note that in all cases the finally block is
executed if it is present
239
Lecture 26: Exceptions in Java
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
If an exception is propagated
• A handler is searched for by backing up through the
call chain on the run-time stack
• This is dynamic exception propagation
• If no handler is ever found
– Console applications crash and report exception
– GUI applications will continue to execute, but may
be in an inconsistent state – more soon
240
Lecture 26: Exceptions in Java
• Checked vs. Unchecked exceptions
Checked exceptions
• If a method does NOT handle these, the method
MUST state that it throws them
– Done in a throws clause in the method header
• These include IOException, and InterruptedException
(and their subclasses)
– That is why various handouts throughout the term have
had some exception handling – it was required
Unchecked exceptions
• Method not required to explicitly "throw" these
• These include RunTimeException and Error
241
Lecture 26: Exceptions in Java
• Catching exceptions
Catching a superclass of an exception will catch
subclass exception objects
catch (Exception e)
> "catch all" if no other exceptions match
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
It is better style to be as specific as possible
with the exceptions that are caught
• See ex25.java
242
Lecture 26: Exceptions in GUIs
• GUIs run using multiple execution threads
A thread is a logically separate execution chain
that shares the same data
• See board
Events in GUIs are generated and handled by
threads
In future courses you may see how to use
threads yourselves
For now we just want to know the effect of
exceptions on applications that have multiple
threads
243
Lecture 26: Exceptions in GUIs
If the thread in which the exception was thrown
does not handle it, the thread will terminate
• However, other threads will continue the execute, so
GUI may continue to run
This does NOT mean that it will run correctly
• The exception may have caused a problem that
persists in the GUI
• Don't think that because the window didn't close that
everything is ok
It is best to always try to anticipate and handle
exceptions in GUIs
244
Lecture 26: Defining Exception Classes
Just like most Java classes, Exception classes
can be extended
• There are many predefined exceptions, designed for
•
•
different circumstances
However, we may have a specific issue that we’d like
to create a new exception class for
Note that if our class is a subclass of some other
exception class, it can be caught using the superclass
exception, or the subclass exception
See MiniCalcTwo.java, DoMathInt.java,
DoMathIntCheck.java
245
Lecture 27: Recursion
• A Java method can call any other public
Java method
main() is just a method itself, and we have
called other methods from it
Thus, a method should be able to call itself – we
call this a RECURSIVE CALL
• Since it is a method
At first thought this seems odd or even
impossible – why would we want to do this?
However, it will be very useful in a lot of
different programming approaches
246
Lecture 27: Recursion
Before we look at the programming in detail, let’s
try to get the idea down, using math
Some mathematical functions are in fact defined
recursively
• Example in text: Factorial
N! = N * (N-1)!
• Note that the function is defined in terms of itself, but
with an important change:
– The “recursive call” is smaller in size (N-1) than the original
call (N)
– This is vital to recursion being viable
• Let’s trace 4! in this way to see what happens (see
board)
– Uh oh!
247
Lecture 27: Recursion
What we are missing in the previous slide is a
condition that allows the recursion to stop
• Every recursive algorithm must have some terminating
condition, to keep it from recursing “forever”
We call this the BASE CASE
•
What is the base case for factorial?
0! = 1
This now allows us to complete our algorithm:
N! = N * (N-1)!
N! = 1
when N > 0
when N = 0
248
Lecture 27: Recursion
 Three important rules for any recursive
algorithm:
1) There must be some recursive case, in which the
2)
3)
algorithm “calls itself”
There must be some base case, in which no
recursive call is made
The recursive calls must lead eventually to the base
case
– Usually by “reducing” the problem size in some way
 Don’t forget these!
249
Lecture 27: More Recursion
Let’s look at another example:
• Calculating an integer power of another integer
MN = M * MN-1
N > 0 recursive case
• Don’t forget the base case
N = 0 base case
MN = 1
• The actions we take are slightly different from
factorial, but the basic idea is similar
Trace this on board
• Note how first call made is last call to complete
• This is important in the implementation of recursion
250
Lecture 27: Implementing Recursion
• So how do we implement recursion?
Luckily the computer code is very similar to the
mathematical functions
Consider factorial below
• Note that the recursive call is made within the return
statement
– This is fine – return is done AFTER call completes
public static int fact(int N)
{
if (N <= 1)
return 1;
else
return (N * fact(N-1));
}
251
Lecture 27: Implementing Recursion
• How does recursion actually work?
Each time a method is called, an activation
record (AR) is allocated for it
• This consists of memory for the parameters and local
variables used in the method
Each new activation record is placed on the top
of the run-time stack
When a method terminates, its activation record
is removed from the top of the run-time stack
Thus, the first AR placed onto the stack is the
last one removed
252
Lecture 27: Implementing Recursion
N = 1
N <= 1? YES
return
N = 2
1
N <= 1? NO
return (2 * fact(1)) =
N = 3
2
N <= 1? NO
return (3 * fact(2)) =
N = 4
6
N <= 1? NO
return (4 * fact(3)) =
1
fact(1)
fact(2)
2
6
24
fact(3)
fact(4)
24
253
Lecture 27: Recursion vs. Iteration
Some recursive algorithms can also be easily
implemented with loops
• Both factorial and power can easily be done in this
•
way
When possible, it is usually better to use iteration,
since we don’t have the overhead of the run-time
stack (that we just saw on the previous slide)
Other recursive algorithms are very difficult to
do any other way (ex: Towers of Hanoi in text)
You will see more about recursion in CS 0445
For now, let’s look at recursion.java
Also look at many handouts in the text
254
Lecture 28: Exam Two
• Same length and general format as Exam
•
•
One
Focus on Lectures 15-27
See online review materials and practice
questions
255
Extra Material: File Types
1) Text Files – discussed previously
Advantage of text files:
• Can read them outside of the program by many
different editors or programs
• Easy to create
Disadvantage of text files:
• Must be converted into the desired types as they are
read in (as demonstrated with parseInt)
– This takes time to do and slows I/O
• Not the most efficient way to store non-String data
– Ex: int 12345678 requires 8 bytes in a text file, but only
needs 4 bytes in the computer as an int or in a binary
file
256
Extra Material: Binary Files
2) Binary Files
 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
257
Extra Material: File Types
 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
 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
 There are reasons to use both of these types of
files in various applications
258
Extra Material: IO Streams
• In Java, file access is provided through a
hierarchy of file and stream classes
These allow various different access
functionalities implemented in a systematic,
consistent way
Often we “wrap” streams around others to
provide more specific access
• Stream wrappers are a similar notion to our primitive
type wrappers – in both cases we are wrapping an
object around other data to increase the functionality
of the data
– However, in this case the data being “wrapped” is
already an object
259
Extra Material: IO Streams
• We have already seen a couple of these:
Scanner (input), PrintWriter (output)
• There are many other IO Streams that we
can use in our programs
The choice depends on the functionality that we
want to wrap around the underlying file
• Ex: For text files, PrintWriter is nice since it allows us
•
to write out strings
Ex: For binary files of primitive types,
DataOutputStream is good since it allows us to write
each of the primitive types
260
Extra Material: Text vs. Binary Files
• We discussed previously that numeric data
can often be stored more efficiently in binary
form than in text form
Let's compare the two by writing the same data
(numbers) to a text file and a binary file
Since the data is just numbers we can use a
DataOutputStream for our output
Allows only simple methods such as writeInt(),
writeDouble(), etc
261
Extra Material: Text vs. Binary Files
• Let’s try this and then compare the sizes of
the binary and text files
We will generate a number of random ints and
random doubles
Store each in a text file and in a binary file and
compare sizes at the end
• Note that the size of the integer text file depends
greatly on the values of the integers, while the size of
the integer binary file is independent of the values
– If we are storing very small integers, using a text file
will actually save us space, but for large integers it will
cost us space
• See ex26.java
262
Extra Material: Object Streams
• Java has the ability to write entire objects to
files in a serialized form
The class type as well as the instance variables
are written in a way that allows the object to be
restored easily upon reading
This is done utilizing the ObjectOutputStream
and ObjectInputStream classes
It will only work if the class implements the
Serializable interface
• Note that if the class uses composition, all data within
•
it must also implement Serializable
See ex27a.java, ex27b.java
263
Extra Material: Preview of Data Structures
• In Data Structures, we want to learn,
understand and be able to utilize many of
the data structures that are fundamental to
computer science
Data structures such as vectors, stacks, queues,
linked-lists and trees are used throughout
computer science
We should understand these from a user's point
of view:
• What are these data structures and how do I use
them in my programs?
264
Extra Material: Preview of Data Structures
• We also want to understand implementation
issues related to these data structures, and
to see how they can be implemented in the
Java programming language
Data structures can be implemented in various
ways, each of which has implications (ex: runtime differences, code complexity, modifiability)
We should understand these data structures
from an implementer's point of view:
• How can these data structures be effectively
implemented?
265
Extra Material: Preview of Data Structures
• We also want to understand and utilize
programming ideas and techniques utilized
in data structure implementation
Object-oriented programming, dynamic memory
utilization, recursion and other principles must
be understood in order to effectively implement
data structures
• What tools must I know and be able to use in order to
implement data structures?
266
Extra Material: Preview of Data Structures
• We also want to learn more of the Java
programming language and its features, and
to become more proficient at programming
with it
Java is a very large language with extensive
capabilities
As your programming skills improve, you can
utilize more of these capabilities effectively
• Since I am working with Java, how well can I learn
and use the language and its features?
267
Extra Material: Preview of Data Structures
• Example: Consider the idea of a List:
Ordered (by position), indexable collection of data
In Java this is an interface – with some methods
as shown:
• void add(int index, Object element)
– Add a new object at the specified index
• int indexOf(Object o)
– Find the object and return its index
• Object get(int index)
– Return the object at the specified index
• Object remove(int index)
– Remove (and return) the object at the specified index
268
Extra Material: Preview of Data Structures
• We can implement a List in different ways
ArrayList
• Use an array as the underlying data structure
• You are already familiar with this
LinkedList
• Use a linked list of nodes as the underlying data
structure
Head
– See singly linked list below
– Actual Java implementation is a doubly linked list
> More details in CS 0445!
269
Extra Material: Preview of Data Structures
Each implementation has advantages and
disadvantages
• Ex: Advantage of ArrayList
– get(i) can be done in one step, since we just go to that
index in the array
– In a LinkedList we must follow references down the list
• Ex: Advantage of LinkedList
– add(0, obj) requires only creating a new object and
linking it correctly to front of list
– In an ArrayList we must shift all of the items from 0
down a spot in order to make "room" at index 0
270
Extra Material: Preview of Data Structures
• Queue and Stack
Two fundamental data structures used through
computer programming
Queue:
• Data managed First In First Out (FIFO)
Stack
• Data managed Last In First Out (LIFO)
Manipulation in other ways is not (or should not
be) allowed
• Using data abstraction and encapsulation we can
implement these nicely
271
Extra Material: Preview of Data Structures
In CS 0445 you will see these and other
implementation ideas in detail
Ex: See ex28.java
• Note that the showList method works for all of the
•
objects, using the Collection interface
However, the underlying objects are different and give
different functionalities and efficiencies
– More in CS 0445!
272
Download