272
Course Notes for CS 0401 Intermediate Programming (with Java) By John C. Ramirez Department of Computer Science University of Pittsburgh

Lecture 1: Prerequisites

  • Upload
    field

  • View
    48

  • Download
    0

Embed Size (px)

DESCRIPTION

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: - PowerPoint PPT Presentation

Citation preview

Page 1: Lecture 1: Prerequisites

Course Notes for

CS 0401Intermediate Programming

(with Java)By

John C. RamirezDepartment of Computer Science

University of Pittsburgh

Page 2: Lecture 1: Prerequisites

2

• 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 Objects, Third to Sixth Editions by Gaddis

4 Java Software Solutions, Fourth and Fifth Editions by Lewis and Loftus

4 Java By Dissection by Pohl and McDowell4 The Java Tutorial (click for link)4 The Java tech home page and its many sub-

links:http://www.oracle.com/technetwork/java/index.html

Page 3: Lecture 1: Prerequisites

3

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 expressions– Numbers, characters, operators, precedence

Page 4: Lecture 1: Prerequisites

4

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

Page 5: Lecture 1: Prerequisites

5

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 extended review!

Page 6: Lecture 1: Prerequisites

6

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

Page 7: Lecture 1: Prerequisites

7

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

Page 8: Lecture 1: Prerequisites

8

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, 15)• Introduction to recursion (Chapter 16)

Page 9: Lecture 1: Prerequisites

9

Lecture 2: Why Java?

• Java4 Java is an interpreted, platform-

independent, object-oriented language• Interpreted, platform-independent:

– Source .java code is compiled into intermediate (byte) code

– Byte code is executed in software via another program called an interpreter

– Benefits: > More safety features and run-time checks can be

built into the language – discuss> Code can be platform-independent> As long as the correct interpreter is installed, the

same byte code can be executed on any platform

Page 10: Lecture 1: Prerequisites

10

Lecture 2: Why Java?

JavaSourceCode(.java)

Java Compiler

JavaByteCode

(.class)

JRE for Windows

JRE for Solaris

JRE for Mac

JRE for Linux

The same .class file can execute on any platform, as long as the JRE is installed there

Page 11: Lecture 1: Prerequisites

11

Lecture 2: Why Java?

– Drawback:> Interpreted code executes more slowly than

regular compiled code> Since program is run in software rather than

hardware, it cannot match the execution times of code that is compiled for specific hardware

> Ex: C, C++ code> No language is best for every application> However, Java implementations can use JIT

compilation of bytecode to execute faster• Object-oriented

– Primary mode of execution is interaction of objects with each other

– We will discuss object-oriented programming in much more detail soon

Page 12: Lecture 1: Prerequisites

12

Lecture 2: 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

Page 13: Lecture 1: Prerequisites

13

Lecture 2: Getting Started with Java

4 Both programs come with the Java Development Kit (JDK)• This is installed on all of the lab PCs other CS

machines• The most recent version (SE 8) can be easily

downloaded and installed from the Oracle Web site:

– http://www.oracle.com/technetwork/java/index.html

– It is free!• More on the basics of using the Java software

development kit is shown in Lab 1– Look for it online soon -- you will do it next week

• But let’s look at an ex. and talk more about Java basics

– See ex1.java – Carefully read the comments!

Page 14: Lecture 1: Prerequisites

14

Lecture 2: Getting Started with Java

• When you have a chance, try the following:– Download ex1.java from the Web site onto a PC

that has the JDK installed (yours or a lab PC)– Open a terminal (command prompt) window– Change to the correct directory– Compile the program: javac ex1.java– Execute the program: java ex1

> Adding the .class extension is optional – it is assumed even if you don’t put it there

– Show the directory to see that the .class file is now there

• Also try the same thing from one of the Lab workstations during your first lab session

Page 15: Lecture 1: Prerequisites

15

Lecture 2: 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 if you wish

Page 16: Lecture 1: Prerequisites

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

Page 17: Lecture 1: Prerequisites

Lecture 2: Java Basics – I/O

• (I)/O (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

Page 18: Lecture 1: Prerequisites

Lecture 2: Java Basics – I/O

• We can output strings, values of variables and expressions and other information using System.out

• We will see more on this once we discuss variables

• We will understand how System.out works more precisely after we have discussed classes and objects later in the term

18

Page 19: Lecture 1: Prerequisites

19

Lecture 2: Java Basics – Identifiers and Variables

• Lexical elements – groups of characters used in program code4 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 complete list

Page 20: Lecture 1: Prerequisites

20

Lecture 2: Java Basics – Identifiers and Variables

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

Page 21: Lecture 1: Prerequisites

Lecture 2: Java Basics – Identifiers and Variables

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

Page 22: Lecture 1: Prerequisites

22

Lecture 2: Java Basics – Identifiers and Variabls

• Important Note:– Java identifiers are case-sensitive – this means that

upper and lower case letters are considered to be different – be careful to be consistent!

– Ex: ThisVariable and thisvariable are NOT the same• Naming Convention:

– Many Java programmers use the following conventions:

> Classes: start with upper case, then start each word with an upper case letter

> Ex: StringBuffer, BufferedInputStream, ArrayIndexOutOfBoundsException

> Methods and variables: start with lower case, then start each word with an upper case letter

> Ex: compareTo, lastIndexOf, mousePressed

Page 23: Lecture 1: Prerequisites

23

Lecture 2: Java Basics – Identifiers and Variables

• Variables• Memory locations that are associated with

identifiers• Values can change throughout the execution of a

program• In Java, must be specified as a certain type or

class– The type of a variable specifies its properties: the

data it can store and the operations that can be performed on it

> Ex: int type: discuss [we will revisit this idea often]– Java is fairly strict about enforcing data type values

> You will get a compilation error if you assign an incorrect type to a variable: Ex: int i = “hello”;

incompatible types found: java.lang.String required: int int i = "hello"; ^

Page 24: Lecture 1: Prerequisites

24

Lecture 2: Java Basics – Identifiers and Variables

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: 1235 Ex: -39841

– Ex: String> A sequence of characters contained within double

quotes> Ex: "Hello there CS 0401 Students!"

• See Section 2.3 for more details on literals

Page 25: Lecture 1: Prerequisites

25

Lecture 2: Java Basics – Statements and Expressions

• Statements• Units of declaration or execution• A program execution can be broken down into

execution of the program’s individual statements

• Every Java statement must be terminated by a semicolon (;)

• Ex: Variable declaration statementint var1, var2;

• Ex: Assignment statementvar1 = 100;

• Ex: Method callSystem.out.println(“Answer is “ + var1);

• We will see many more statements later

Page 26: Lecture 1: Prerequisites

26

Lecture 2: Java Basics – Statements and Expressions

– Note: For numeric types, you get an error if the value assigned will “lose precision” if placed into the variable

> Generally speaking this means we can place “smaller” values into “larger” variables but we cannot place “larger” values into “smaller” variables

> Ex: byte < short < int < long < float < double – Ex: int i = 3.5;

– Ex: double x = 100;> This is ok

possible loss of precision found : double required: int

int i = 3.5; ^

Page 27: Lecture 1: Prerequisites

27

Lecture 3: Java Basics – Statements and Expressions

– Floating point literals in Java are by default double

> If you assign one to a float variable, you will get a “loss of precision error” as shown in the previous slide

– If you want to assign a “more precise” value to a “less precise” variable, you must explicitly cast the value to that variable typeint i = 5;

int j = 4.5;float x = 3.5;float y = (float) 3.5;double z = 100;i = z;y = z;z = i;j = (long) y;j = (byte) y;

Error check each of thestatements in the box to

the right

Page 28: Lecture 1: Prerequisites

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;

– 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

var1 100

Page 29: Lecture 1: Prerequisites

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

– 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

s Hello There

Page 30: Lecture 1: Prerequisites

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

• 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

cannot resolve symbol symbol : variable x

location : class classname x = 5.0;

^

Page 31: Lecture 1: Prerequisites

Lecture 3: Data and Expressions

• Multiple variables of the same type can be declared and initialized in a single statement, as long as they are separated by commas

– Ex: int i = 10, j = 20, k = 45;• Multiple variables of different types cannot be

declared within a single declaration statement• See ex2.java

31

Page 32: Lecture 1: Prerequisites

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 for integer operands and gives the remainder of integer division

> However, % can be used with floating point as well

int i, j, k, m;i = 19; j = 7;k = i / j; // answer?m = i % j;// answer?

Page 33: Lecture 1: Prerequisites

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

Page 34: Lecture 1: Prerequisites

34

Lecture 3: More Operators

• Java has a number of convenience operators4 Allow us to do operations with less typing4 Ex:

X = X + 1; X++;Y = Y – 5; Y –= 5;

4 See Section 2.6 for more details4 One point that should be emphasized is

the difference between the prefix and postfix versions of the unary operators• What is the difference between the statements:

X++; ++X;– Discuss– See ex3.java

Page 35: Lecture 1: Prerequisites

Lecture 4: Input and the Scanner Class

• Input4 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 stream4 By default this object allows us to read

data from the console / keyboard

35

Page 36: Lecture 1: Prerequisites

36

Lecture 4: Input and the Scanner Class

• In JDK releases up to 1.44 Console text input was fairly complicated

to use4 Objects had to be created and exceptions

had to be handled4 Made it difficult to show students learning

Java simple input and output• Consequently, textbook authors often created

their own classes to make console I/O easier• But they weren't standard Java, so students

would not find them useful after their courses ended

• In JDK 1.5, the Scanner class was added

Page 37: Lecture 1: Prerequisites

37

Lecture 4: 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 delimiter4 The tokens can be read in either as Strings

• next()4 Or they can be read as primitive types

• Ex: nextInt(), nextFloat(), nextDouble()

Page 38: Lecture 1: Prerequisites

38

Lecture 4: 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: helloException in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at ex3.main(ex3.java:39)

• These types of errors are run-time errors and in Java are called exceptions

• Java has many different exceptions• We'll look at exceptions in more detail later

4 Let's look at ex4.java

Page 39: Lecture 1: Prerequisites

39

Lecture 4: Control Statements

• Java Statements4 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 execute more than one time

Page 40: Lecture 1: Prerequisites

40

Lecture 4: Control Statements

Linear Execution Conditional Execution Iterative Execution

Page 41: Lecture 1: Prerequisites

41

Lecture 4: Boolean Expressions

• Key to many control statements in Java are boolean expressions4 Expressions whose result is true or false

• true and false are predefined literals in Java4 Can be created using one or more

relational operators and logical operators• Relational operators

– Used to compare (i.e. relate) two primitive values

– Result is true or false based on values and the comparison that is asserted

Ex: 6 < 10 -- true because 6 IS less than 10 7 != 7 -- false because 7 IS NOT not equal to

7

Page 42: Lecture 1: Prerequisites

42

Lecture 4: Boolean Expressions

• Java has 6 relational operators< <= > >= == !=

4 Some boolean expressions are more complicated than just a simple relational operation

• These expressions require logical operators

– Operate on boolean values, generating a new boolean value as a result

! && ||– Recall their values

from a truth table

A B

true true

true false

false true

false false

!A

false

false

true

true

A&&B

true

false

false

false

A||B

true

true

true

false

Page 43: Lecture 1: Prerequisites

43

Lecture 4: Boolean Expressions

• Let’s look at some examplesint 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)

