0% found this document useful (0 votes)
22 views298 pages

Cs 401

Uploaded by

sohailhamna50
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views298 pages

Cs 401

Uploaded by

sohailhamna50
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 298

Intermediate Programming

(with Java)
• These notes are intended for use by students in
CS0401 at the University of Pittsburgh and no one
else
• These notes are provided free of charge and may
not be sold in any shape or form
• Material from these notes is obtained from various
sources, including, but not limited to, the
following:
4 Starting Out with Java, From Control Structures through
Data Structures, Fourth Edition, by Gaddis and Muganda
4 Starting Out with Java, From Control Structures through
Objects, Third to Seventh Editions by Gaddis
4 Java Software Solutions, Fourth and Fifth Editions by
Lewis and Loftus
4 Java By Dissection by Pohl and McDowell
4 The Java Tutorial (click for link)
4 The Java home page and its many sub-links:
http://www.oracle.com/technetwork/java/index.html
2
Lecture 1: Prerequisites

• Students taking CS401 should


already have some programming
background:
4 Previous experience with Java (ex: CS
0007) is recommended, but Python, C,
C++ and VB are also acceptable
4 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
3
expressions
– Numbers, characters, operators, precedence
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
4 If you do not have this background, you
should consider taking CS 0007 before
taking CS0401
• Really!
• I am not kidding!
4
Lecture 1: Goals of the Course

• Goals for CS 0401 Course:


4 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 extended5 review!
Lecture 1: Goals of Course

4 To learn the principles of object-oriented


programming and to see Java from an
object-oriented 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

4 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

4 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) – possible coverage
• Introduction to recursion (Chapter 15)
• Introduction to linked lists (Chapter 19)
8
Lecture 1: Why Java?

• Java
4 Java is a (bytecode) interpreted, platform-
independent, object-oriented language
• Interpreted, platform-independent:
– Source .java code is compiled into intermediate
(byte) code
– Byte code is executed in software via another
program called an interpreter (JRE)
– Benefits:
> More safety features and run-time checks can be
built into the language – discuss
> Code can be platform-independent
> As long as the correct JRE is installed, the same
byte code can be executed on any platform

9
Lecture 1: Why Java?

JRE for Windows

Java Java
JRE for Linux
Source Byte
Code Java Compiler Code
(.java) (.class)

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 1: Why Java?
– Drawback:
> Interpreted code executes more slowly than
regular compiled code
> Since program is run in software rather than
hardware, it cannot match the execution times of
code that is compiled for specific hardware
> Ex: C, C++ code
> No language is best for every application
> However, Java implementations can use JIT
compilation of bytecode to execute faster
• Object-oriented
– Primary mode of execution is interaction of
objects with each other
– We will discuss object-oriented programming in
much more detail soon

11
Lecture 1: Getting Started with Java

• How do we execute Java programs?


4 First we must compile our source (.java)
code into the intermediate (.class) code
• We do this with the Java Compiler
• javac program
4 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 1: Getting Started with Java

4 Both programs come with the Java


Development Kit
• This is installed on all of the lab PCs and the Mac
Minis
• The most recent version (JDK 12) can be easily
downloaded and installed from the Oracle Web
site:
– http://www.oracle.com/technetwork/java/index.ht
ml

– It is free!
• More on the basics of using the Java software
development kit is shown in Lab 1
– See the Lab Info link on the CS 0401 site for
details
• But let’s look at an ex.
13
and talk more about Java
Lecture 1: Getting Started with Java

• 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 1: Getting Started with Java

4 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
15 if you wish
Lecture 2: Java Basics

• What fundamental entities / abilities do


we need for any useful Java program?
4 A way to get data into and out of our
program
• I/O
4 A way to create / name / variables and
constants to store our data
• Identifiers and variables
4 A way to manipulate / operate on the data
• Statements and Expressions
4 A way to make decisions and control our
flow of execution
• Control structures16
Lecture 2: Java Basics

• Output (we will defer input until after we discuss variables)


4 Java has a predefined object called
System.out
4 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

• We can output strings, values of variables and


expressions and other information using
System.out
– This will be very useful in all of our programs
• 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

• Lexical elements – groups of


characters used in program code
4 These form all of the parts of the program
code
• Ex: keywords, identifiers, literals, delimiters
4 We will discuss some of these in the Java
language
4 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
19 complete list
Lecture 2: Java Basics

4 Predefined Identifiers
• Identifiers that were written as part of some
class / package that are already integrated into
the language
– Ex: System, Applet, JFrame – class names
– Ex: println, start, close – method names
– Ex: E, PI – constant names
• Programmers can use these within the context
in which they are defined
• In Java there are a LOT because Java has a
large predefined class library

20
Lecture 2: Java Basics

4 Other Identifiers
• Defined by programmer
• used to represent names of variables, methods,
classes, etc
• Cannot be keywords
• We could redefine predefined identifiers if we
wanted to, but this is generally not a good idea
• Java IDs must begin with a letter, followed by
any number of letters, digits, _ (underscore) or
$ characters
– Similar to identifier rules in most programming
langs

21
Lecture 2: Java Basics

• Important Note:
– Java identifiers are case-sensitive – this means that
upper and lower case letters are considered to be
different – be careful to be consistent!
– Ex: ThisVariable and thisvariable are NOT the same
• Naming Convention:
– Many Java programmers use the following
conventions:
> Classes: start with upper case, then start each word
with an upper case letter
> Ex: StringBuffer, BufferedInputStream,
ArrayIndexOutOfBoundsException
> Methods and variables: start with lower case,
then start each word with an upper case letter
> Ex: compareTo, lastIndexOf, mousePressed

22
Lecture 2: Java Basics

4 Literals
• Values that are hard-coded into a program
– They are literally in the code!
• Different types have different rules for literal
values
– They are fairly intuitive and similar across most
programming languages
– Ex: Integer
> An optional +/- followed by a sequence of digits
> Ex: 234 -4566
– Ex: String
> A sequence of characters contained within double
quotes
> Ex: “Hello” “My name is Inigo Montoya”
• See Section 2.3 for more details on literals
23
Lecture 2: Java Basics

4 Putting all of this together, we get:


• Lexical elements are the building blocks of Java
programs
• Some useful lexical elements include:
– Keywords
> Restricted to their predefined use
– Predefined identifiers
> Predefined but could be redefined
– Programmer defined identifiers
> Made up by programmer for variable names, class
names, method names, etc
– Literals
> Values that are hard-coded into a program

24
Lecture 2: Java Basics

• Statements
• Units of declaration or execution
• A program execution can be broken down into
execution of the program’s individual
statements
• Every Java statement must be terminated by
a semicolon (;)
• Ex: Variable declaration statement
int var1, var2;
• Ex: Assignment statement
var1 = 100;
• Ex: Method call
System.out.println(“Answer is “ + var1);
• We will see many more statements later
25
Lecture 2: Java Basics

• Variables
• Memory locations that are associated with
identifiers
• Values can change throughout the execution of a
program
• In Java, must be specified as a certain type or
class
– The type of a variable specifies its properties: the
data it can store and the operations that can be
performed on it
> Ex: int type: discuss
– Java is fairly
incompatible strict about
types: String enforcing data typeto
cannot be converted values
int
int i = "hello";
> You will get a compilation error if you assign an
^
incorrect type to a variable: Ex: int i = “hello”;

26
Lecture 2: Java Basics
– Note: For numeric types, you even get an error if
the value assigned will “lose precision” if placed
into the variable
> Generally speaking this means we can place
“smaller” values into “larger” variables but we
cannot place “larger” values into “smaller”
variables
> Ex: byte < int < long < float < double
– Ex: int i = 3.5;
incompatible types: possible lossy conversion from double to int
int i = 3.5;
^

– Ex: double x = 100;


> This is ok

27
Lecture 2: Java Basics
– Floating point literals in Java are by default
double
> If you assign one to a float variable, you will get a
“loss of precision error” as shown in the previous
slide
– If you want to assign a “more precise” value to a
“less precise” variable, you must explicitly cast
the value toint
that ivariable
= 5; type
int j = 4.5;
float x = 3.5;
float y = (float) 3.5;
Error check each of the
double z = 100;
statements in the box to
i = z;
the right
y = z;
z = i;
j = (long) y;
j = (byte) y;
28
Lecture 3: Data and Expressions

4 In Java, variables fall into two categories:


4 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

29
Lecture 3: Data and Expressions

4 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

30
Lecture 3: Data and Expressions

4 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
error: cannot find symbol
x = 5.0;
^
symbol : variable x
location: class classname

• 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
31
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

32
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 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?
33
Lecture 3: Data and Expressions

4 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
34
Lecture 3: More Operators

• Java has a number of convenience


operators
4 Allow us to do operations with less typing
4 Ex:
X = X + 1; X++;
Y = Y – 5; Y –= 5;
4 See Section 2.6 for more details
4 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
35
– See ex3.java
Lecture 3: Input and the Scanner Class

• Input
4 Java has a predefined object called
System.in
• Analogous to System.out discussed previously
• Allows data to be input from the standard input
stream
– Recall that System.out accessed the standard
output stream
4 By default this object allows us to read
data from the console / keyboard

36
Lecture 3: Input and the Scanner Class

4 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
4 The tokens can be read in either as Strings
• next()
4 Or they can be read as primitive types
• Ex: nextInt(), nextFloat(), nextDouble()
37
Lecture 3: Input and the Scanner Class

4 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(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at ex4.main(ex4.java:48)
• 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
4 Let's look at ex4.java
38
Lecture 4: Control Statements

• Java Statements
4 We already discussed some Java
statements
• Declaration statement
• Assignment statement
• Method call
4 One of the most important types of
statements in programming is the control
statement
• Allows 2 very important types of execution
– Conditional execution
> Statements may or may not execute
– Iterative execution
> Statements may 39
execute more than one time
Lecture 4: Control Statements

Linear Execution Conditional Execution Iterative Execution

40
Lecture 4: Boolean Expressions

• Key to many control statements in Java


are boolean expressions
4 Expressions whose result is true or false
• true and false are predefined literals in Java
4 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
41
because 7 IS NOT not equal to
7
Lecture 4: Boolean Expressions
• Java has 6 relational
operators
< <= > >= == !
= A&&
4 Some boolean A B !A B
A||B

expressions are
more complicated true true false true true
than just a simple
relational operation true false false false true
• These expressions
require logical false true true false true
operators
– Operate on false false true false false
boolean values,
generating a new
boolean value as a
result
! && ||
– Recall their values
from a truth table
42
Lecture 4: Boolean Expressions

• 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 5: if statement

• The if statement is very intuitive:


if (booleanexpression)
<true option>;
else
<false option>;
4 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
4 else + <false option> is optional
4 Note parens around booleanexpression -
required
44
Lecture 5: if statement

• Nested ifs
4 Since both <true option> and <false
option> can be any Java statement, they
can certainly be if statements
4 This allows us to create nested if
statements
• We can nest on <true option>, on <false
option> or both
– Show on board
• Enables us to test multiple conditions and to
have a different result for each possibility

45
Lecture 5: if statement

4 Dangling else
• The structure of a Java if statement allows for
an interesting special case:
if (grade >= 95) // condition1
if (extraCredit) // condition2
System.out.println(“A+”);
else
System.out.println(“?”);
• Question: is the <false option> for condition1
or condition2?
– As shown above it will ALWAYS be for condition2
– Rule is that an else will always be associated
with the “closest” unassociated, non-
terminated if

46
Lecture 5: if statement

• 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: COMPILATION 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>;
4 where <loop body> can be any Java
statement
4 Logic of while loop:
• Evaluate (booleanexpression)
• If result is true, execute <loop body>, otherwise
skip to next statement after loop
• Repeat
4 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:
4 User will enter some scores and the
program will calculate the average
4 Let’s do this together, trying to come up
with a good solution
4 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?
4 Once we have a solution, 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


4 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 }
4 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
4 These expressions make the for loop
52
extremely flexible
Lecture 6: for loop

4 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
4 In effect we can use a for loop as if it were
a while loop if we’d like
4 However, it is more readable and less
prone to logic errors if you use it as a
counting loop
4 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

4 Since Java 1.5+, there is an additional


version of the for loop:
for (type var : iterator_obj)
<loop body>;
4 This version is called the "foreach" loop
• In a lot of scripting languages such as Perl and
PHP, so it was adopted into Java
4 However, to use it we need to understand
something about objects and iterators
4 This version is really cool!
4 We will come back and talk about this
later
54
Lecture 6: switch statement

• We know that if can be used in a


multiple alternative form
4 If we nest statements

• Sometimes choices are simple, integral


values
4 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 6: switch statement

switch (int_expr)
{
case constant_expr:

case constant_expr:

default: // this is optional
}
4 int_expr is initially evaluated
4 constant_expr are tested against int_expr
from top to bottom
• First one to match determines where execution
within the switch body BEGINS
– However, execution will proceed from there to
the END of the block
56
Lecture 6: switch statement

• 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


4 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
4 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
4 Most of these problems can be solved by
breaking our program into smaller
segments 59
Lecture 7: Methods and Method Calls

• Method (or function or subprogram)


4 A segment of code that is logically
separate from the rest of the program
4 When invoked (i.e. called) control jumps
from main to the method and it executes
• Usually with parameters (arguments)
4 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
4 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
61 to easily use methods
that they didn’t write
Lecture 7: Return Value vs. Void

• Java methods have two primary uses:


4 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;
4 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 62
Lecture 7: Predefined Methods

• There are MANY predefined methods in


Java
4 Look in the online API
4 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 63
Lecture 7: Predefined Methods

4 Some are also called in the following way


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
4 These are instance methods – associated
with an object – we will discuss these
shortly
• For now we will concentrate
64
on static methods
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

4 Really simple example:


public static void sayWacky()
{
System.out.println(“Wacky”);
}
4 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

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

4 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
4 Parameters in Java are passed by value
• The parameter is a copy of the evaluation of
the argument
• Any changes to the parameter do not affect the
argument answer calculated
method completed answer returned

Main Class area method


value passed from
rad arg. to parameter radius 2.0
2.0
result returned to ans 12.566…
theArea 12.566…
main
double ans =
Math.PI * radius
double theArea * radius;
main calls area
= area(rad); return ans;
method
69
Lecture 7: More on Parameters

• Effect of value parameters:


4 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
object-oriented programming
70
Lecture 7: Local variables and scope

• Variables declared within a method are


local to that method
• We typically call these method variables
4 They exist only within the context of the
method
4 This includes parameters as well
• Think of a parameter as a local variable that is
initialized in the method call
4 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 7: Local variables and scope

• However, Java variables can also be


declared within blocks inside of
methods
4 In this case the scope is the point of the
declaration until the end of that block
• Show on board
4 Be careful that you declare your variables
in the correct block
• See Java Debug Help slides for more details
– debug.ppt

72
Lecture 7: Local variables and scope

• Note that either way, local variables


cannot be shared across methods
4 In other words, a local variable declared in
one method cannot be accessed in a
different method
• Even if they have the same name, they are still
different variables
4 We can still get data from one method to
another
• How?
4 To share variables across methods, we need
to use object-oriented programming
• We will see this soon! 73
• See ex7.java
Lecture 8: References and Reference Types

• Recall from Slides 29-30 that Java has


primitive types and reference types
4 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

4 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 Porsche 911
75 Turbo S Cabriolet
Lecture 8: Classes and Objects

• What do we mean by "objects"?


4 Let's first discuss classes

• Classes are blueprints for our data


4 The class structure provides a good way to
encapsulate the data and operations of a
new type together
• Instance data and instance methods
– This is a fundamental feature of OOP which we
will discuss more soon
• 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
4 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
4 We call this data abstraction
• Compare to functional abstraction discussed
previously
4 Java classes determine the structure and
behavior of Java objects
4 To put it another way, Java objects are
instances of Java classes
• They are encapsulations
77 of data and methods
Lecture 8: Classes and Objects
Class Foo
class Foo definition
{
int x;
void f(); 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
4 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 references79an instance of a StringBuilder
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
4 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

4 Properties of objects (public methods and


public instance variables) are accessed via
"dot" notation
S1.append(" Friends!");
• The process of accessing an object in this way is
called dereferencing the object
– S1 is a reference (address)
– S1.<whatever> means:
> Go to the object whose address is stored in S1
S1 > Access / call the specified variable or method
Hello Friends!
S2

– Note: In this case S2 will also access the appended


object 81
Lecture 8: More References

4 Comparison of reference variables


compares the references, NOT the objects
StringBuilder S3 =
new StringBuilder("Hello Friends!");
if (S1 == S2) System.out.println("Equal"); // yes
if (S1 == S3) System.out.println("Equal"); // no
• Recall that S1, S2 and S3 are all variables
storing addresses
– The == simply compares those address values
– i.e. Are they looking at the same location?
• What if we want to compare the objects?
– Do the objects (where ever they are) have the
same data stored within them?

82
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
83
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)

4 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!");
84
Lecture 8: More references

• Why?
– The method calls are associated with the OBJECT
that is being accessed, NOT with the variable
– If there is no object, there are no methods
available to call
– Result is NullPointerException – common
error so remember it!
4 Let's take a look at ex8.java
4 Side note: speaking of common errors
• Take another look at debug.ppt – it has some of
the things we just mentioned

85
Lecture 9: Intro. to Object-Oriented Programming (OOP)

• Object-Oriented Programming consists


of 3 primary ideas:
4 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
86
Lecture 9: Intro. to OOP

4 Inheritance
• Properties of a data type can be passed down
to a sub-type – we can build new types from old
ones
• We can build class hierarchies with many levels
of inheritance
• We will discuss this more in Chapter 11
4 Polymorphism
• Operations used with a variable are based on
the class of the object being accessed, not the
class of the variable
• Parent type and sub-type objects can be
accessed in a consistent way
• We will discuss this more in Chapter 11
87
Lecture 9: Encapsulation and Data Abstraction

• Consider primitive types


4 Each variable represents a single, simple
data value
4 Any operations that we perform on the
data are external to that data
X+Y

X 10
+
Y 5

88
Lecture 9: Encapsulation and Data Abstraction

• Consider the data


4 In many applications, data is more
complicated than just a simple value
4 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) 89
Lecture 9: Encapsulation and Data Abstraction

• Consider the operations


4 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 Polygon90 by deltaX and deltaY
Lecture 9: Encapsulation and Data Abstraction

4 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
91
Lecture 9: Encapsulation and Data Abstraction

4 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]
Thus, the
npoints 4
operations are
always implicitly addPoint()
acting on the contains()
object’s data translate()
Ex: translate
means translate
the points that
make up P 92
Lecture 9: Encapsulation and Data Abstraction

4 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 P2

xpoints [0,4,4,0] xpoints [8,11,8]]


ypoints [0,0,2,2] ypoints [0,2,4]
npoints 4 npoints 3

addPoint() addPoint()
contains() contains()
translate() translate()
93
Lecture 9: Encapsulation and Data Abstraction