Page 44: Lecture 1: Prerequisites

44

Lecture 4: 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 statements4 else + <false option> is optional4 Note parens around booleanexpression -

required

Page 45: Lecture 1: Prerequisites

45

Lecture 5: if statement

• Nested ifs4 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

Page 46: Lecture 1: Prerequisites

46

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

Page 47: Lecture 1: Prerequisites

47

Lecture 5: if statement

• Thus, there is no problem for the computer– Problem is if the programmer does not

understand the rule– Result is a LOGIC ERROR

> Logic errors can be very problematic and difficult to correct

> Unlike a syntax error, which prevents the program from being compiled, with a logic error the program may run and may seem fine

> However, one or more errors in the programmer’s logic cause the result will be incorrect!

– Compare on board: SYNTAX ERROR, RUN-TIME ERROR, LOGIC ERROR

• Luckily, in this case the problem is easy to correct

– How?

Page 48: Lecture 1: Prerequisites

48

Lecture 5: while loop

• The while loop is also intuitivewhile (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?

Page 49: Lecture 1: Prerequisites

49

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 average4 Let’s do this together, trying to come up

with a good solution4 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?

Page 50: Lecture 1: Prerequisites

50

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 Let’s look at two possible solutions• ex5a.java and ex5b.java• Note that for many programming problems,

there are MANY possible solutions

Page 51: Lecture 1: Prerequisites

51

Lecture 6: for loop

• The for loop is more complicated4 Its obvious use is as a counting loop

• Goes through a specified number of iterationsfor (int i = 0; i < max; i++){ // will iterate max times }

4 However it is much more general than thatfor (init_expr; go_expr; inc_expr){

// loop body}• Let’s talk about this a bit

Page 52: Lecture 1: Prerequisites

52

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

body4 These expressions make the for loop

extremely flexible

Page 53: Lecture 1: Prerequisites

53

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

Page 54: Lecture 1: Prerequisites

54

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

Page 55: Lecture 1: Prerequisites

55

Lecture 7: switch statement

• We know that if can be used in a multiple alternative form4 If we nest statements

• Sometimes choices are simple, integral values4 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!

Page 56: Lecture 1: Prerequisites

56

Lecture 7: switch statement

switch (int_expr){

case constant_expr: … case constant_expr: … default: // this is optional

}4 int_expr is initially evaluated4 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

Page 57: Lecture 1: Prerequisites

57

Lecture 7: switch statement

• If we want the execution of the different cases to be exclusive of each other, we need to stop execution prior to the next case

– We can do this using the break statement• Switch is actually passed down to Java from C –

it doesn’t really fit too well with the spirit of the Java language, but it is there and can be used

• Let’s look at an example using switch– Program to rate movies– User enters a “star” value from 1-4 and the

program comments back on the movie quality– See ex6.java

> Handout also shows some formatting> See also ex6b.java

Page 58: Lecture 1: Prerequisites

58

Lecture 7: Methods and Method Calls

• If programs are short4 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 longer4 Programming in a single segment gets

more and more difficult• Logic is more complex• Many variables / expressions / control

statements

Page 59: Lecture 1: Prerequisites

59

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• Ex: Break some sticks!

Page 60: Lecture 1: Prerequisites

60

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

Page 61: Lecture 1: Prerequisites

61

Lecture 7: Functional Abstraction

• Methods provide us with functional (or procedural) abstraction4 We do not need to know all of the impl.

details of the methods in order to use them• We simply need to know

– What arguments (parameters) we must provide– What the effect of the method is (i.e. what does

it do?)• The actual implementation could be done in

several different ways• Ex: Predefined method: sort(Object [] a)

– There are many ways to sort!• This allows programmers to easily use methods

that they didn't write

Page 62: Lecture 1: Prerequisites

62

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 expressionEx: 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 statementsEx: System.out.println(“Wacky”);

Arrays.sort(myData);

Page 63: Lecture 1: Prerequisites

63

Lecture 7: Predefined Methods

• There are MANY predefined methods in Java4 Look in the online API4 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 methodEx: Y = Math.sqrt(X);• These are called STATIC methods or CLASS

methods– They are associated with a class, not with an

object

Page 64: Lecture 1: Prerequisites

64

Lecture 7: Predefined Methods

4 Some methods are also called in the following wayClassName.ObjectName.methodName(param_list

)• Where ObjectName is the name of a static,

predefined object that contains the methodEx: 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 on static methods

Page 65: Lecture 1: Prerequisites

65

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

Page 66: Lecture 1: Prerequisites

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

Page 67: Lecture 1: Prerequisites

67

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

Page 68: Lecture 1: Prerequisites

68

Lecture 7: Writing Static Methods

Ex: public static double area(double radius){

double ans = Math.PI * radius * radius;return ans;

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

parameterargument

Page 69: Lecture 1: Prerequisites

69

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

Main Class

2.0rad

area method

radius 2.0

main calls area method

value passed from arg. to parameter

double theArea = area(rad);

theAreadouble ans =

Math.PI * radius * radius;

return ans;

ans 12.566…result returned to main12.566…

answer calculated

answer returnedmethod completed

Page 70: Lecture 1: Prerequisites

70

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

Page 71: Lecture 1: Prerequisites

71

Lecture 8: Local variables and scope

• Variables declared within a method are local to that method4 They exist only within the context of the

method4 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

Page 72: Lecture 1: Prerequisites

72

Lecture 8: Local variables and scope

• However, Java variables can also be declared within blocks inside of methods4 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

Page 73: Lecture 1: Prerequisites

73

Lecture 8: Local variables and scope

• Note that either way, local variables cannot be shared across methods4 In other words, a local variable declared in

one method cannot be accessed in a different method

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!• See ex7.java

Page 74: Lecture 1: Prerequisites

74

Lecture 8: References and Reference Types

• Recall from Slides 28-29 that Java has primitive types and reference types4 Also recall how they are stored

• With primitive types, data values are stored directly in the memory location associated with a variable

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

var1 100

s Hello There

Page 75: Lecture 1: Prerequisites

75

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 Curved 105 inch 4K Ultra HD LED TV

Page 76: Lecture 1: Prerequisites

76

Lecture 8: Classes and Objects

• What do we mean by "objects"?4 Let's first discuss classes, then objects,

since the two are related• 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• The data gives us the structure of the objects

and the operations show us how to use them• Ex: A String

– Discuss

Page 77: Lecture 1: Prerequisites

77

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

previously4 Java classes determine the structure and

behavior of Java objects4 To put it another way, Java objects are

instances of Java classes

Page 78: Lecture 1: Prerequisites

Lecture 8: Classes and Objects

78

class Foo{ int x; void f(); …}

Foo F;F = new Foo(10); F

x = 10f()

Class Foo definition

Foo object

Declaring Foo variableCreating Foo object

Foo reference

Page 79: Lecture 1: Prerequisites

79

Lecture 8: More References

• Back to references, let's now see some of the implications of reference variables4 Declaring a variable does NOT create an

object• We must create objects separately from

declaring variablesStringBuilder S1, S2;– Right now we have no actual StringBuilder

objects – just two variables that could access them

– To get objects we must use the new operator or call a method that will create an object for us

S1 = new StringBuilder("Hello");– S1 now references an instance of a StringBuilder

object but S2 does not

Page 80: Lecture 1: Prerequisites

80

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 objectS2 = S1;• Now any change via S1 or S2 will update the

same objectS1

S2

Hello

Page 81: Lecture 1: Prerequisites

81

Lecture 8: More References

4 Properties of objects (public methods and public instance variables) are accessed via "dot" notationS1.append(" there Java maestros!");• S2 will also access the appended object

4 Comparison of reference variables using == compares the references, NOT the objectsStringBuilder S3 = new StringBuilder("Hello there Java maestros!");if (S1 == S2) System.out.println("Equal"); // yesif (S1 == S3) System.out.println("Equal"); // no

– S1 and S3 reference different objects, so they have different addresses, regardless of the object contents

• What if we want to compare the object contents?

Page 82: Lecture 1: Prerequisites

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

Page 83: Lecture 1: Prerequisites

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 resultsS1 = null;S1.append("This will not work!");

Page 84: Lecture 1: Prerequisites

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.java4 Side note: speaking of common errors

• Take another look at debug.ppt – it has some of the things we just mentioned

Page 85: Lecture 1: Prerequisites

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

Page 86: Lecture 1: Prerequisites

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

Page 87: Lecture 1: Prerequisites

87

Lecture 9: Objects and Data Abstraction

• Consider primitive types4 Each variable represents a single, simple

data value4 Any operations that we perform on the

data are external to that dataX + Y

X 10

Y 5+

Page 88: Lecture 1: Prerequisites

88

Lecture 9: Objects and Data Abstraction

• Consider the data4 In many applications, data is more

complicated than just a simple value4 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)

Page 89: Lecture 1: Prerequisites

89

Lecture 9: Objects and Data Abstraction

• Consider the operations4 Now consider operations that a Polygon can

do• Note how that is stated – we are seeing what a

Polygon CAN DO rather than WHAT CAN BE DONE to it

• This is another fundamental idea of OOP – objects are ACTIVE rather than PASSIVE

• Ex: – void addPoint(int x, int y) – add a new point to

Polygon– boolean contains(double x, double y) – is point

(x,y) within the boundaries of the Polygon– void translate(int deltaX, int deltaY) – move all

points in the Polygon by deltaX and deltaY

Page 90: Lecture 1: Prerequisites

90

Lecture 9: Objects and Data Abstraction

4 These operations are actually (logically) PART of the Polygon itselfint [] 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

Page 91: Lecture 1: Prerequisites

91

Lecture 9: Objects and Data Abstraction

4 Objects enable us to combine the data and operations of a type together into a single entity: encapsulationP

xpoints [0,4,4,0]ypoints [0,0,2,2]

npoints 4

addPoint()contains()translate()

Thus, the operations are

always implicitly acting on the object’s dataEx: translate

means translate the points that

make up P

Page 92: Lecture 1: Prerequisites

92

Lecture 9: Objects and Data Abstraction

4 For multiple objects of the same class, the operations act on the object specifiedint [] moreXs = {8, 11, 8};int [] moreYs = {0, 2, 4};Polygon P2 = new Polygon(moreXs, moreYs, 3);

P

xpoints [0,4,4,0]ypoints [0,0,2,2]

npoints 4

addPoint()contains()translate()

P2

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

npoints 3

addPoint()contains()translate()

Both objects have the same

blueprint

…but they are distinct

instances

Page 93: Lecture 1: Prerequisites

93

Lecture 9: Encapsulation and Data Abstraction

• Recall that we previously discussed data abstraction4 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 object4 This concept is exemplified through

objects• We can think of an object as a container with

data and operations inside– We can see some of the data and some of the

operations, but others are kept hidden from us– The ones we can see give us the functionality of

the objects

Page 94: Lecture 1: Prerequisites

94

Lecture 9: Encapsulation and Data Abstraction

• As long as we know the method names, params and how to use them, we don't need to know how the actual data is stored4 Note that I can use a

Polygon without knowing how the data is stored OR how the methods are implemented• I know it has points

but I don't know how they are stored

• Data Abstraction!

P

xpoints [0,4,4,0]ypoints [0,0,2,2]

npoints 4

addPoint()contains()translate()

Page 95: Lecture 1: Prerequisites

95

Lecture 9: Instance Variables

• Let us look again at StringBuilder4 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!!!

Page 96: Lecture 1: Prerequisites

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

Page 97: Lecture 1: Prerequisites

97

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 objectStringBuilder B = new StringBuilder(“this is “);B.append(“really fun stuff!”);System.out.println(B.toString());

Page 98: Lecture 1: Prerequisites

98

Lecture 9: Class Methods vs. Instance Methods

4 Class methods have no implicit data to act on• They are not associated with individual objects• All data must be passed into them using

arguments• Class methods are called using:

ClassName.methodName(param list)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• Instance methods are called using:

variableName.methodName(param list)where variableName is a reference to an object

Page 99: Lecture 1: Prerequisites

99

Lecture 9: 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 constructorB = new StringBuilder(10); // capacity 10

Page 100: Lecture 1: Prerequisites

100

Lecture 9: Constructors, Accessors and Mutators

4 Accessors• These methods are used to access the object in

some way without changing it• Usually used to get information from it• No special syntax – categorized simply by their

effectStringBuilder 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

Page 101: Lecture 1: Prerequisites

101

Lecture 9: Constructors, Accessors and Mutators

4 Mutators• Used to change the object in some way• Since the instance variables are usually private,

we use mutators to change the object in a specified way without needing to know the instance variablesB.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 object4 We use accessors and mutators to

indirectly access the data, since we don’t have direct access – see ex9.java

Page 102: Lecture 1: Prerequisites

102

Lecture 10: Simple Class Example

• We can use these ideas to write our own classes4 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!!!)

Page 103: Lecture 1: Prerequisites

103

Lecture 10: More on Classes and Objects

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

Page 104: Lecture 1: Prerequisites

104

Lecture 10: Developing Another Example

• Remember the things we need for a class:4 Instance variables

• Fill in ideas from board4 Constructors

• Fill in ideas from board4 Accessors

• Fill in ideas from board4 Mutators

• Fill in ideas from board

Page 105: Lecture 1: Prerequisites

105

Lecture 10: 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

4 Let's look at one example

Page 106: Lecture 1: Prerequisites

106

Lecture 11: Intro. to Java Files

• So far4 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?

Page 107: Lecture 1: Prerequisites

107

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

interpreted in a different way

Page 108: Lecture 1: Prerequisites

Lecture 11: Java Text Files

– To create an actual int we need to convert the characters into an integer – this is what the nextInt() method in the Scanner class does> We will discuss the conversion procedure more

later– If we want to read data into an object with

many instance variables, we can read each data value from the file then assign the object via a constructor or via mutators> See PlayListTest.java

– If we want to fill an array, we can read in as many values as we need> We may first need to read in how many values

there are, then create the array and read in the actual data

> See PlayListTest.java and another example soon

108

Page 109: Lecture 1: Prerequisites

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 API109

Page 110: Lecture 1: Prerequisites

Lecture 11: Java Text Files

• It is fairly simple to use– See FileTest.java

• However, when creating the file an Exception can occur

– We will see how to handle this later– For now we will “pass the buck”– We do this via the “throws” clause in the method

header> States that we are not handling the exception> Must be stated in a method where the exception

could occur or in any method that calls a method … (since the exception is passed on)

– See FileTest.java

110

Page 111: Lecture 1: Prerequisites

111

Lecture 11: Arrays

• So far (for the most part) we have stored data in a 1:1 fashion4 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

Page 112: Lecture 1: Prerequisites

112

Lecture 11: 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?

Page 113: Lecture 1: Prerequisites

113

Lecture 11: Arrays

4 We can’t know the final order until all scores have been read• Last value could be smallest, largest or

anywhere in between4 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

Page 114: Lecture 1: Prerequisites

114

Lecture 11: Java Arrays

• Java Arrays4 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

Page 115: Lecture 1: Prerequisites

115

Lecture 11: Java Arrays

• Syntax:4 First, consider only PRIMITIVE TYPE data4 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

arrayvar_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

Page 116: Lecture 1: Prerequisites

116

Lecture 11: Java Arrays

4 Ex:int [] myArray;myArray = new int[20]; // size can be a variable

// or expression4 These two steps can be done as one if

we’d likeint [] 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

• We can change these values via indexing

Page 117: Lecture 1: Prerequisites

117

Lecture 11: Java Arrays

• Indexing an array4 An array variable gives us access to the

“beginning” of the array4 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

Page 118: Lecture 1: Prerequisites

118

Lecture 12: Java Arrays

• Iterating through an array4 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 counterfor (int value : myArray){

System.out.println(“Next value is : “ + value);}

Page 119: Lecture 1: Prerequisites

119

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 a file example

Page 120: Lecture 1: Prerequisites

120

Lecture 12: References and Reference Types

• Recall from previous discussions that Java has primitive types and reference types4 Also recall (once again!) how they are

stored• With primitive types, data values are stored

directly in the memory location associated with a variable

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

var1 100

s Hello There

Page 121: Lecture 1: Prerequisites

121

Lecture 12: Arrays as Reference Types

• Java arrays are reference types4 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];for (int i = 0; i < 5; i++)

A[i] = 2*i;int [] B = A;A[3] = 5;A = new int[4];A[1] = 3;A[3] = 7;

A

0 01 22 43 64 8

0 01 02 03 0

B

5

3

7

Page 122: Lecture 1: Prerequisites

122

Lecture 12: Arrays as Parameters

• Recall that all Java parameters are value4 A copy of the argument is passed to the

param4 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

• We cannot change the argument variable in the method but we CAN mutate the array object!

Page 123: Lecture 1: Prerequisites

123

Lecture 12: Arrays as Parameters

4 See ex11.java4 Sounds confusing, right?

• Not so much once you picture it!• Show example on board• We will also see an example shortly

4 This allows us to change arrays within methods• Ex: Read data into an array• Ex: Remove data from an array• Ex: Sort an array

Page 124: Lecture 1: Prerequisites

124

Lecture 12: 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

Page 125: Lecture 1: Prerequisites

125

Lecture 12: Sequential Search

• Sequential Search4 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 algorithms4 Q: What kind of loop is best for this?

• Think about what needs to be done4 Let’s look at an example: ex12a.java

Page 126: Lecture 1: Prerequisites

126

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

Page 127: Lecture 1: Prerequisites

127

Lecture 13: Arrays of Objects

• However, remember that objects are accessed by reference types

• Thus, when we create the array, we have an array of references, with no objects yet

– All of the locations are initialized to null– We need to create objects to store in the array

separately• For example:

String [] names;names = new String[5];names[1] = new String(“Herb”);names[3] = new String(“Madge”);names[4] = new String(“Mort”);– names[0] and names[2] are still null– Show on board

Page 128: Lecture 1: Prerequisites

128

Lecture 13: Arrays of Objects

• Note that we have two levels of references here

• See PlayListTest.java for another example

names0

1

2

3

4

Herb

Madge

Mort

Page 129: Lecture 1: Prerequisites

129

Lecture 13: Arrays as Instance Data and Composition

• When we create a new class we can have arbitrary instance variables within it4 If the instance variables are reference types

(i.e. other classes) we say we are building a new class via composition • We are “composing” the new class from pieces that

already exist, putting them together in an appropriate way

• We briefly discussed this already with the PlayList class

• Also sometimes called aggregation• Our use of these classes is limited to the

functionality provided as public– We are building new classes using “off the shelf”

components, so we may have to compromise based on what the “off the shelf” components can do

Page 130: Lecture 1: Prerequisites

Lecture 13: Arrays as Instance Data and Composition

4 As a simple example, consider the Player class from Assignment 2• Inside Player you have a String for the name

plus some primitive types for the rounds and money

• Thus you are composing your Player class out of the existent String class (plus some primitives)

• From within Player:– We are a client of String, having access to the

public methods in the String class• From outside Player:

– User may not even know a String is used since it is a private instance variable

– String is abstracted out of the user’s view130

Page 131: Lecture 1: Prerequisites

131

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

Page 132: Lecture 1: Prerequisites

132

Lecture 13: Resizing an array

• Java array objects can be of any size4 However once created, they cannot be

resized4 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 time– Ex: Students in a university

Page 133: Lecture 1: Prerequisites

133

Lecture 13: 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!

Page 134: Lecture 1: Prerequisites

Lecture 13: Resizing an array

4 What if we don’t have enough data to fill all of those new slots?• We must keep track of the number of locations

that are actually being used in the array– i.e. we need an additional variable besides the

array data itself• This way we can “add” elements to the end of

the array until it fills – only then will we have to resize

• Note that the array size and number of elements being stored in the array are not necessarily the same

• This is what is done in the predefined ArrayList class

• See ResizeDemo.java134

Page 135: Lecture 1: Prerequisites

Lecture 14: Exam One

• Exam One

135

Page 136: Lecture 1: Prerequisites

136

Lecture 15: 2-D Arrays

• Two-D arrays in Java are actually arrays of arraysint [][] 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

Page 137: Lecture 1: Prerequisites

Lecture 15: ArrayLists

• Programmers can use arrays in arbitrary ways4 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 137

Page 138: Lecture 1: Prerequisites

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• We simply need to look up its functionality in

the Java API4 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

necessary4 Look at a simple example: ArrayL.java

138

Page 139: Lecture 1: Prerequisites

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

139

Page 140: Lecture 1: Prerequisites

Lecture 15: ArrayLists

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

140

Page 141: Lecture 1: Prerequisites

141

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 < j4 A is sorted in descending order if

A[i] > A[j] for all i < j4 Q: What if we want non-decreasing or non-

increasing order?• What does it mean and how do we change the

definitions?

Page 142: Lecture 1: Prerequisites

142

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

Page 143: Lecture 1: Prerequisites

143

Lecture 16: SelectionSort

• SelectionSort is very intuitive:4 Idea:

Find the smallest item and swap it into index 0Find the next smallest item and swap it into index

1Find the next smallest item and swap it into index

2…Find the next smallest item and swap it into index

N-2• What about index N-1?

4 Let’s trace it on the board for the following data:

0 1 2 3 4 5 6 735 50 20 40 75 10 15 60

Page 144: Lecture 1: Prerequisites

144

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?

Page 145: Lecture 1: Prerequisites

Lecture 16: Sorting

– We could write a version of SelectionSort (or InsertionSort) for each

– Lots of typing, where everything other than the types involved is the same for each one

> This is a key issue – the only difference in the sorts of different types is the data values and how they are compared

> The sorting algorithm is the same– Is there a way we can do this without having to

write the method so many times?– Yes!

> Java Generics> We will discuss this later after we discuss

polymorphism and interfaces

145

Page 146: Lecture 1: Prerequisites

146

Lecture 16: Binary Search

• Consider Sequential Search again– See Slides 124-125 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

Page 147: Lecture 1: Prerequisites

147

Lecture 16: Binary Search

• Idea of Binary Search:4 Searching for a given key, K4 Guess middle item, A[mid] in array

• If A[mid] == K, we found it and are done• If A[mid] < K then K must be on right side of the

array• If A[mid] > K then K must be on left side of the

array– Either way, we eliminate ~1/2 of the remaining

items with one guess– Show on board for a search for 400 1 2 3 4 5 6 710 15 20 35 40 50 60 75

Page 148: Lecture 1: Prerequisites

148

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

Page 149: Lecture 1: Prerequisites

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

149

Page 150: Lecture 1: Prerequisites

150

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

Page 151: Lecture 1: Prerequisites

151

Lecture 17: 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 should be shared amongst

all objects

Page 152: Lecture 1: Prerequisites

152

Lecture 17: 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• Ex: Age for a person – variable or method?

4 Look again PlayList.java and PlayListTest.java

Page 153: Lecture 1: Prerequisites

Lecture 17: 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

153

Page 154: Lecture 1: Prerequisites

Lecture 17: 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

> See ex12b.java and Scores.java154

Page 155: Lecture 1: Prerequisites

Lecture 17: Misc OO Notes

– Deep copies tend to be more difficult to implement than shallow copies, due to the somewhat indefinite number of references that will have to be “followed” for the copy to be made

> Ex: A linked list, which you will see in CS 0445• Neither shallow nor deep is necessarily correct

or incorrect• It depends on the needs for a given class• The important thing is to be AWARE of how your

copies are being made and the implications thereof

155

Page 156: Lecture 1: Prerequisites

Lecture 17: 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 156

Page 157: Lecture 1: Prerequisites

Lecture 17: 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

157

Page 158: Lecture 1: Prerequisites

Lecture 17: Misc OO Notes

– The alternative is to return a copy, delete the original, update the copy, then reinsert it

– This is possible but a lot more work• However, keep in mind that returning

references to the “originals” is more dangerous than returning copies

– If we accidentally modify the object via the returned reference, that will impact the original encompassing object

– It could even invalidate the encompassing object in some cases

> Ex: Maintaining a sorted collection of data> If a reference to an item within the collection is

returned, the value could be changed and the overall collection may no longer be sorted

158

Page 159: Lecture 1: Prerequisites

Lecture 17: 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

159

Page 160: Lecture 1: Prerequisites

Lecture 17: 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

160

Page 161: Lecture 1: Prerequisites

Lecture 17: Misc OO Notes

• The garbage collector runs when needed to deallocate the memory taken up by garbage so that it can be reused

• The details of how it works are very interesting, but beyond the scope of this course

161

Page 162: Lecture 1: Prerequisites

162

Lecture 18: Graphical Interfaces

• So far all of our programs have used4 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-friendly4 Users want to use the mouse (or a finger)4 Users want windows with dialog boxes and

buttons4 Users need maximum guidance with

minimum room for error

Page 163: Lecture 1: Prerequisites

163

Lecture 18: Graphical Interfaces

• Java has all of the tools for us to design and implement complex graphical interfaces4 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 theory4 But once we learn how to do it we will

typically prefer it over console applications

Page 164: Lecture 1: Prerequisites

164

Lecture 18: AWT and Swing

• The AWT (Abstract Windowing Toolkit) was developed for the first versions of Java4 Created components such as Frame,

Panel, Button, TextField, Label• However, the look and feel of the AWT

varied on different windowing systems4 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

Page 165: Lecture 1: Prerequisites

165

Lecture 18: AWT and Swing

• Since a goal of Java is to be platform independent, its look and feel should also be platform independent

• Swing was developed from Java v. 1.2 to be more consistent in its look and feel across all platforms4 It also adds some extra features that did

not exist in the AWT4 Many Swing components are similar to

AWT in name, but with a “J” in front• Ex: JFrame, JPanel, JButton, JTextField, JLabel

Page 166: Lecture 1: Prerequisites

Lecture 18: JavaFX

• JavaFX is a“Set of graphics and media packages that enables developers to design, create, test, debug and deploy rich client applications that operate consistently across diverse platforms”

-- from Oracle JavaFX docs4 As more programming moves toward Web

interfaces, JavaFX will gain in popularity4 Can be used with Swing as well, so

learning Swing is still a good thing

166

Page 167: Lecture 1: Prerequisites

Lecture 18: JavaFX

4 JavaFX is covered in the text, and I encourage you to explore it• However, the text discussion requires a

software download which is not currently in our labs

4 We may discuss JavaFX a bit more later if we have time

4 For now we will focus on Swing• Much of the approach is the same, as we will

discuss

167

Page 168: Lecture 1: Prerequisites

168

Lecture 18: JFrames and JApplets

• JFrames are objects that will be the windows in graphical applications4 We can draw/paint graphics within them4 We can place and manipulate graphical

components within them• JApplets are similar in their

functionality to JFrames4 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

Page 169: Lecture 1: Prerequisites

169

Lecture 18: JFrames

• We will focus on JFrames4 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

Page 170: Lecture 1: Prerequisites

170

Lecture 18: JLabels

• JLabels are simple components to show formatted text on the display4 We can set the font type, size and color4 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 ex15a.java• See the comments to determine how the

various objects are created and set up properly

Page 171: Lecture 1: Prerequisites

171

Lecture 18: 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

Page 172: Lecture 1: Prerequisites

172

Lecture 18: JButtons

• JButtons are simple components that can also show text on the display4 However, in addition to showing text, they

also respond to clicks of the mouse• If a user clicks the mouse within a JButton, an

ActionEvent object is generated in response• This object is passed automatically to an

ActionListener object– The ActionListener must be registered to “listen”

to the JButton– ActionListener is actually an interface with the

single method actionPerformed()> We will discuss interfaces formally soon

Page 173: Lecture 1: Prerequisites

173

Lecture 18: Event-Driven Programming

– Any class that implements actionPerformed() can be an ActionListener

• This causes the actionPerformed method within the ActionListener to execute

– It is the actionPerformed method that is doing the actual response to the button click

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)

Page 174: Lecture 1: Prerequisites

Lecture 18: Event-Driven Programming

174

JButton ActionListener object

public void actionPerformed( ){ // code to execute

}

1) JButton is clicked2) ActionEvent (AE)

generated3) Event passed to

ActionListener4) actionPerformed

executed

Note that because the ActionEvent is passed to the actionPerformed method, the method can get information from the ActionEvent through its accessor methods

AE

Page 175: Lecture 1: Prerequisites

175

Lecture 18: 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

event4 It is important that event handlers are linked

to the appropriate event generators• Otherwise event will still be generated but will not

be responded to• Do example in class

4 See ex15b.java

Page 176: Lecture 1: Prerequisites

Lecture 18: Event-Driven Programming

4 Note that ex15b.java has a single JButton and a single listener• If we have multiple buttons / event generators

we could share listeners amongst them or allocate individual listeners for the generators

• The choice is based on our goals and what we want the program to do

4 See a simple example of this• ex15b2.java

– 2 buttons, one listener• ex15b3.java

– 2 buttons, two listeners

176

Page 177: Lecture 1: Prerequisites

177

Lecture 19: 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 actions4 The setup of this program is very similar to

ex15b.java• Only difference is what the listener is doing

4 See ex15c.java

Page 178: Lecture 1: Prerequisites