• Recall that we previously discussed


data abstraction
4 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
4 This concept is exemplified through
objects
• We can think of an object as a container with
data and operations inside (i.e. encapsulating
them)
– We can see some of the data and some of the
operations, but others
94 are kept hidden from us

Lecture 9: Encapsulation and Data Abstraction

• As long as we know the


method names, params P
and how to use them,
we don’t need to know
xpoints [0,4,4,0]
how the actual data is ypoints [0,0,2,2]
stored npoints 4

4 Note that I can use a addPoint()


contains()
Polygon without knowing translate()
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! 95
Lecture 9: Instance Variables

• Let us look again at StringBuilder


4 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!!!
96
Lecture 9: Instance Variables

4 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
– See ex8.java
97
Lecture 9: Encapsulation, Data Abstraction and Instance Variables

4 Consider again the ideas of encapsulation


and data abstraction
• Encapsulation allows the instance variables to
be separated / hidden from the user of a class
– private declarations and (we will see later)
protected declarations are not directly
accessible by the user of a class
• Data abstraction enables a user to not require
direct knowledge of these variables in order to
use a class

98
Lecture 9: Class Methods vs. Instance Methods

4 Recall that methods we discussed before


were called class methods (or static
methods)
• These were not associated with any object
4 Now, however in this case we WILL
associate methods with objects (as shown
with Polygon)
4 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());
99
Lecture 9: Class Methods vs. Instance Methods

4 Class methods have no implicit data to


act on
• All data must be passed into them using
arguments
• Class methods are called using:
ClassName.methodName(param list)
4 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
– This is because they are encapsulated within
that same object
• Instance methods are called using:
VariableName.methodName(param list)
100
• Where VariableName is a reference to an object
Lecture 9: Encapsulation / Abstraction Summary

• In summary:
4 Objects allow us to encapsulate data and
operations together into a single entity
• Instance variables define the data within the
object
• Instance methods define the operations to be
used by the object
4 The instance variables and methods are
specified in the class definition
• Which variables / methods can be "seen" by a
user of the object can be restricted by private
declarations
4 Objects are instances of class which
contain the specified
101 data and methods
Lecture 9: Encapsulation / Abstraction Summary

4 Because of data abstraction


• To use objects in our program we need to
know:
– The general idea of the data to be stored
– What the instance methods are (i.e. names)
– What they are supposed to do (i.e. general
function)
– What parameters they need
• We don't need to know
– The specific instance variables (names or types)
– The instance method implementations
4 Encapsulation and data abstraction are
closely related
• Encapsulating the data and methods in an
object enables programmer
102 to restrict access
Lecture 10: Constructors, Accessors and Mutators

• Instance methods can be categorized


by what they are designed to do:
4 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

103
Lecture 10: Constructors, Accessors and Mutators

4 Accessors
– Also called getters
• These methods are used to access the object in
some way without changing it
• Usually used to get information from it
• No special syntax – categorized simply by their
effect
StringBuilder B = new StringBuilder(“hello there”);
char c = B.charAt(4); // c == ‘o’
String S = B.substring(3, 9); // S == “lo the”
// note that end index is NOT
inclusive
int n = B.length(); // n == 11
– These methods give us information about the
StringBuilder without revealing the implementation
details 104
Lecture 10: Constructors, Accessors and Mutators

4 Mutators
– Also called setters
• Used to change the object in some way
• Since the instance variables are usually private,
we use mutators to change the object in a
specified way without needing to know the
instance variables
B.setCharAt(0, ‘j’); // B == “jello there”
B.delete(6,7); // B == “jello here”
B.insert(6, “is “); // B == “jello is here”;
– These methods change the contents or
properties of the StringBuilder object
4 We use accessors and mutators to
indirectly access the data, since we don’t
have direct access 105
– see ex9.java
Lecture 10: Simple Class Example

• We can use these ideas to write our


own classes
4 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!!!)
106
Lecture 10: More on Classes and Objects

• Classes
4 Define the nature and properties of
objects
• Objects
4 Instances of classes

• Let’s learn more about these by


developing another example together
• Goal:
4 Write a class that represents a playlist
(group of songs)
4 Write a simple driver program to test it
107
Lecture 10: Developing Another Example

• Remember the things we need for a


class:
4 Instance variables
• Fill in ideas from board
4 Constructors
• Fill in ideas from board
4 Accessors
• Fill in ideas from board
4 Mutators
• Fill in ideas from board

108
Lecture 11: Developing Another Example

4 Once we have the basic structure of the


class we can start writing / testing it
4 A good approach is to do it in a modular,
step-by-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

109
Lecture 11: Testing Your Classes

4 There are formal approaches to doing this:


• Unit testing
– A framework / program is developed to test the
required functionalities of the class (or “unit”) in a
formalized way
– Test to make sure the class behaves the way it is
supposed to behave
– See: https://en.wikipedia.org/wiki/Unit_testing
• Java assertions
– Conditions that should always be true
> Ex: currCount <= maxCount
– If an assertion becomes false, an AssertionError is
thrown
– See:
https://docs.oracle.com/javase/7/docs/technotes/guid
es/language/assert.html
110
Lecture 11: Intro. to Java Files

• So far
4 Our programs have read input from the
keyboard and written output to the
monitor
• This works fine in some situations, but
is not so good in others:
4 What if we have a large amount of output
that we need to save?
4 What if we need to initialize a database
that is used in our program?
4 What if output from one program must be
input to another?
111
Lecture 11: Java Text Files

• In these situations we need to use


files
4 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
112
interpreted in a different way
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

113
Lecture 11: Java Text Files

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

114
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

115
Lecture 12: Arrays

• So far (for the most part) we have


stored data in a 1:1 fashion
4 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:
4 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
116
Lecture 12: Arrays

4 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
4 However, what about listing them in
sorted order?

117
Lecture 12: Arrays

4 We can’t know the final order until all


scores have been read
• Last value could be smallest, largest or
anywhere in between
4 Thus, we need to store all of the values as
they are being read in, THEN sort them
and print them out
4 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

118
Lecture 12: Java Arrays

• Java Arrays
4 In Java, arrays are objects, with certain
properties
• Like other reference types
4 Simply put, an array is logically a
single variable name that allows
access to multiple variable locations
4 In Java, the locations also must be
contiguous and homogeneous
• Each directly follows the previous in memory
• All references in the array are of the same type

119
Lecture 12: Java Arrays

• Syntax:
4 First, consider only PRIMITIVE TYPE data
4 We create a Java array in 2 steps:
prim_type [] var_name;
• where prim_type is any primitive type
• where var_name is any legal identifier
• This creates array variable, but NOT an actual
array
var_name = new prim_type[arr_size]
• where arr_size is the number of elements that
will be in the array
• Indexing in Java always starts at 0
• This creates the array object
120
Lecture 12: Java Arrays

4 Ex:
int [] myArray;
myArray = new int[20]; // size can be a variable
// or expression
4 These two steps can be done as one if
we’d like
int [] myArray = new int[20];
4 Once we have created the array, we now
need to put values into it
• Numeric types are initialized to 0
• Booleans are initialized to false
– This is because the locations within an array are
considered as instance variables within the array
object
121
• We can change these values via indexing
Lecture 12: Java Arrays

• Indexing an array
4 An array variable gives us access to the
“beginning” of the array
4 To access an individual location in the
array, we need to index, using the []
operator
4 Ex:
myArray[5] = 250;
myArray[10] = 2 * myArray[5];
myArray[11] = myArray[10] – 1;
• Show on board
• Discuss
122
Lecture 12: Java Arrays

• Iterating through an array


4 We can easily iterate through an entire
array using a loop (often a for loop)
4 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);
}
123
Lecture 12: Direct Access and Sequential Access

• The previous two slides demonstrate


the two basic ways of accessing
arrays:
4 Direct Access
• Arbitrary items are accessed by providing the
appropriate index of the item
4 Sequential Access
• Items are accessed in index order from
beginning to end (or from end to beginning)
4 The usefulness of arrays comes from
allowing access in both of these ways
4 Let’s see both direct and sequential
access of arrays with
124 a file example
Lecture 12: References and Reference Types

• Recall from previous discussions that


Java has primitive types and reference
types
4 Also recall (once again!) how they are
stored
• With var1
primitive100
types, data values are stored
directly in the memory location associated with
a variable

s
Hello
• With reference types, values are There
references to
objects that are stored elsewhere in memory

125
Lecture 12: Arrays as Reference Types

• Java arrays are reference types


4 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
4 But I can alter the contents of the array through
indexing
4 Ex:
int [] A = new int[5]; A
for (int i = 0; i < 5; i++) 0 0
A[i] = 2*i; 0 0 1 0
B 3
int [] B = A; 1 2 2 0
A[3] = 5;
2 4 3 0 7
A = new int[4];
A[1] = 3; 3 6 5
A[3] = 7; 4 8

126
Lecture 12: Arrays as Parameters

• Recall that all Java parameters are


value
4 A copy of the argument is passed to the
param
4 Changes to the parameter do not affect
the argument
• What about arrays?
4 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 127
Lecture 12: Arrays as Parameters

• This is the same issue we discussed previously


with reference types (see showInfo() in
ex9.java)
• In the case of arrays, mutating includes
changing the value of a location (since locs are
instance vars)
4 See ex11.java
4 Sounds confusing, right?
• Not so much once you picture it!
• Show example on board
4 This allows us to change arrays within
methods
• Ex: Read data into an array
• Ex: Remove data from128 an array
Lecture 13: Searching an Array