178

Lecture 19: Multiple Components

• If we want multiple components, we need to determine how to lay them out4 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-dimensional rectangular grid

Page 179: Lecture 1: Prerequisites

179

Lecture 19: Multiple Components

• Multiple components may also need to interact with each other4 Listener for one component may need to

access the other component• In this case we must allow the listener access

to all components involved -- so it must be different from how we did it in ex15b.java and ex15c.java

• In those programs the listener could access the button that created the event through the getSource() method

• However, other than that the listener is isolated from the variables in the main program

Page 180: Lecture 1: Prerequisites

Lecture 19: Multiple Components

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 by a JButton

• We can use this to process input from a user– For example to change the contents of a JButton

• However, in this case the listener must be able to access both the object that generated the event (the JTextField) and the object it needs to change (the JButton)

– To do this the objects must be set up in a different way so that the variables can be shared

180

Page 181: Lecture 1: Prerequisites

181

Lecture 19: Multiple Components

• Let’s look at another example4 Our JFrame will have a JButton and a

JTextField• The JButton will behave as in ex15b – clicking it

will change the color of the text• The JTextField will allow us to enter new text for

the JButton4 To allow the second option we must set up

our components and listeners in a different manner

4 See ex15d.java

Page 182: Lecture 1: Prerequisites

182

Lecture 19: 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

Page 183: Lecture 1: Prerequisites

183

Lecture 19: 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

Page 184: Lecture 1: Prerequisites

184

Lecture 19: 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

– Use a listener (ex: ActionListener)• See Counters.java

Page 185: Lecture 1: Prerequisites

Lecture 20: 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

185

Page 186: Lecture 1: Prerequisites

Lecture 20: Extending JPanels

4 We will talk about inheritance formally soon

4 For now we just need the basics• When we extend a class in Java, the new class

has all of the functionality of the original, plus any new functionality that we give it via additional instance variables and methods

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

both186

Page 187: Lecture 1: Prerequisites

Lecture 20: Extending JPanels

4 Idea:• A JPanel already encapsulates a component

which can be displayed and can store / manage other components

• By extending it we can encapsulate any other data / methods we would like and give it a new functionality

– We extend it, or add more to what was already there

4 Let’s look at two examples• Counters2.java

– Same functionality as Counters.java, but done via extending JPanel

• JPanelDemo.java and LabelButton.java– Can help with Assignment 4187

Page 188: Lecture 1: Prerequisites

188

Lecture 20: Intro. to Interfaces

• In our graphical examples so far we have used ActionListener objects to handle events4 But ActionListener is not a class4 And we use different classes, all of which we