• Often we may want to see if a value is


stored in an array or not:
4 “Is this book in the library?”
4 “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

129
Lecture 13: Sequential Search

• Sequential Search
4 Start at the beginning of the array and
check each item in sequence until the end
of the array is reached or the item is found
• Note that we have two conditions here
– One stops the loop with failure (get to end)
– The other stops the loop with success (found
item)
• We should always consider all possible
outcomes when developing algorithms
4 Q: What kind of loop is best for this?
• Think about what needs to be done
4 Let’s look at an example: ex12a.java
130
Lecture 13: Arrays of Objects

• 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?
4 The first two steps are the same
• Declare variable
• Create array object

131
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; // declare array var
names = new String[5]; // make array object
names[1] = new String(“Herb”); // make String
names[3] = new String(“Madge”);
names[4] = new String(“Mort”);
– names[0] and names[2] are still null
– Show on board
132
Lecture 13: Arrays of Objects

• Note that we have two levels of references here

0
names
1 Herb
2
3 Madge
4 Mort

• See PlayListTest.java for another example

133
Lecture 13: Instance Data and Composition

• When we create a new class we can have


arbitrary instance variables within it
4 Recall that 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”
134 components can do
Lecture 13: Instance Data and Composition

4 As a simple example, consider the


Dictionary class from Assignment 2
• Dictionary contains instance variables:
– ArrayList<String> words
– Scanner dictFile
– Random R
• Thus the Dictionary class is composed of
ArrayList<String>, Scanner and Random
• From within Dictionary:
– We know all of the implementation details of
Dictionary
– But we are a client of the classes that compose
it, having access to only the public methods in
the classes
135
Lecture 13: Instance Data and Composition

• From outside Dictionary:


– User may not know any of these variables even
exist
– They are abstracted out of the user’s view
4 This idea can be applied indefinitely
• Once a class is written, it can be used as
instance data within another class
• This is the cool thing about object-oriented
programming!
– We can use this approach to build arbitrarily
complex objects.

136
Lecture 13: Arrays as Instance Data

4 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
4 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
137
Lecture 14: Exam One

• Exam One
4 All material from Lecture 1 to Lecture 13,
inclusive
4 See review sheet and practice questions
on Online Materials link of web site

138
Lecture 15: Resizing an array

• Java array objects can be of any size


4 However once created, they cannot be
resized
4 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];
4 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
139 time
Lecture 15: Resizing an array

4 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!
140
Lecture 15: Physical vs. Logical Array Size

4 What if we don’t have enough data to fill all


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
– We call the array size the physical size of the array
– We call the number of elements being stored the
logical size of the array
• This is what is done in141
the predefined ArrayList class
Lecture 15: ArrayLists

• Programmers can use arrays in arbitrary


ways
4 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
4 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
4 ArrayList 142
Lecture 15: ArrayLists

4 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
> Ex: When and how is it resized?
• We simply need to look up its functionality in the
Java API
4 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
4 Look at a simple example:
143
ArrayL.java
Lecture 15: ArrayLists

4 Idea:
• Data is maintained in two parts:
– an array to actually store the information
– an int to keep track of the number of elements
being stored
• Most of our operations are concerned with the
logical size of the array
– Number of actual elements being stored
• The physical size of the array is abstracted out
of our view
– This changes as necessary but we never need to
know what it actually is in order to use the
ArrayList
– Remember previous discussion on resizing

144
Lecture 15: Array Based Data Structures

4 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

145
Lecture 15: 2-D Arrays

• Two-D arrays in Java are actually arrays


of arrays
int [][] A = new int[4][8];
4 The first index gives us a "row", which is
an array of items
• We say this is "row major order"
4 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
146
Lecture 16: Simple Sorting

• What does it mean to sort our data?


4 Consider an array, A of N items:
A[0], A[1], A[2], …, A[N-1]
4 A is sorted in ascending order if
A[i] < A[j] for all i < j
4 A is sorted in descending order if
A[i] > A[j] for all i < j
4 Q: What if we want non-decreasing or non-
increasing order?
• What does it mean and how do we change the
definitions?

147
Lecture 16: Simple Sorting

• How do we sort?
4 There are MANY ways of sorting data
• Sorting has been widely studied in computer
science
4 Some algorithms are better than others
• The most useful measure of “better” here is
how long it takes to run
• The better algorithms run a lot more quickly
than the poorer algorithms
4 However, some very simple algorithms are
ok if N is not too large
• We will look at a simple algorithm here
– In CS 0445 you will see other, better ways of
sorting 148
Lecture 16: SelectionSort

• SelectionSort is very intuitive:


4 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
0 about
1 index
2 N-1? 4
3 5 6 7
4 Let’s trace it on the board for the following
35 50 20 40 75 10 15 60
data:
149
Lecture 16: SelectionSort

4 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?

150
Lecture 16: Sorting
– We could write a version of SelectionSort (or
InsertionSort) for each
– Lots of typing, where everything other than the
types involved is the same for each one
> This is a key issue – the only difference in the
sorts of different types is the data values and how
they are compared
> The sorting algorithm is the same
– Is there a way we can do this without having to
write the method so many times?
– Yes!
> Java Generics
> We will discuss this later after we discuss
polymorphism and interfaces

151
Lecture 16: Binary Search

• Consider Sequential Search again


– See previous slides and ex12a.java
4 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
4 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?
4 Consider example: Guess number from 1-
1000 152
Lecture 16: Binary Search

• Idea of Binary Search:


4 Searching for a given key, K
4 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
–0Show 1on board
2 for3a search
4 for5 40 6 7
10 15 20 35 40 50 60 75

153
Lecture 16: Binary Search

• What if item is not in array? We need a stopping


condition in the “not found” case
4 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
4 How to code this? Not difficult!
• We can do it with a simple while loop
• See author's code: BinarySearchDemo.java

154
Lecture 16: Binary Search

• Notes:
4 As with the version of SelectionSort we
saw previously, this version of Binary
Search only works for arrays of ints
• If we want to generalize it we need to write it in
a slightly different way, using Java generics
• We will look at this later once we have
discussed inheritance and interfaces

155
Lecture 16: Binary Search

4 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

156
Lecture 17: Contiguous Memory Data Structures

• The Java array and ArrayList use


contiguous memory
4 Locations are located next to each other in
memory
• Given the address of the first location, we can
find all of the others based on an offset from the
first
0 1 … i i+1 …

4 Benefits of contiguous memory:


• We have direct access to individual items
– Access of item A[i] can be done in a single
operation
157
Lecture 17: Contiguous Memory

• Direct access allows us to use efficient


algorithms such as Binary Search to find an item
• Arrays and array-based DS are also fairly simple
and easy to use

4 Drawbacks of contiguous memory


1) Allocation of the memory must be done at
once, in a large block as we just discussed
– If we allocate too much memory we are being
wasteful
– If we "run out of memory" we must resize by
making a new, larger array and copying the data
into it
> This process may be transparent (ex: in an
ArrayList) but it is not free due to the copying of
data 158
Lecture 17: Contiguous Memory

2) Inserting or deleting data "at the middle" of


an array may require shifting of the other
elements
– Also requires some time to do
– We must make room for a new item or fill in the
gap created after deleting an item
> This is necessary because the data is contiguous
• See SimpleAList.java
– This is simplified version of the standard
ArrayList
> It is defined for only one underlying type (String)
> It has only a few operations
• We will discuss the details of "how much" time
is required for resizing and for shifting in CS
0445
– This deals with algorithm
159 analysis
Lecture 17: Linked Data Structures

• Let's concentrate on the drawbacks


of contiguous memory
4 Is there an alternative way of storing a
collection of data that avoids these
problems?
4 What if we can allocate our memory in
small, separate pieces, one for each
item in the collection
• Now we allocate exactly as many pieces as
we need
• Now we do not have to shift items, since all
of the items are separate anyway
– Draw on board
160
Lecture 17: Linked Data Structures

4 But how do we keep track of all of the


pieces?
• We let the pieces keep track of each other!
• Let each piece have 2 parts to it
– One part for the data it is storing
front
– One part to store the location of the next piece
> This is the idea behind a linked-list

data
data

data data
161
Lecture 17: Linked Data Structures

• Idea of Linked List:


4 If we know where the beginning of the
list is
4 And each link knows where the next one
is
4 Then we can access all of the items in
the list
• Our problems with contiguous
memory now go away
4 Allocation can be done one link at a
time, for as many links as we need
4 New links can be "linked up" anywhere
162
in the list, without shifting needed
Lecture 17: Linked Lists

• How can we implement linked lists?


4 The key is how each link is implemented
4 As we said, two parts are needed, one for
data and one to store the location of the
next link
• We can do this with a self-referential data type
class Node
{
private T data;
private Node next;

– Where T is some legal Java data type
• A Node is a common name for a link in a
linked-list 163
Lecture 17: Node As an Inner Class

4 The Node class is an implementation-


specific data type
• Its whole existence is to facilitate the
implementation of the linked list
• The user of the linked list does not even need to
know what a Node is or what it does
• Thus we will make it a private inner class in
our linked list class
– Declared within the linked list (textually)
– This makes Node accessible within our linked list
> We can access the next and data fields directly
within our linked list
– But Node is not even visible outside our linked list
> Users of the linked list do not even know it exists
and cannot even access it
> But they don’t need to due to data abstraction

164
Lecture 17: Node As an Inner Class

4 For example:
public class SimpleLList
{
private class Node
{
private T data;
private Node next;

}
private Node front; // front of list
// SimpleLList methods go here
// These methods can access Node and its
// data but outside of SimpleLList Node
// cannot be accessed
165
Lecture 17: Linked List Operations

4 So what will we do with our linked list?


4 The operations can be arbitrary, but for
now we will focus on the same operations
we looked at for the SimpleAList
• The idea is that the SimpleAList and SimpleLList
will have the same functionality
• However
– The SimpleAList will be implemented using an
underlying array
– The SimpleLList will be implemented using an
underlying linked list
– Later we will see how to further abstract out the
implementation details

166
Lecture 17: Linked List Operations

• Adding a new value into a linked list


4 Idea:
• Determine where to put the new value
• Create a new Node for the value
• Link the Node correctly into the list
• Be careful for special cases
– Linked data structures typically have special
cases that must be handled
4 Where to put new value?
• We have two options in our SimpleAList
– Add new value at end
– Add new value at location i (anywhere in the list)

167
Linked List Operations

4 Two important things to remember for all


linked list operations:
1) Linked lists are inherently sequential
data structures
• There is no direct access
• To get to Node k, we must traverse through
Nodes 0..k-1
2) We must keep the Nodes linked correctly
• Adding a Node at position k requires us to
– Get to location k-1
– Connect the new Node to the previous Node at
position k
– Connect Node k-1 to the new Node

168
Linked List Operations

• Deleting a Node at position k requires us to


– Get to location k-1
– Connect the Node at position k-1 to the Node at
position k+1
– Previous Node k will now still exist but as
garbage since it is disconnected from the list
• Note the special case for adding or deleting the
first Node in the list
– There is no Node k-1 in this case
– The front instance variable must be changed
front
Node k-1 Node k+1

169
Linked List Operations

4 Let’s look at SimpleLList.java


• Carefully look at the code and read the
comments
• Note how the add() and remove() methods
follow the ideas mentioned
• Note that the next field of the last Node is null
– We call this a null-terminated linked list
– We can test for this value to know that we are at
the end of the list
• Note the special cases (at front)
• Let’s trace a couple of operations to see how
they work
4 See also Lab 8 for a linked list exercise

170
Lecture 18: Additional OO Notes

4 static variables
• Variables that are associated with the class itself
rather than individual objects
• Can be accessed through the class using
– ClassName.variableName
• or through the objects using
– variableName from within an object
– objectName.variableName from outside an object
• Show logic of this on the board
• To access from class or from outside of an object,
the data must be public
• Used when variables are shared amongst all
objects
– See StaticDemo.java
171
Lecture 18: Additional OO Notes

4 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
4 Look again PlayList.java and
PlayListTest.java
172
Lecture 18: Misc OO Notes

4 Copying objects
• Sometimes, for various reasons, we need to
make a copy of an object
• In Java there are two primary ways of doing
this:
– Using a “copy constructor” for the class
> This method takes an argument of the same class
type and makes a copy of the object
> Ex: String newString = new String(oldString);
– Using the “clone” method for a class
> This allows an object to “make a copy of itself”
> It is a bit more complicated to use
> We will defer it to CS 0445

173
Lecture 18: Misc OO Notes

4 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 174
> See ex12b.java and Scores.java
Lecture 18: 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
– Consider the SimpleLList class that we just
discussed
> Shallow copy will simply copy the front and size
variables
> The entire list of Nodes is shared by both
copies
> Deeper copy will make an entirely new set of
Nodes and copy the data into the new Nodes
> Note: Copying the data in the Nodes does not
guarantee a deep copy – it depends on the
data!
• Neither shallow nor deep is nec. correct nor
incorrect 175
Lecture 19: Misc OO Notes

4 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 176
Lecture 19: Misc OO Notes

4 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
> Otherwise we may have to use a mutator (or
perhaps more than one)

177
Lecture 19: Misc OO Notes

• However, keep in mind that returning references


to the “originals” is more dangerous than
returning copies
– If we accidentally (or intentionally) modify the
object via the returned reference, that will impact
the orig. encompassing object
– It may even invalidate / destroy the data in that
collection
• Ex: Consider the PlayList class
– There is a method (commented) getSongs() that
will return the list (array) of Songs in the PlayList
> This method could return a reference to the Songs in
the PlayList (original, unsafe version)
> This method could make a new copy of the array of
Songs and return that (commented, safer version)
> Note that even this method is not totally safe if
Songs are mutable
178
> See SafeReturn.java
Lecture 19: Misc OO Notes

4 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 self-
reference to an object
– It allows disambiguation between instance
variables and method variables
• See example on board

179
Lecture 19: Misc OO Notes

4 Garbage Collection
• When a reference to an object is reassigned,
the original object can no longer be accessed
through that reference
• If there is no other reference to that object,
then it cannot be accessed, period
• In this case the object has become garbage
– An object sitting in memory that can no longer
be an active part of the program
• If a program produces a lot of garbage it can
consume a lot of memory

180
Lecture 19: Misc OO Notes

• 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

181
Independent Work: Wrappers

• Much useful Java functionality relies on


classes / objects
4 Inheritance (Chapter 10)
4 Polymorphic access (Chapter 10)
4 Interfaces (Chapter 10)

• Unfortunately, the Java primitive types


are NOT classes, and thus cannot be
used in this way
4 If I make an array of Object or any other
class, primitive types cannot be stored in
it
182
Independent Work: Wrappers

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

183
Independent Work: Wrappers

4 The wrapper classes


also provide extra
useful functionality for Integer
these types int
• Ex: Integer.parseInt() is
a static method that
enables us to convert
from a String into an int Double
• Ex: Character.isLetter() double
is a static method that
tests if a letter is a
character or not
4 See more in API

184
Independent Work: Wrappers and Casting

4 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

185
Independent Work: Wrappers

4 In Java 1.4 and before:


• Programmer had to do the conversions explicitly
– Painful!
4 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
4 We will see more on how wrappers are
useful after we discuss inheritance,
polymorphism and interfaces
186
Independent Work: Parsing Primitive Types

4 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 now187see the actual algorithm
Independent Work: 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
• See MyInteger.java and Wrappers.java

188
Independent Work: Character class

• The Character wrapper class provides


many useful methods:
4 Ex:
• Case conversion, checking for letters, checking
for digits
4 Can be useful when we are parsing text
files ourselves
• The String class has some very useful
methods as well
4 See text for a lot of them (ex: split())
4 See Stringy.java

189
Lecture 19: Inheritance

• Sometimes we want to build a new


class that is largely like one we already
have
4 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
4 Attributes of a base class, or superclass
are passed on to a subclass

190
Lecture 19: Inheritance and “is a”

4 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
4 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
4 Ex: ArrayList “is a” AbstractList
191
Lecture 19: Inheritance and “is a”

AbstractList

is a is a
is a

AbstractSequentialList ArrayList Vector

is a • AbstractSequentialList, ArrayList
and Vector are all AbstractLists
LinkedList 4 LinkedList “is a” AbstractSequentialList

• However, an AbstractList is not


necessarily an
AbstractSequentialList, ArrayList or
Vector
4 “Is a” is a one way relationship
192
Lecture 19: Extending Classes

• Inheritance in Java is implemented by


extending a class
public class NewClass extends OldClass
{

4 We then continue the definition of
NewClass as normal
4 However, implicit in NewClass are all data
and operations associated with OldClass
• Even though we don’t see them in the
definition
– This is important! Don't forget this!

193
Lecture 19: private, public and protected

4 We already know what public and private


declarations mean
4 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
4 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 ex15.java 194
Lecture 20: Inheritance Example

• As another example
4 Compare MixedNumber class and
MixedNumber2 class
4 Both utilize the RationalNumber class from
the Lewis & Loftus text to do most of the
"work"
4 Both also have the same functionality, but
MixedNumber uses composition and
MixedNumber2 uses inheritance
• Note simplicity of MixedNumber2 methods
• Read over the comments carefully!
• See ex16.java, RationalNumber.java,
MixedNumber.java and MixedNumber2.java
195
RationalNumber
Lecture 20: Inheritance Example
int numerator
int denominator Composition: MixedNumber
-------------- MixedNumber class
add(), subtract(), utilizes a RationalNumber int whole
multiply(), object. Methods in RationalNumber frac
divide(), etc. MixedNumber must
--------------
manipulate the
RationalNumber object as add(), subtract(),
a "client", since it has no multiply(),
special relationship to divide(), etc.
RationalNumber

Inheritance:
RationalNumber MixedNumber2 class is a
MixedNumber2 extends RationalNumber, but with
RationalNumber modifications. Ex: The
int numerator
numerator in MixedNumber2
int denominator is that defined in
add(), subtract(), -------------- RationalNumber. Methods in
multiply(), add(), subtract(), RationalNumber can be used
divide(), etc. multiply(), directly, and new versions
divide(), etc. are only needed where the
return type must be
MixedNumber2.
196
Lecture 20: Inheritance Example

• Note Lines 67-109 in ex16.java


– In this code we are using RationalNumber
references to access both RationalNumber and
MixedNumber2 objects
> This is legal due to the "is a" relationship of
MixedNumber2 to RationalNumber
– We will examine this type of access in more
detail soon when we discuss polymorphism
• Important Note (will be repeated):
– When a superclass reference is used to access a
subclass object
> The only methods that are callable are those that
were initially defined in the superclass
> The object may have additional methods (defined
initially in the subclass) that cannot be called

197
Lecture 21: Java Class Hierarchy

• In Java, class Object is the base class


to all other classes
4 If we do not explicitly say extends in a new
class definition, it implicitly extends Object
4 The tree of classes that extend from
Object and all of its subclasses is called
the class hierarchy
4 All classes eventually lead back up to
Object
4 This will enable consistent access of
objects of different classes, as we shall
see shortly
198
Lecture 21: Polymorphism

• Idea of polymorphism
4 See internet definition:
• On Google type “definition polymorphism” and
see the results
– This search works for many CS terms that you may
be curious about
• http://www.webopedia.com/TERM/P/polymorphism.
html

4 Generally, it allows us to mix methods and


objects of different types in a consistent way
4 Earlier in the text, one type of polymorphism
was already introduced
199
Lecture 21: Method Overloading

4 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
200
Lecture 21: 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
4 See ex17.java
4 Note: This type of polymorphism is not
necessarily object-oriented – can be done
in non-object-oriented
201 languages
Lecture 21: Polymorphism

• Subclassing Polymorphism
4 Sometimes called “true polymorphism”
4 Consists basically of two ideas:
1) Method overriding
• A method defined in a superclass is redefined
in a subclass with an identical method
signature
• Since the signatures are identical, rather than
overloading the method, it is instead
overriding the method
– For subclass objects, the definition in the
subclass replaces the version in the superclass
– See OverrideDemo.java, SimpleAList.java,
SortAList.java
202
Lecture 21: Polymorphism

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
4 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 call203for each)
Lecture 21: 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+ move() move()
+)
• References are all the
A[i].move();
same, but objects are not
• move() method invoked is
that associated with the move()
OBJECT, NOT with the
204
reference
Lecture 21: Object, Method and Instance Variable Access