call ActionListeners4 How can this be?

• ActionListener is an interface• This is different from a class• But what is it and how does it work?

– To really understand interfaces, we need to understand inheritance and polymorphism

– However, for now we will discuss them superficially

Page 189: Lecture 1: Prerequisites

189

Lecture 20: Intro. to Interfaces

• A Java interface is a named set of methods

• However, no method bodies are given – just the headers

• Static constants are allowed, but no instance variables are allowed

• No static methods are allowed (changed in Java 8)

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 class4 A given class can implement any number

of interfaces

Page 190: Lecture 1: Prerequisites

190

Lecture 20: 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()

Page 191: Lecture 1: Prerequisites

191

Lecture 20: Intro. to Interfaces

• Ex:public class Comedian implements Laughable, Booable{ // various methods here (constructor, etc.) public void laugh() {

System.out.println(“Ha ha ha”); } public void boo() {

System.out.println(“You stink!”); }

}• Note that in the class header we must declare that the

interfaces are implemented

Page 192: Lecture 1: Prerequisites

192

Lecture 21: 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

Page 193: Lecture 1: Prerequisites

Lecture 21: Intro. to Interfaces

4 Ex:Laughable L1, L2, L3;L1 = new Comedian();L2 = new SitCom(); // implements LaughableL3 = new Clown(); // implements LaughableL1.laugh(); L2.laugh(); L3.laugh();L1.boo(); // illegal even though Comedian has // the boo() method

((Booable)L1).boo(); // this is ok since we cast

• See ex16.java

4 Interfaces are closely related to inheritance and polymorphism• These are discussed in Chapter 10 of the text• We will revisit interfaces in more detail soon

193

Page 194: Lecture 1: Prerequisites

194

Lecture 21: Wrappers

• Much useful Java functionality relies on classes / objects4 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 way4 If I make an array of Object or any other

class, primitive types cannot be stored in it

Page 195: Lecture 1: Prerequisites

195

Lecture 21: 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);

Page 196: Lecture 1: Prerequisites

196

Lecture 21: Wrappers

4 The wrapper classes also provide extra useful functionality for these types• Ex: Integer.parseInt() is

a static method that enables us to convert from a String into an int

• Ex: Character.isLetter() is a static method that tests if a letter is a character or not

4 See more in API

int

Integer

double

Double

Page 197: Lecture 1: Prerequisites

197

Lecture 21: 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

Page 198: Lecture 1: Prerequisites

198

Lecture 21: 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

Page 199: Lecture 1: Prerequisites

Lecture 21: 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 now see the actual algorithm199

Page 200: Lecture 1: Prerequisites

200

Lecture 21: Parsing Primitive Types

– We know ‘0’ is ASCII 48– So our integer is(49-48)x104 + (50-48)x103 + (51-48)x102

+ (52-48)x101 + (53-48)x100

– This can be done “manually” in a nice efficient way using a simple loop, and is what the parseInt() method does

– Let’s do it ourselves to see how it can be done– Any suggestions on how to start?

• See MyInteger.java and ex17.java

Page 201: Lecture 1: Prerequisites

Lecture 21: 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 well4 See text for a lot of them (ex: split())4 See ex18.java

201

Page 202: Lecture 1: Prerequisites

202

Lecture 22: Inheritance

• Sometimes we want to build a new class that is largely like one we already have4 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 inheritance4 Attributes of a base class, or superclass

are passed on to a subclass

Page 203: Lecture 1: Prerequisites

203

Lecture 22: 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 properties4 Ex: Button “is a” Component

Page 204: Lecture 1: Prerequisites

204

Lecture 22: Inheritance and “is a”

• AbstractButton, JLabel and JPanel are all JComponents4 JButton “is a” AbstractButton

• However, a JComponent is not necessarily an AbstractButton, JLabel or JCheckbox4 “Is a” is a one way relationship

JComponent

AbstractButton JLabel JPanel

is a is ais a

JButton

is a

Page 205: Lecture 1: Prerequisites

205

Lecture 22: 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• We saw this already in Counters2.java, where

our new class extended JPanel

Page 206: Lecture 1: Prerequisites

206

Lecture 22: 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 ex19.java

Page 207: Lecture 1: Prerequisites

207

Lecture 22: Inheritance Example

• As another example4 Compare MixedNumber class and

MixedNumber2 class4 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 ex20.java, RationalNumber.java,

MixedNumber.java and MixedNumber2.java

Page 208: Lecture 1: Prerequisites

208

Lecture 22: Inheritance Exampleint numerator

int denominator--------------

add(), subtract(),multiply(),

divide(), etc.

RationalNumber

int wholeRationalNumber frac

--------------add(), subtract(),

multiply(),divide(), etc.

MixedNumber

add(), subtract(),multiply(),

divide(), etc.

MixedNumber2 extends RationalNumber int numerator

int denominator--------------

add(), subtract(),multiply(),

divide(), etc.

RationalNumber

Composition: MixedNumber class

utilizes a RationalNumber object. Methods in MixedNumber must

manipulate the RationalNumber object as a "client", since it has no

special relationship to RationalNumber

Inheritance: MixedNumber2 class is a RationalNumber, but with

modifications. Ex: The numerator in MixedNumber2

is that defined in RationalNumber. Methods in RationalNumber can be used

directly, and new versions are only needed where the

return type must be MixedNumber2.

Page 209: Lecture 1: Prerequisites

Lecture 23: Method Overriding

• In the previous examples, we used inheritance to4 Add some new functionality / methods

utilizing existing instance variables4 Add some new functionality with

additional instance variables• However, sometimes we want to

extend a class and change some of the things it does4 In this case we may want to keep a

method header the same as it was4 Yet we might want to change its body209

Page 210: Lecture 1: Prerequisites

Lecture 23: Method Overriding

4 Idea:• The subclass type has the same basic structure

as its superclass, but has some different behaviors or different ways of performing identically named tasks

4 Ex:• Consider a simple array list to maintain data in

positional order– Can add or remove an item from an arbitrary

location or just add at the end– Can access or change the value at an existing

location– This is the basic functionality of the predefined

ArrayList class– See MyAList.java

210

Page 211: Lecture 1: Prerequisites

Lecture 23: Method Overriding

• Now consider an array list in which the data must be maintained in some type of sorted order

• What are the differences?– Can no longer add in an arbitrary location

> Must be in the correct sorted order– Can we change the data at a location?

> No? Maybe a way to go> Yes? What should we do in this case

• We could implement this class from scratch but there are a lot of things that MyAList does that we can use