• Remember rules we discussed for


accessing subclass objects with
superclass references:
4 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
4 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 205
Lecture 21: Object, Method and Instance Variable Access

4 Ex:
• Suppose class Fish contains a new instance
variable waterType and a new method
getWaterType()
Fish F = new Fish();
Animal A = new Fish();
System.out.println(F.getWaterType()); // ok
System.out.println(A.getWaterType()); // NO!
– The above is NOT legal, even though the method
exists for class Fish. The reason is that the
method is not visible from the reference’s point of
view (A is an Animal reference so it can only “see”
the data and methods defined in class Animal)
System.out.println(((Fish) A).getWaterType());
– This is ok, since we have now cast the reference to
the Fish type, which CAN access the method
206
Lecture 21: Object, Method and Instance Variable Access

• 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 ex18.java for an example

207
Lecture 21: Object, Method and Instance Variable Access

• To summarize:
• Superclass references CAN BE used to
reference subclass objects
• Subclass references CANNOT BE used to
reference superclass objects
• The type of the reference determines what
public data and methods are ACCESSIBLE / can
be seen
• The type of the object determines what data
and methods EXIST
– Methods and data initially defined within a
subclass CANNOT BE accessed via a superclass
reference
– The type of the object also determines which
VERSION of an overridden method is called
208
Lecture 22: Abstract Classes

• Abstract classes
4 Sometimes in a class hierarchy, a class
may be defined simply to give cohesion to
its subclasses
• No objects of that class will ever be defined
• But instance data and methods will still be
inherited by all subclasses
4 This is an abstract class
• Keyword abstract used in declaration
• One or more methods may be declared to be
abstract and are thus not implemented
• No objects may be instantiated

209
Lecture 22: Abstract Classes

4 Subclasses of an abstract class must


implement all abstract methods, or they
too must be declared to be abstract
4 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
4 See ex19.java

210
Lecture 22: Java Interfaces

• Java allows only single inheritance


4 A new class can be a subclass of only one
parent (super) class
4 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
4 However, it is sometimes useful to be able
to access an object through more than one
superclass reference

211
Lecture 22: Java Interfaces

4 We may want to identify an object in


multiple ways:
• One based on its inherent nature (i.e. its
inheritance chain)
– Ex: A Person
– Classes are used to identify objects in this way
• Others based on what it is capable of doing
– Ex: A swimmer
– Ex: A musician
– Ex: A performer
– Note a Person can potentially do many things
> They can also be identified by this ability
– Interfaces are used to identify objects in this way

212
Lecture 22: Intro. to Interfaces

• A Java interface is a named set of


methods
• However, no method bodies are given – just
the headers [See note at bottom of this slide]
• Static constants are allowed, but no instance
variables are allowed
4 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
4 A given class can implement any number
of interfaces
213
Lecture 22: Intro. to Interfaces

4 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()
214
Lecture 22: 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

215
Lecture 22: Intro. to Interfaces

4 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
216
Lecture 22: Intro. to Interfaces

4 Ex:
Laughable [] funny = new Laughable[3];
funny[0] = new Comedian();
funny[1] = new SitCom(); // implements Laughable
funny[2] = new Clown(); // implements Laughable
for (int i = 0; i < funny.length; i++)
funny[i].laugh();

funny[0].boo(); // illegal even though Comedian


// has the boo() method
• See ex20.java
• This restricted access is the same behavior that
we saw with superclass variables and subclass
objects
• Interfaces are closely related to inheritance and
polymorphism
217
Lecture 22: Interfaces

4 Recall our previous discussion of polymorphism


4 This behavior also applies to interfaces – the
interface acts as a superclass and the
implementing classes implement the actual
methods however they want
4 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
4 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
218
Lecture 23: "Generic" Operations
4 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
219
Lecture 23: “Generic” Operations

4 They all can be compared to each other


• So we need some method that invokes this
comparison
4 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
4 Huh? ¿Qué?
• Perhaps it will make more sense if we develop
an example…but first we will need some
background!
220
• Let's look again as Selectionsort of ints from a
Lecture 23: "Generic" operations
public static void selectionSort(int [] array) Parameter is an array of
{ int
int startScan, index, minIndex, minValue; minValue is an int
for (startScan = 0; startScan < (array.length-1); startScan++)
{
minIndex = startScan;
minValue = array[startScan];
for(index = startScan + 1; index < array.length; index++)
{
if (array[index] < minValue) Primitive values are
{ compared using relational
minValue = array[index];
minIndex = index; ops
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
– Note code in red – this is the only code that is
specific to sorting an array of int

221
Lecture 23: “Generic” Operations
4 Consider the Comparable interface:
• It contains one method:
int compareTo(Object r);
• Returns a negative number if the current object is
less than r, 0 if the current object equals r and a
positive number if the current object is greater
than r
• Look at Comparable in the API
4 Consider what we need to know to sort data:
• is A[i] less than, equal to or greater than A[j]
– That's it – nothing else!
4 Thus, we can sort Comparable data
without knowing anything else about it
222
Lecture 23: "Generic" operations
public static void selectionSort(Comparable [] array) Parameter is array of
{ Comparable
int startScan, index, minIndex;
Comparable minValue; minValue is
Comparable
for (startScan = 0; startScan < (array.length-1); startScan++)
{
minIndex = startScan;
minValue = array[startScan];
for(index = startScan + 1; index < array.length; index++)
{
if (array[index].compareTo(minValue) < 0) Values compared using
{ the compareTo() method
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
– Same algorithm but now will work for any type that
implements Comparable
223
Lecture 23: “Generic” Operations

4 Think of 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
– And we could not access it anyway with Comparable
• Different classes may implement Comparable
differently
– Polymorphism allows this to work
4 Thus, a single sort method will work for an
array of any Comparable class
• See SortAll.java and ex21.java
– Also see SortAllT.java and ex21T.java
224
• Similar logic applies for searching (ex: Binary
Lecture 23: Generic Classes

• We can also write a generic class in


Java
4 Consider a collection class such as an
ArrayList
4 We would like to be able to store different
things in different ArrayLists
• Ex: An ArrayList of String, an ArrayList of
Integer, etc.
4 Or we may want to "mix and match items"
• Ex: An ArrayList of Object, where (by
inheritance) we can store any Java objects
4 If we want to mix and match we can must
make an array of Object225
• By "is a" we can put anything into that
Lecture 23: Generic Classes

4 However, what if we want to restrict the


data to be homogeneous
• We want a collection of a certain type and that
type only
• We would like the type to be arbitrary but we
also want it to be homogeneous
4 This can be done using parameterized
types in Java

226
Lecture 23: Parameterized Types

• Idea:
4 Consider a collection of data (ex: array list
but there are many others)
4 Allow an argument to be passed into the
collection type itself
• This argument will be another Java type, which
will indicate the "base type" for the collection
4 For example, rather than saying
• An array list (where it could store any Java
objects)
4 we instead say
• An array list OF T, where T is some Java type
227
Lecture 23: Parameterized Types

• This will limit the data to that particular type,


keeping the collection homogeneous
4 Ex: Consider type SimpleAList that we
discussed previously
• In this type the underlying data is an array of
String and the methods utilize String for
parameters and return values
• Thus, we can add / get / set only String in a
SimpleAList
– For other types we would need to define new
classes
4 We can redesign this type to be
parameterized, and thus restrict its data to
a single type
228
Lecture 23: Parameterized Types

4 However, we can take this one step


further using interfaces
• Recall previous handout ALvsLL.java
– The SimpleAList and SimpleLList classes had the
same functionality, but were implemented in
very different ways
– We can define this functionality in a generic
interface, and have both classes implement this
interface
– We can then use a variable of the interface type
to access an object of either class
• Look at SimpleListInterface.java
– Note that it specifies a parameter T and several
methods
– It does NOT specify how these will be
implemented 229
Lecture 23: Parameterized Types

4 Now we can implement


SimpleListInterface<T> in possibly more
than one way
• Perhaps one implementation is better for one
application and another better for a different
application
public class SimpleAListT<T> implements SimpleListInterface<T>
{ // data and method bodies in here }

public class SimpleLListT<T> implements SimpleListInterface<T>


{ // data and method bodies in here }
• Both classes implement this interface and can
be used for all of the operations
– However, the implementations vary greatly
(array vs. linked list)
– See SimpleAListT.java, SimpleLListT.java,
230
ALvsLL_Generic.java
Lecture 24: Graphical Interfaces

• So far all of our programs have used


4 Input from the keyboard (or file)
4 Output to the console (or file)

• This is effective but in today’s world is


not so user-friendly
4 Users want to use the mouse
4 Users want windows with dialog boxes and
buttons
4 Users need maximum guidance with
minimum room for error

231
Lecture 24: Graphical Interfaces

• Java has all of the tools for us to design


and implement complex graphical
interfaces
4 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
4 But once we learn how to do it we will
typically prefer it over console applications
232
Lecture 24: AWT and Swing

• The AWT (Abstract Windowing Toolkit)


was developed for the first versions of
Java
4 Created components such as Frame,
Panel, Button, TextField, Label
• However, the look and feel of the AWT
varied on different windowing systems
4 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
233
Lecture 24: 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
4 It also adds some extra features that did
not exist in the AWT
4 Many Swing components are similar to
AWT in name, but with a “J” in front
• Ex: JFrame, JPanel, JButton, JTextField, JLabel
234
Lecture 24: 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
4 As more programming moves toward Web
interfaces, JavaFX will gain in popularity
4 Can be used with Swing as well, so
learning Swing is still a good thing

235
Lecture 24: JavaFX vs. Swing

4 The newest edition of the Gaddis text


focuses on JavaFX and no longer features
Swing
• There is certainly good motivation to do this,
and it is certainly a good thing to learn JavaFX
• However, in CS 0401 we are focusing on object-
oriented programming and developing
applications with Swing fits better with our
recent class discussions of inheritance,
polymorphism and interfaces.
• Thus, we will focus on Swing for GUIs in this
course
4 If you have a new edition of Gaddis, you
can use the reference below for a Swing
tutorial: 236
Lecture 24: JFrames and JApplets

• JFrames are objects that will be the


windows in graphical applications
4 We can draw/paint graphics within them
4 We can place and manipulate graphical
components within them
• JApplets are similar in their
functionality to JFRames
4 However, they are run within the context
of another program (i.e. a Web browser)
4 Used to be very popular, but not so much
any more
237
Lecture 24: JFrames

• We will focus on JFrames


4 To use them we:
• Create a JFrame object
• Size it as desired
• Show it on the display
4 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
238
Lecture 24: JLabels

• JLabels are simple components to show


formatted text on the display
4 We can set the font type, size and color
4 We can set and change the text itself as
desired throughout program execution
• Let’s look at a very simple example:
4 Create a JFrame, then put a JLabel in it and
display it
4 See ex22a.java
• See the comments to determine how the
various objects are created and set up properly

239
Lecture 24: Simple Example
4 Note that this example does not really do
much
• No interaction with the user
4 But it does show us some of the basic
setup for graphical applications
4 Let’s now add a bit more functionality
• Add a button that user can click to change the
color of the label text

240
Lecture 24: JButtons

• JButtons are simple components that


can also show text on the display
4 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()
> Remember interfaces?

241
Lecture 24: Event-Driven Programming
– Thus any class that implements
actionPerformed() can be an ActionListener
• This causes the actionPerformed method within
the ActionListener to execute
– It is the actionPerformed method that is doing
the actual response to the button click
4 This idea is called event-driven
programming
• As program executes, user generates events in
various ways
– Ex: click a button, move the mouse, edit text
• Programmer writes code to respond to the
various events that may occur
• See trace on next slide (run as a presentation
to see effects)
242
Lecture 24: Event-Driven Programming

JButton AE ActionListener object

1) JButton is clicked
2) ActionEvent (AE)
generated public void
3) Event passed to actionPerformed( )
ActionListener {
4) actionPerformed // code to execute
executed
}
Note that because the
ActionEvent is passed to the
actionPerformed method, the
method can get information
from the ActionEvent through its 243
accessor methods
Lecture 24: Event-Driven Programming

4 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
4 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 244
• Do example in class
Lecture 24: Another Example

• Let’s look at another simple example:


4 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
4 The setup of this program is very similar to
ex22b.java
• Only difference is what the listener is doing
4 See ex22c.java

245
Lecture 24: Multiple Components

• If we want to have multiple


components, we need to determine
how to lay them out
4 To do this we use a layout manager
• These determine how components appear in a
window and how much space is allocated for
them
4 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-
246
dimensional rectangular grid
Lecture 24: Multiple Components

• If multiple components generate


events, we must also manage our
listeners
4 Do we share a listener between
components?
• Ex: ex22b2.java
4 Do we have a separate listener for each
component?
• Ex: ex22b3.java
4 Neither is right or wrong – but they behave
differently
• We need to know which is better for a given
situation 247
Lecture 25: Multiple Components

• Multiple components may also need to


interact with each other
4 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 ex22b.java and
ex22c.java
4 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
248 by a JButton
Lecture 25: Multiple Components

• We can use this to process input from a user


• For example to change the contents of a JLabel
or a JButton
• Let’s look at another example
4 Our JFrame will have a JButton and a
JTextField
• The JButton will behave as in ex22b – clicking it
will change the color of the text
• The JTextField will allow us to enter new text for
the JButton
4 We will also set things up differently to
allow for more convenient access
4 See ex22d.java – read the extensive
comments! 249
Independent Material: More on GUIs

• What if we want different parts of our


window laid out differently?
4 There is a GridBagLayout that allows for
arbitrary configurations, but it is quite
complicated to use
4 A simpler solution is to subdivide our
window
4 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
250
Independent Material: More on GUIs

4 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
4 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
251
Independent Material: More on GUIs

• How to terminate a graphical program?


4 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);
4 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 252
– Use a listener (ex: ActionListener)
Independent Material: More on JPanels

• What if we want to encapsulate data


within a JPanel?
4 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
4 What if we want it to also store and
manipulate our own data in the JPanel?
• We need to extend it using inheritance

253
Independent Material: Extending JPanels

4 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
• Now our new class has all of the functionality of
the original class
– The abilities of any Java JPanel to store, arrange
and manipulate components
• Plus any new functionality that we give it via
additional instance variables and methods
4 Things like this are what make inheritance
great!
• See Counters2.java 254
and JPanelDemo.java
Independent Material: Other GUI Features

• Java has a lot of other classes /


interfaces to allow us to build GUIs and
utilize them via event-driven
programming
4 See text and Java API for some examples
4 Ex: MouseEvent, MouseListener and
MouseMotionListener
• A MouseEvent is generated with the mouse is
clicked, released, moved or dragged (i.e.
moved while pressed down)
• Java has two listener interfaces to handle /
process these events
255
Independent Material: MouseEvents
• MouseListener:
– This has 5 methods to handle the various types
of mouse state events:
> mousePressed
> mouseReleased
> mouseClicked
> mouseEntered
> A new component
> mouseExited
> A component
• MouseMotionListener
> mouseMoved
> mouseDragged
– Programmer should define behaviors by
providing bodies for each of the methods
> See Mousey.java
256
Independent Material: MouseEvents

• Q: What if the programmer does not need to


handle all of the 5 types of events for
MouseListener?
– Still must provide all of them in order to fulfill the
MouseListener interface
• To help with this Java provides adapter classes
for listener interfaces containing more than one
method
– An adapter class contains trivial
implementations of all of the methods in the
interface
> Technically it meets the requirements of the
interface
> It just is not actually doing anything for each
method
– The programmer then extends the adapter and
overrides only the 257
methods he / she needs
Independent Material: Simple Shapes

4 Java also has tools to draw graphical


shapes
• It contains some simple predefined shapes and
components of shapes
• We can create larger, more interesting shapes
via composition
• We can also read in pictures / figures from files
4 Using events / listeners (ex: MouseEvent,
MouseListener and MouseMotionListener)
we can also manipulate these shapes
• See Mousey.java

258
Independent Material: Touch Events

4 Swing was developed prior to the common


use of touch screens
• Thus does not have built in handling of touch /
multi-touch
• Single touch can be handled via existing
MouseEvents
– Google “Java swing touch events”
• For multi-touch, your best bet is to use JavaFX
4 Look at a simple example from Oracle
• TouchEvents.java
– To run this you will also need the images
• Note how many import packages there are
– JavaFX has a LOT of abstraction

259
Lecture 25: Intro. to Exceptions in Java

• Run-time errors happen


4 User enters incorrect input
4 Resource is not available (ex. file)
4 Logic error (bug) that was not fixed

• For Production software


4 Having a program "crash" is a HIGHLY
UNDESIRABLE thing
• Users think software is no good
• Lose confidence

260
Lecture 25: Intro. to Exceptions in Java

• Exception:
4 An occurrence of an erroneous, unusual or
unexpected event in a program execution
4 In older languages
• Code the handling of exceptions into each area
of the program that needed it, typically with if
statements
• Some exceptions could not even be handled by
the HLL
– ex. standard Pascal cannot handle I/O errors or
division by 0
> We can still "handle" by extensive testing – but
only to prevent the error not to actually handle it
> Discuss
261
Lecture 25: Intro. to Exceptions in Java

4 In newer languages
• Exception handling built into the language
• We can separate exception handling from the
"main line" code
4 Java uses an exception handling model
similar to that used in C++

Exceptions are objects that


are thrown …
and catched
Some exceptions are built into the
language
Others can be created and thrown by the
programmer 262
Lecture 25: Exceptions in Java

• Java exception handling


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

263
Lecture 25: Exceptions in Java

4 If all goes well (no exceptions occur)


• Code in try block is executed, followed by code
in (optional) finally block
4 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
4 Note that in all cases the finally block is
executed if it is present
264
Lecture 25: Exceptions in Java

4 If an exception is handled
• Execution resumes immediately AFTER
try/catch block in which it was handled, and
does NOT return to throw point
• termination model of exception handling
– As opposed to a resumption model, where
execution resumes from where the exception
occurred
4 If an exception is propagated
• A handler is searched for by backing up
through the call chain on the run-time stack
(discuss)
• This is dynamic exception propagation
• If no handler is ever found
– Console applications crash and report
exception
– GUI applications will
265 continue to execute, but
Lecture 25: Exceptions in Java

• Checked vs. Unchecked exceptions


4 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
4 Unchecked exceptions
• Method not required to explicitly "throw" these
• These include RunTimeException
266
Lecture 25: Exceptions in Java

• Catching exceptions
4 Catching a superclass of an exception will
catch subclass exception objects
catch (Exception e)
> "catch all" if no other exceptions match
4 Should list exceptions in order of most
specific to most general
– If catch above is first NO OTHER catches in the
block could ever execute
4 It is better style to be as specific as
possible with the exceptions that are
caught
• See ex23.java
267
Lecture 26: Exceptions in GUIs

• GUIs run using multiple execution


threads
4 A thread is a logically separate execution
chain that shares the same data
• See board
4 Events in GUIs are generated and handled
by threads
4 In future courses you may see how to use
threads yourselves
4 For now we just want to know the effect of
exceptions on applications that have
multiple threads
268
Lecture 26: Exceptions in GUIs

4 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
4 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
4 It is best to always try to anticipate and
handle exceptions in GUIs

269
Lecture 26: Defining Exception Classes

4 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
4 See MiniCalcTwo.java, DoMathInt.java,
DoMathIntCheck.java

270
Lecture 26: Recursion

• A Java method can call any other


public Java method
4 main() is just a method itself, and we have
called other methods from it
4 Thus, a method should be able to call itself
– we call this a RECURSIVE CALL
• Since it is a method
4 At first thought this seems odd or even
impossible – why would we want to do
this?
4 However, it will be very useful in a lot of
different programming approaches
271
Lecture 26: Recursion

4 Before we look at the programming in detail,


let’s try to get the idea down, using math
4 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!
272
Lecture 26: Recursion

4 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
0! = 1case for factorial?
4 What is the base

N!now
4 This = N *allows
(N-1)! us to
when N>0
complete our
N! = 1
algorithm: when N = 0

273
Lecture 26: Recursion

4 Three important rules for any recursive


algorithm:
1) There must be some recursive case, in which
the algorithm “calls itself”
2) There must be some base case, in which no
recursive call is made
3) The recursive calls must lead eventually to the
base case
– Usually by “reducing” the problem size in some
way
4 Don’t forget these!

274
Lecture 26: More Recursion

4 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
MN =
1 N = 0 base case
• The actions we take are slightly different from
factorial, but the basic idea is similar
4 Trace this on board
• Note how first call made is last call to
complete
• This is important in the implementation of
recursion

275
Lecture 26: Implementing Recursion

• So how do we implement recursion?


4 Luckily the computer code is very similar
to the mathematical functions
4 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));
}