– Same basic data– Same get() method– Same remove(loc) method– Same resize() method211

Page 212: Lecture 1: Prerequisites

Lecture 23: Method Overriding

4 So what we want is• A new class that fundamentally is a MyAList,

but with some differences4 One way we can define this is using

inheritance and method overriding4 Method Overriding

• A method defined in a superclass is redefined in a subclass with an identical method signature

• For subclass objects, the definition in the subclass replaces the version in the superclass

• See SortAList.java and Override.java

212

Page 213: Lecture 1: Prerequisites

213

Lecture 23: Java Class Hierarchy

• In Java, class Object is the base class to all other classes4 If we do not explicitly say extends in a new

class definition, it implicitly extends Object4 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

Page 214: Lecture 1: Prerequisites

214

Lecture 23: Polymorphism

• Idea of polymorphism4 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

Page 215: Lecture 1: Prerequisites

215

Lecture 23: 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

Page 216: Lecture 1: Prerequisites

216

Lecture 23: Method Overloading

• If an exact signature match is not possible, the one that is closest via “widening” of the values is used

– “Widening” means that values of “smaller” types are cast into values of “larger” types

> Ex: int to long int to float float to double– Fewer widenings provides a "closer" match

• If two or more versions of the method are possible with the same amount of “widening”, the call is ambiguous, and a compilation error will result

4 See ex21.java4 Note: This type of polymorphism is not

necessarily object-oriented – can be done in non-object-oriented languages

Page 217: Lecture 1: Prerequisites

217

Lecture 24: Polymorphism

• Subclassing Polymorphism4 Sometimes called “true polymorphism”4 Consists basically of two ideas:1) Method overriding (as previously

discussed)• A method defined in a superclass is redefined

in a subclass with an identical method signature

• Since the signatures are identical, rather than overloading the method, it is instead overriding the method– For subclass objects, the definition in the

subclass replaces the version in the superclass

Page 218: Lecture 1: Prerequisites

218

Lecture 24: Polymorphism

2) Dynamic (or late) binding• The code executed for a method call is

associated with the call during run-time• The actual method executed is determined by

the type of the object, not the type of the reference

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 call for each)

Page 219: Lecture 1: Prerequisites

219

Lecture 24: Polymorphism• Ex. Each subclass overrides the move() method in its own way

Animal [] A = new Animal[3];A[0] = new Bird();A[1] = new Person();A[2] = new Fish();for (int i = 0; i < A.length; i+

+)A[i].move();

move()

move()

move()• References are all the

same, but objects are not• move() method invoked is

that associated with the OBJECT, NOT with the reference

Page 220: Lecture 1: Prerequisites

220

Lecture 24: Object, Method and Instance Variable Access

• When mixing objects of difference classes, some access rules are important to know:4 Superclass references can always be used

to access subclass objects, but NOT vice versaAnimal A = new Bird(); // this is okBird 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• They still exist if defined in a subclass, but they

are not accessible through R

Page 221: Lecture 1: Prerequisites

221

Lecture 24: 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()); // okSystem.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

Page 222: Lecture 1: Prerequisites

222

Lecture 24: Object, Method and Instance Variable Access

• Note that we can access these methods or instance variables INDIRECTLY if an overridden method accesses them

– So, for example, if the move() method as defined in class Fish called the getWaterType() method, and we called

A.move();– It would work fine

• Also note that if we cast a reference to a different type, and the object is not that type (or a subtype), we will get ClassCastException

– If unsure, test using instanceof operator before casting

• See ex22.java for an example

Page 223: Lecture 1: Prerequisites

Lecture 24: Object, Method and Instance Variable Access

• To summarize:• Superclass references CAN BE used to

reference subclass objects• Subclass references CANNOT BE used to

reference superclass objects• The type of the reference determines what data

and methods are ACCESSIBLE• The type of the object determines what data

and methods EXIST– Methods and data initially defined within a

subclass CANNOT BE accessed via a superclass reference

– The type of the object also determines which VERSION of an overridden method is called

223

Page 224: Lecture 1: Prerequisites

224

Lecture 24: Abstract Classes

• Abstract classes4 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 subclasses4 This is an abstract class

• Keyword abstract used in declaration• One or more methods declared to be abstract

and are thus not implemented• No objects may be instantiated

Page 225: Lecture 1: Prerequisites

225

Lecture 24: 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 hierarchy4 See ex23.java

Page 226: Lecture 1: Prerequisites

Lecture 24: Assignment 5 Help

4 We have already discussed using graphical components such as JButtons, JLabels and JPanels

4 We have also used ActionEvents and ActionListeners to allow user interaction

4 Java also allows programmers to draw / render images in a JFrame or a JPanel

4 Java also allows MouseEvents to handle mouse actions and motion• See Mousey.java

226

Page 227: Lecture 1: Prerequisites

Lecture 24: Assignment 5 Help

4 Utilizing MouseEvents, a JPanel, some predefined graphical classes and inheritance, we can write programs to draw / manipulate figures on the screen• See MyRectangle2D.java and DrawDemo.java

4 In Assignment 5 you will extend the Polygon class to enable it to be used in a simple program to draw primitive graphical scenes• See Assig5.java and the MyPoly.java outline

227

Page 228: Lecture 1: Prerequisites

228

Lecture 25: More Interfaces

• Java allows only single inheritance4 A new class can be a subclass of only one

parent (super) class4 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

Page 229: Lecture 1: Prerequisites

229

Lecture 25: More Interfaces

4 We may want to identify an object in multiple ways:• Based on its inherent nature (i.e. its inheritance

chain)– Ex: A Person

• Based on what it is capable of doing– Ex: An athlete– Ex: a pilot

• Recall from previous discussion that we can think of an interface as an "ability"

– Classes that implement an interface have the ability defined by the interface methods

– They can also be identified by this ability

Page 230: Lecture 1: Prerequisites

230

Lecture 25: Interfaces

4 Also recall our previous discussion of polymorphism

• This behavior also applies to interfaces – the interface acts as a superclass and the implementing classes implement the actual methods however they want

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 Laughablefunny[2] = new Clown(); // implements Laughablefor (int i = 0; i < funny.length; i++) funny[i].laugh();

• Same polymorphic behavior we saw with Animal hierarchy

Page 231: Lecture 1: Prerequisites

231

Lecture 25: "Generic" Operations4 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

Page 232: Lecture 1: Prerequisites

232

Lecture 25: “Generic” Operations

4 They all can be compared to each other• So we need some method that invokes this

comparison4 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!

Page 233: Lecture 1: Prerequisites

233

Lecture 25: “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 API4 Consider what we need to know to sort data:

• is A[i] less than, equal to or greater than A[j]4 Thus, we can sort Comparable data

without knowing anything else about it• Awesome! Polymorphism allows this to work

Page 234: Lecture 1: Prerequisites

234

Lecture 25: “Generic” Operations

4 Think of the objects we want to sort as “black boxes”• We know we can compare them because they

implement Comparable• We don’t know (or need to know) anything else

about them– Show on board

4 Thus, a single sort method will work for an array of any Comparable class• Let’s write it now, altering the code we already

know from our simple sort method• See SortAll.java and ex24.java

– Also see SortAllT.java and ex24T.java

Page 235: Lecture 1: Prerequisites

235

Lecture 26: Intro. to Exceptions in Java

• Run-time errors happen4 User enters incorrect input4 Resource is not available (ex. file)4 Logic error (bug) that was not fixed

• For Production software4 Having a program "crash" is a HIGHLY

UNDESIRABLE thing• Users think software is no good• Lose confidence

Page 236: Lecture 1: Prerequisites

236

Lecture 26: Intro. to Exceptions in Java

• Exception:4 An occurrence of an erroneous, unusual or

unexpected event in a program execution4 In older languages

• Code the handling of exceptions into each area of the program that needed it, typically with if statements

• Some exceptions could not even be handled by the HLL

– ex. standard Pascal cannot handle I/O errors or division by 0

> Ask for integer and user enters a text string – what do you do?

> Discuss

Page 237: Lecture 1: Prerequisites

237

Lecture 26: Intro. to Exceptions in Java

4 In newer languages• Exception handling built into the language• We can separate exception handling from the

"main line" code4 Java uses an exception handling model

similar to that used in C++

Exceptions are objects that are thrown … and catchedSome exceptions are built into the languageOthers can be created and thrown by the programmer