276
Lecture 26: Implementing Recursion

• How does recursion actually work?


4 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
4 Each new activation record is placed on
the top of the run-time stack
4 When a method terminates, its activation
record is removed from the top of the run-
time stack
4 Thus, the first AR placed onto the stack is
the last one removed
277
Lecture 26: Implementing Recursion

N = 1
N <= 1? YES fact(1)
return 1

N = 2
N <= 1? NO 1 fact(2)
return (2 * fact(1)) = 2

N = 3
N <= 1? NO 2
fact(3)
return (3 * fact(2)) = 6

N = 4
N <= 1? NO 6
fact(4)
return (4 * fact(3)) = 24

24
278
Lecture 26: Recursion vs. Iteration

4 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)
4 Other recursive algorithms are very
difficult to do any other way (ex: Towers of
Hanoi in text)
4 You will see more about recursion in CS
0445
4 For now, let’s look at
279 recursion.java
Lecture 27: More Recursion

4 Consider again functional abstraction


• User of a method does not need to know how it
is implemented
• However, often recursive methods require more
parameters than equivalent iterative methods
– Extra parameters enable the testing for base
cases
– This can be problematic if the methods are part
of an interface, which specifies the method
headers
• We can get around this by using an additional,
non-recursive method
– The additional method satisfies the required
header
– It then calls the recursive method, adding any
extra needed parameters
280
Lecture 27: More Recursion

4 For example, consider a method to reverse


an array of objects
• The header might be something like
public static void reverse(Object [] data)
• However, to implement this recursively, we
need extra parameters to keep track of the
logical beginning and end of the array
• These extra parameters can be added in a call
to the recursive method
public static void reverse(Object [] data)
{ rec_reverse(data, 0, data.length-1); }
• See a String version of this method in
recursion.java
• You will do similar implementations in Lab 13
281
Lecture 27: Recursive Linked List

• We can also implement data structures


recursively
4 Consider our generic linked list from
earlier in the term (SimpleLListT.java)
• Recall that the LL implements the
SimpleListInterface
• Nothing about that interface requires a specific
implementation
• Thus we can implement it recursively if we so
choose
• However, since we (usually) need extra
parameters for our recursive methods, we will
define extra private methods to do the
recursion
282
• See SimpleLListT_rec.java
Lecture 27: More Recursion

4 Let's look at one method:


public boolean add(T val)
• Recall that this will add a new value at the end
of the list
– To do this we must make a link from the
"current" last Node to the new Node
• Think recursively about how we would do this
• Special case
– List is empty! Add at the front without recursing
• Else call the recursive method
– Are we at the last Node? If so add after it
– Else recurse to the next Node and try again

283
Lecture 27: More Recursion
public boolean add(T val) // same public spec (must be since)
{ // it must satisfy interface
Node curr = front;
if (curr == null) // Special case for front node
{ // Don't need to recurse in this case
front = new Node(val);
size++;
return true;
}
else // Recursively add to end of list. Note the extra
// parameter in this call for the current Node.
return addAtEnd(curr, val);
}

284
Lecture 27: More Recursion
private boolean addAtEnd(Node curr, T val)
{
if (curr.next == null) // Base case -- current Node is
{ // last node in the list. Add new Node after
// it.
curr.next = new Node(val);
size++;
return true;
}
else // We are not yet at end, recursively add to the
// next Node
return addAtEnd(curr.next, val);
}
4 See code for rest of the implementation

285
Lecture 28: Exam Two

• Same length and general format as


Exam One
• Focus on Lectures 15-27
• See online review materials and
practice questions

• See next slides (287+) for some extra


material – this material will not be on
the exam

286
Bonus Material: File Types

1) Text Files – discussed previously


4 Advantage of text files:
• Can read them outside of the program by many
different editors or programs
• Easy to create
4 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 287
Bonus Material: Binary Files

2) Binary Files
4 Data in the file is stored in the same way
(or in a “serialized” version) that it is
stored in the program
• We can store arbitrary bytes or we can store
“whole” data types, including primitive types
(int, double, etc.) and objects (String, any
other Serializable object type)
– We will discuss Serializable more shortly

288
Bonus Material: File Types

4 Advantages:
• Since data is already in its binary form,
reading and writing require little if any
conversion and is faster than for text files
• Non-string data can often be stored more
efficiently in its binary form than in ASCII form
4 Disadvantage:
• Data in the files is not readable except via a
specific computer program
– Ex: A Java object in a file can only be read in by
a Java program
4 There are reasons to use both of these
types of files in various applications
289
Bonus Material: IO Streams

• In Java, file access is provided through


a hierarchy of file and stream classes
4 These allow various different access
functionalities implemented in a
systematic, consistent way
4 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

290
Bonus Material: IO Streams

• We have already seen a couple of


these:
4 Scanner (input), PrintWriter (output)

• There are many other IO Streams that


we can use in our programs
4 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
291 types
Bonus Material: Text vs. Binary Files

• We discussed previously that numeric


data can often be stored more efficiently
in binary form than in text form
4 Let's compare the two by writing the same
data (numbers) to a text file and a binary
file
4 Since the data is just numbers we can use a
DataOutputStream for our output
4 Allows only simple methods such as
writeInt(), writeDouble(), etc

292
Bonus Material: Text vs. Binary Files

• Let’s try this and then compare the


sizes of the binary and text files
4 We will generate a number of random ints
and random doubles
4 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 ex24.java 293
Bonus Material: Object Streams

• Java has the ability to write entire


objects to files in a serialized form
4 The class type as well as the instance
variables are written in a way that allows
the object to be restored easily upon
reading
4 This is done utilizing the
ObjectOutputStream and
ObjectInputStream classes
4 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
294
Serializable
• See ex25a.java, ex25b.java
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
4 Data structures such as vectors, stacks,
queues, linked-lists and trees are used
throughout computer science
4 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?

295
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
4 Data structures can be implemented in
various ways, each of which has
implications (ex: run-time differences, code
complexity, modifiability)
4 We should understand these data
structures from an implementer's point of
view:
• How can these data296structures be effectively
Extra Material: Preview of Data Structures

• We also want to understand and utilize


programming ideas and techniques
utilized in data structure
implementation
4 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?

297
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
4 Java is a very large language with
extensive capabilities
4 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?

298

You might also like