Page 238: Lecture 1: Prerequisites

238

Lecture 26: Exceptions in Java

• Java exception handling4 Exceptions are handled using try-catch

blockstry{ // code that will normally execute}catch (ExceptionType1 e){ // code to "handle" this exception}catch (ExceptionType2 e){ // code to "handle" this exception}... // can have many catchesfinally{ // code to "clean up" before leaving try block}

Page 239: Lecture 1: Prerequisites

239

Lecture 26: Exceptions in Java

4 If all goes well (no exceptions occur)• Code in try block is executed, followed by code

in (optional) finally block4 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

Page 240: Lecture 1: Prerequisites

240

Lecture 26: 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• This is dynamic exception propagation• If no handler is ever found

– Console applications crash and report exception

– GUI applications will continue to execute, but may be in an inconsistent state – more soon

Page 241: Lecture 1: Prerequisites

241

Lecture 26: Exceptions in Java

• Checked vs. Unchecked exceptions4 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 and Error

Page 242: Lecture 1: Prerequisites

242

Lecture 26: Exceptions in Java

• Catching exceptions4 Catching a superclass of an exception will

catch subclass exception objectscatch (Exception e)

> "catch all" if no other exceptions match4 Should list exceptions in order of most

specific to most general– If catch above is first NO OTHER catches in the

block could ever execute4 It is better style to be as specific as

possible with the exceptions that are caught• See ex25.java

Page 243: Lecture 1: Prerequisites

243

Lecture 26: Exceptions in GUIs

• GUIs run using multiple execution threads4 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

Page 244: Lecture 1: Prerequisites

244

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 run4 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 ok4 It is best to always try to anticipate and

handle exceptions in GUIs

Page 245: Lecture 1: Prerequisites

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

245

Page 246: Lecture 1: Prerequisites

246

Lecture 27: Recursion

• A Java method can call any other public Java method4 main() is just a method itself, and we have

called other methods from it4 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

Page 247: Lecture 1: Prerequisites

247

Lecture 27: 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: FactorialN! = 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!

Page 248: Lecture 1: Prerequisites

248

Lecture 27: 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 CASE4 What is the base case for factorial?

4 This now allows us to complete our algorithm:

0! = 1

N! = N * (N-1)! when N > 0N! = 1 when N = 0

Page 249: Lecture 1: Prerequisites

249

Lecture 27: 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 made3) The recursive calls must lead eventually to the

base case– Usually by “reducing” the problem size in some

way4 Don’t forget these!

Page 250: Lecture 1: Prerequisites

250

Lecture 27: More Recursion

4 Let’s look at another example:• Calculating an integer power of another integer

MN =• Don’t forget the base case

MN =• The actions we take are slightly different from

factorial, but the basic idea is similar4 Trace this on board

• Note how first call made is last call to complete

• This is important in the implementation of recursion

M * MN-1 N > 0 recursive case

1 N = 0 base case

Page 251: Lecture 1: Prerequisites

251

Lecture 27: Implementing Recursion

• So how do we implement recursion?4 Luckily the computer code is very similar

to the mathematical functions4 Consider factorial below

• Note that the recursive call is made within the return statement

– This is fine – return is done AFTER call completespublic static int fact(int N){

if (N <= 1)return 1;

elsereturn (N * fact(N-1));

}

Page 252: Lecture 1: Prerequisites

252

Lecture 27: 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 method4 Each new activation record is placed on

the top of the run-time stack4 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

Page 253: Lecture 1: Prerequisites

253

Lecture 27: Implementing Recursion

N = 4N <= 1? NOreturn (4 * fact(3)) =

N = 3N <= 1? NOreturn (3 * fact(2)) =

N = 2N <= 1? NOreturn (2 * fact(1)) =

N = 1N <= 1? YESreturn

fact(4)

fact(3)

fact(2)

fact(1)

2

6

24

1

1

2

6

24

Page 254: Lecture 1: Prerequisites

254

Lecture 27: 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 recursion.java4 Also look at many handouts in the text

Page 255: Lecture 1: Prerequisites

Lecture 28: Exam Two

• Same length and general format as Exam One

• Focus on Lectures 15-27• See online review materials and

practice questions

255

Page 256: Lecture 1: Prerequisites

256

Extra Material: File Types

1)Text Files – discussed previously4 Advantage of text files:

• Can read them outside of the program by many different editors or programs

• Easy to create4 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

Page 257: Lecture 1: Prerequisites

257

Extra Material: Binary Files

2) Binary Files4 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

Page 258: Lecture 1: Prerequisites

Extra 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 program4 There are reasons to use both of these

types of files in various applications258

Page 259: Lecture 1: Prerequisites

259

Extra Material: IO Streams

• In Java, file access is provided through a hierarchy of file and stream classes4 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

Page 260: Lecture 1: Prerequisites

260

Extra 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 programs4 The choice depends on the functionality

that we want to wrap around the underlying file• Ex: For text files, PrintWriter is nice since it

allows us to write out strings• Ex: For binary files of primitive types,

DataOutputStream is good since it allows us to write each of the primitive types

Page 261: Lecture 1: Prerequisites

261

Extra Material: Text vs. Binary Files

• We discussed previously that numeric data can often be stored more efficiently in binary form than in text form4 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

Page 262: Lecture 1: Prerequisites

262

Extra Material: Text vs. Binary Files

• Let’s try this and then compare the sizes of the binary and text files4 We will generate a number of random ints

and random doubles4 Store each in a text file and in a binary file

and compare sizes at the end• Note that the size of the integer text file

depends greatly on the values of the integers, while the size of the integer binary file is independent of the values

– If we are storing very small integers, using a text file will actually save us space, but for large integers it will cost us space

• See ex26.java

Page 263: Lecture 1: Prerequisites

Extra Material: Object Streams

• Java has the ability to write entire objects to files in a serialized form4 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 Serializable• See ex27a.java, ex27b.java

263

Page 264: Lecture 1: Prerequisites

264

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

Page 265: Lecture 1: Prerequisites

265

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 language4 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 data structures be effectively

implemented?

Page 266: Lecture 1: Prerequisites

266

Extra Material: Preview of Data Structures

• We also want to understand and utilize programming ideas and techniques utilized in data structure implementation4 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?

Page 267: Lecture 1: Prerequisites

267

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 it4 Java is a very large language with

extensive capabilities4 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?

Page 268: Lecture 1: Prerequisites

268

Extra Material: Preview of Data Structures

• Example: Consider the idea of a List:4 Ordered (by position), indexable collection

of data4 In Java this is an interface – with some

methods as shown:• void add(int index, Object element)

– Add a new object at the specified index• int indexOf(Object o)

– Find the object and return its index• Object get(int index)

– Return the object at the specified index• Object remove(int index)

– Remove (and return) the object at the specified index

Page 269: Lecture 1: Prerequisites

269

Extra Material: Preview of Data Structures

• We can implement a List in different ways4 ArrayList

• Use an array as the underlying data structure• You are already familiar with this

4 LinkedList• Use a linked list of nodes as the underlying data

structure– See singly linked list below– Actual Java implementation is a doubly linked list

> More details in CS 0445!

Head

Page 270: Lecture 1: Prerequisites

270

Extra Material: Preview of Data Structures

4 Each implementation has advantages and disadvantages• Ex: Advantage of ArrayList

– get(i) can be done in one step, since we just go to that index in the array

– In a LinkedList we must follow references down the list

• Ex: Advantage of LinkedList– add(0, obj) requires only creating a new object

and linking it correctly to front of list– In an ArrayList we must shift all of the items

from 0 down a spot in order to make "room" at index 0

Page 271: Lecture 1: Prerequisites

271

Extra Material: Preview of Data Structures

• Queue and Stack4 Two fundamental data structures used

through computer programming4 Queue:

• Data managed First In First Out (FIFO)4 Stack

• Data managed Last In First Out (LIFO)4 Manipulation in other ways is not (or

should not be) allowed• Using data abstraction and encapsulation we

can implement these nicely

Page 272: Lecture 1: Prerequisites

272

Extra Material: Preview of Data Structures

4 In CS 0445 you will see these and other implementation ideas in detail

4 Ex: See ex28.java• Note that the showList method works for all of

the objects, using the Collection interface• However, the underlying objects are different

and give different functionalities and efficiencies

– More in CS 0445!