SlideShare a Scribd company logo
Lecture 1
Introduction to
Java
What is a Computer
Program?
 For a computer to be able to do anything
(multiply, play a song, run a word processor),
it must be given the instructions to do so.
 A program is a set of instructions written by
humans for computers to perform tasks.
 The instructions are written in programming
languages such as C, C++, Java, etc.
Recipe Analogy
Comparing a computer program to a food recipe
Food Recipe
 a chef writes a set of
instructions called a recipe
 the recipe requires
specific ingredients
 the cook follows the
instruction step-by-step
 the food will vary
depending on the amount
of ingredients and the cook
Computer Program
 a programmer writes a set
of instructions called a
program
 the program requires
specific inputs
 the computer follows the
instructions step-by-step
 the output will vary
depending on the values of
the inputs and the computer
Compiling Programs
 Computers do not understand the languages
(C++, Java, etc) that programs are written in.
 Programs must first be compiled (converted)
into machine code that the computer can run.
 A compiler is a program that translates a
programming language into machine code.
Running Programs
 All programs follow a simple format:
Input Execution Output
 Inputs can be from users, files, or
other computer programs
 Outputs can take on many forms:
numbers, text, graphics, sound, or
commands to other programs
Multiple Compilers
 Because different operating systems (Windows, Macs,
Unix) require different machine code, you must compile
most programming languages separately for each platform.
program
compiler
compiler
compiler
Win
MAC
Unix
 Java is a little different.
 Java compiler produces bytecode not
machine code.
 Bytecode can be run on any computer
with the Java interpreter installed.
Java Program
compiler
Java Bytecode
Win
MAC
Unix
Interpreter
Java Interpreter
Advantages and Disadvantages
of Java
Advantages:
 Java is platform independent. Once it's compiled, you can run
the bytecode on any machine with a Java interpreter. You do not
have to recompile for each platform.
 Java is safe. Certain common programming bugs and dangerous
operations are prevented by the language and compiler.
 Java standardizes many useful operations like managing
network connections and providing graphical user interfaces.
Disadvantages:
 Running bytecode through the interpreter is not as fast as
running machine code, which is specific to that platform.
 Because it is platform independent, it is difficult to use platform
specific features (e.g., Windows taskbar, quick launch) in Java.
 Java interpreter must be installed on the computer in order to run
Java programs.
Your First Java Program
 Open your text-editor and type the following piece
of Java code exactly:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
 Save this file as HelloWorld.java (watch
capitalization) in the following directory:
c:java
Compiling and Running
Your First Program
 Open the command prompt in Windows
 To run the program that you just wrote, type at the command
prompt:
cd c:java
 Your command prompt should now look like this:
c:java>
 To compile the program that you wrote, you need to run the Java
Development Tool Kit Compiler as follows:
At the command prompt type:
c:java> javac HelloWorld.java
 You have now created your first compiled Java program named
HelloWorld.class
 To run your first program, type the following at the command
prompt:
c:java>java HelloWorld
Although the file name includes the .class extension , this part of the name must be
left off when running the program with the Java interpreter.
You’ve created your
first
Java program!
Object-Oriented
Programming
 Java is an object-oriented
programming language
 For the rest of this lecture, we’ll
introduce you to the basic principles
of object-oriented programming.
 We won’t be using these principles
immediately, but they will become
important over the next few weeks.
OOP Concepts
 In object-oriented programming (OOP),
programs are organized into objects
 The properties of objects are
determined by their class
 Objects act on each other by passing
messages
Object
 Definition: An object is a software
bundle that has State and Behavior.
 Software Objects are often used to
model real-world objects.
 Example: dogs have states (name,
color, hungry, breed) and behaviors
(bark, fetch, and wag tail).
Object Examples
 Example 1: Dogs
 States: name, color, breed, and “is
hungry?”
 Behaviors: bark, run, and wag tail
 Example 2: Cars
 States: color, model, speed, direction
 Behaviors: accelerate, turn, change gears
Class
 Definition: A class is a blueprint that defines the
states and the behaviors common to all objects of
a certain kind.
 In the real world, you often have many objects of
the same kind. For example, a guard dog, herding
dog, snoop dog . . .
 Even though all dogs have four legs, and bark,
each dog’s behavior is independent of other dogs.
 For example: Dog #1 is a black Poodle, Dog #2 is
a red Irish Setter
Message
 Definition: Software objects interact and
communicate with each other by sending
messages to each other.
 Example: when you want your dog to
gather a herd of goats, you whistle and
send him out.
Summary of OOP
 When writing an object-oriented program, we
define classes, which describe categories of
objects, and the states and behaviors that they
have in common.
 We then create objects which belong to classes,
and share the common features of their class.
 Objects interact with each other by passing
messages.
 You will be creating your own classes and
objects soon!
Lecture 2
Variables and Primitive
Data Types
What is a Variable?
 Variables are places where information
can be stored while a program is
running.
 Their values can be changed at any
point over the course of a program
Creating Variables
 To create a variable, declare its name and
the type of information that it will store.
 The type is listed first, followed by the name.
 Example: a variable that stores an integer
representing the highest score on an exam
could be declared as follows:
int highScore ;
type name
Creating Variables (continued)
 Now you have the variable (highScore),
you will want to assign a value to it.
 Example: the highest score in the class
exam is 98.
highScore = 98;
 Examples of other types of variables:
String studentName;
boolean gameOver;
Naming Variables
 The name that you choose for a variable is
called an identifier. In Java, an identifier can
be of any length, but must start with:
a letter (a – z),
a dollar sign ($),
or, an underscore ( _ ).
 The rest of the identifier can include any
character except those used as operators in
Java such as + , - , * .
 In addition, there are certain keywords reserved
(e.g., "class") in the Java language which can
never be used as identifiers.
 Java is a case-sensitive language – the
capitalization of letters in identifiers matters.
A rose is not a Rose is not a ROSE
 It is good practice to select variable names that
give a good indication of the sort of data they
hold
 For example, if you want to record the size of a hat,
hatSize is a good choice for a name whereas qqq
would be a bad choice
Naming (Continued)
 When naming a variable, the following
convention is commonly used:
 The first letter of a variable name is lowercase
 Each successive word in the variable name begins
with a capital letter
 All other letters are lowercase
 Here are some examples:
pageCount
loadFile
anyString
threeWordVariable
POP QUIZ
 Which of the following are valid variable
names?
1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#
Statements
 A statement is a command that causes
something to happen.
 All statements in Java are separated by
semicolons ;
 Example:
System.out.println(“Hello, World”);
 You have already used statements to
create a variable and assign it a value.
Variables and Statements
 One way is to declare a variable and then
assign a value to it with two statements:
int e; // declaring a variable
e = 5; // assigning a value to a variable
 Another way is to write a single
initialization statement:
int e = 5; // declaring AND assigning
Java is a Strongly-Typed
Language
 All variables must be declared with a data
type before they are used.
 Each variable's declared type does not
change over the course of the program.
 Certain operations are only allowed with
certain data types.
 If you try to perform an operation on an
illegal data type (like multiplying Strings),
the compiler will report an error.
Primitive Data Types
 There are eight built-in (primitive) data
types in the Java language
 4 integer types (byte, short, int, long)
 2 floating point types (float, double)
 Boolean (boolean)
 Character (char)
**see Appendix II: Summary of Primitive Data Types for a
complete table of sizes and formats**
Integer Data Types
 There are four data types that can be used
to store integers.
 The one you choose to use depends on the
size of the number that we want to store.
 In this course, we will always use int when
dealing with integers.
Data Type Value Range
byte -128 to +127
short -32768 to +32767
int -2147483648 to +2147483647
long -9223372036854775808 to
+9223372036854775807
 Here are some examples of when you would
want to use integer types:
- byte smallValue;
smallValue = -55;
- int pageCount = 1250;
- long bigValue = 1823337144562L;
Note: By adding an L to the end of the value in the last
example, the program is “forced” to consider the value
to be of a type long even if it was small enough to be
an int
Floating Point Data Types
 There are two data types that can be used
to store decimal values (real numbers).
 The one you choose to use depends on the
size of the number that we want to store.
 In this course, we will always use double
when dealing with decimal values.
Data Type Value Range
float 1.4×10-45 to 3.4×1038
double 4.9×10-324 to 1.7×10308
 Here are some examples of when you
would want to use floating point types:
 double g = 7.7e100 ;
 double tinyNumber = 5.82e-203;
 float costOfBook = 49.99F;
 Note: In the last example we added an F
to the end of the value. Without the F, it
would have automatically been considered
a double instead.
Boolean Data Type
 Boolean is a data type that can be
used in situations where there are
two options, either true or
false.
 Example:
boolean monsterHungry = true;
boolean fileOpen = false;
Character Data Types
 Character is a data type that can be used to
store a single characters such as a letter,
number, punctuation mark, or other symbol.
 Example:
 char firstLetterOfName = 'e' ;
 char myQuestion = '?' ;
 Note that you need to use singular quotation
marks when assigning char data types.
Introduction to Strings
 Strings consist of a series of characters inside
double quotation marks.
 Examples statements assign String variables:
String coAuthor = "John Smith";
String password = "swordfish786";
 Strings are not one of the primitive data types,
although they are very commonly used.
 Strings are constant; their values cannot be
changed after they are created.
POP QUIZ
What data types would you use to store
the following types of information?:
1)Population of Ethiopia
2)Approximation of π
3)Open/closed status of a file
4)Your name
5)First letter of your name
6)$237.66
int
double
boolean
String
char
double
Appendix I: Reserved Words
The following keywords are reserved in the Java
language. They can never be used as identifiers:
abstract assert boolean break byte
case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceo
f
int interfac
e
long native new
package private protected public return
short static strictfp super switch
synchronize
d
this throw throws transient
try void violate while
Appendix II: Primitive Data Types
The following tables show all of the primitive
data types along with their sizes and formats:
Data Type Description
byte Variables of this kind can have a value from:
-128 to +127 and occupy 8 bits in memory
short Variables of this kind can have a value from:
-32768 to +32767 and occupy 16 bits in memory
int Variables of this kind can have a value from:
-2147483648 to +2147483647 and occupy 32 bits in memory
long Variables of this kind can have a value from:
-9223372036854775808 to +9223372036854775807 and occupy
64 bits in memory
Integers
Appendix II: Primitive Data Types
(cont)
Data Type Description
float Variables of this kind can have a value from:
1.4e(-45) to 3.4e(+38)
double Variables of this kind can have a value from:
4.9e(-324) to 1.7e(+308)
Real Numbers
char Variables of this kind can have a value from:
A single character
boolean Variables of this kind can have a value from:
True or False
Other Primitive Data Types
Lecture 3
Operators
What are Operators?
• Operators are special symbols used for
– mathematical functions
– assignment statements
– logical comparisons
• Examples:
3 + 5 // uses + operator
14 + 5 – 4 * (5 – 3) // uses +, -, * operators
• Expressions can be combinations of variables, primitives
and operators that result in a value
 There are 5 different groups of operators:
 Arithmetic operators
 Assignment operator
 Increment/Decrement operators
 Relational operators
 Conditional operators
The Operator Groups
Arithmetic Operators
 Java has 6 basic arithmetic operators
+ add
- subtract
* multiply
/ divide
% modulo (remainder)
^ exponent (to the power of)
 Order of operations (or precedence) when
evaluating an expression is the same as you
learned in school (PEMDAS).
Order of Operations
 Example: 10 + 15 / 5;
 The result is different depending on whether the
addition or division is performed first
(10 + 15) / 5 = 5
10 + (15 / 5) = 13
Without parentheses, Java will choose the
second case
 Note: you should be explicit and use
parentheses to avoid confusion
Integer Division
 In the previous example, we were
lucky that (10 + 15) / 5 gives an
exact integer answer (5).
 But what if we divide 63 by 35?
 Depending on the data types of the
variables that store the numbers,
we will get different results.
Integer Division Example
 int i = 63;
int j = 35;
System.out.println(i / j);
Output: 1
 double x = 63;
double y = 35;
System.out.println(x / y);
Ouput: 1.8
 The result of integer division is just
the integer part of the quotient!
Assignment Operator
 The basic assignment operator (=)
assigns the value of var to expr
var = expr ;
 Java allows you to combine arithmetic
and assignment operators into a single
operator.
 Examples:
x = x + 5; is equivalent to x +=
5;
y = y * 7; is equivalent to y *=
7;
Increment/Decrement Operators
count = count + 1;
can be written as:
++count; or count++;
++ is called the increment operator.
count = count - 1;
can be written as:
--count; or count--;
-- is called the decrement operator.
The increment/decrement operator has two forms:
 The prefix form ++count, --count
first adds 1 to the variable and then continues to any other
operator in the expression
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6
 The postfix form count++, count--
first evaluates the expression and then adds 1 to the variable
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15
numOranges has value 6
Relational (Comparison)
Operators
operation is true when . . .
a > b a is greater than b
a >= b a is greater than or equal to b
a == b a is equal to b
a != b a is not equal to b
a <= b a is less than or equal to b
a < b a is less than b
• Relational operators compare two values
• Produces a boolean value (true or false)
depending on the relationship
int x = 3;
int y = 5;
boolean result;
1) result = (x > y);
now result is assigned the value false because
3 is not greater than 5
2) result = (15 == x*y);
now result is assigned the value true because the product of
3 and 5 equals 15
3) result = (x != x*y);
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
Examples of Relational Operations
Conditional Operators
Symbol Name
&& AND
|| OR
! NOT
 Conditional operators can be referred to as boolean
operators, because they are only used to combine
expressions that have a value of true or false.
Truth Table for Conditional
Operators
x y x && y x || y !x
True True True True False
True False False True False
False True False True True
False False False False True
boolean x = true;
boolean y = false;
boolean result;
1. Let result = (x && y);
now result is assigned the value false
(see truth table!)
2. Let result = ((x || y) && x);
(x || y) evaluates to true
(true && x) evaluates to true
now result is assigned the value true
Examples of Conditional Operators
 Examples:
(a && (b++ > 3))
(x || y)
 Java will evaluate these expressions from
left to right and so will evaluate
a before (b++ > 3)
x before y
 Java performs short-circuit evaluation:
it evaluates && and || expressions from left
to right and once it finds the result, it stops.
Using && and ||
Short-Circuit Evaluations
(a && (b++ > 3))
What happens if a is false?
 Java will not evaluate the right-hand expression (b++
> 3) if the left-hand operator a is false, since the
result is already determined in this case to be false.
This means b will not be incremented!
(x || y)
What happens if x is true?
 Similarly, Java will not evaluate the right-hand operator
y if the left-hand operator x is true, since the result is
already determined in this case to be true.
POP QUIZ
1) What is the value of number?
int number = 5 * 3 – 3 / 6 – 9 * 3;
2) What is the value of result?
int x = 8;
int y = 2;
boolean result = (15 == x * y);
3) What is the value of result?
boolean x = 7;
boolean result = (x < 8) && (x > 4);
4) What is the value of numCars?
int numBlueCars = 5;
int numGreenCars = 10;
int numCars = numGreenCars++ + numBlueCars + ++numGreeenCars;
-12
false
true
27
References
 Summary of Java operators
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/opsummary.html
 Order of Operations (PEMDAS)
1. Parentheses
2. Exponents
3. Multiplication and Division from left to right
4. Addition and Subtraction from left to right
Lecture 4
Control Structures
Program Flow
 Java will execute the
statements in your code in a
specific sequence, or "flow".
 The "flow" of the program
and can be described
through a "flow diagram":
a more sophisticated program
a simple program
statement
statement
statement
statement
statement
statement
statement statement
statement
statement
What are Control
Structures?
 Control structures alter the flow of the
program, the sequence of statements that
are executed in a program.
 They act as "direction signals" to control
the path a program takes.
 Two types of control structures in Java:
 decision statements
 loops
Decision Statements
 A decision statement allows the
code to execute a statement or
block of statements conditionally.
 Two types of decisions statements
in Java:
 if statements
 switch statements
If Statement
if (expression) {
statement;
}
rest_of_program;
 expression must evaluate to a boolean value, either
true or false
 If expression is true, statement is executed and
then rest_of_program
 If expression is false, statement is not executed
and the program continues at rest_of_program
If Statement Flow
Diagram
The if decision statement executes
a statement if an expression is true
execute
statement
execute
rest_of_program
Is expression
true?
yes
no
if (expression) {
statement1;
}
rest_of_program
If-Else Statement
if (expression) {
statement1;
}
else{
statement2;
}
next_statement;
 Again, expression must produce a boolean value
 If expression is true, statement1 is executed and
then next_statement is executed.
 If expression is false, statement2 is executed and
then next_statement is executed.
If-Else Flow Diagram
if (expression){
statement1;
} else {
statement2;
}
rest_of_program
The if-else decision
statement executes a
statement if an expression
is true and a different
statement if it is not true.
is
“expression”
true?
execute
statement1
execute
rest_of_program
no
yes
execute
statement2
Chained If-Else
Statements
if (grade == 'A')
System.out.println("You got an A.");
else if (grade == 'B')
System.out.println("You got a B.");
else if (grade == 'C')
System.out.println("You got a C.");
else
System.out.println("You got an F.");
Switch Statements
 The switch statement enables you to test several cases
generated by a given expression.
 For example:
switch (expression) {
case value1:
statement1;
case value2:
statement2;
default:
default_statement;
}
Every statement after the true case is executed
 The expression must evaluate to a char, byte, short
or int, but not long, float, or double.
y
y
n
n
switch (expression){
case value1:
// Do value1 thing
case value2:
// Do value2 thing
...
default:
// Do default action
}
// Continue the program
expression
equals
value1?
Do value1 thing
Do value2 thing
Do default action
expression
equals
value2?
Continue the
program
Break Statements in Switch
Statements
 The break statement tells the computer to exit
the switch statement
 For example:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
default:
default_statement;
break;
}
switch (expression){
case value1:
// Do value1 thing
break;
case value2:
// Do value2 thing
break;
...
default:
// Do default action
break;
}
// Continue the program
expression
equals
value1?
expression
equals
value2?
do default action
Do value1 thing
Do value2 thing
break
break
break
Continue the
program
y
y
n
n
Remember the Chained If-Else .
. .
if (grade == 'A')
System.out.println("You got an A.");
else if (grade == 'B')
System.out.println("You got a B.");
else if (grade == 'C')
System.out.println("You got a C.");
else
System.out.println("You got an F.");
 This is how it is accomplished with a switch:
 if-else chains can be sometimes be rewritten
as a “switch” statement.
 switches are usually simpler and faster
switch (grade) {
case 'A':
System.out.println("You got an A.");
break;
case 'B':
System.out.println("You got a B.");
break;
case 'C':
System.out.println("You got a C.");
break;
default:
System.out.println("You got an F.");
}
Loops
 A loop allows you to execute a statement or
block of statements repeatedly.
 Three types of loops in Java:
1. while loops
2. for loops
3. do-while loops (not discussed in this course)
The while Loop
while (expression){
statement
}
 This while loop executes as long as the given logical
expression between parentheses is true. When
expression is false, execution continues with the
statement following the loop block.
 The expression is tested at the beginning of the loop, so
if it is initially false, the loop will not be executed at all.
 For example:
int sum = 0;
int i = 1;
while (i <= 10){
sum += i;
i++;
}
 What is the value of sum?
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
The for Loop
The control of the for loop appear in parentheses and is made up of
three parts:
1. The first part, the init_expression,sets the initial
conditions for the loop and is executed before the loop starts.
2. Loop executes so long as the loop_condition is true and
exits otherwise.
3. The third part of the control information, the
increment_expr, is usually used to increment the loop
counter. This is executed at the end of each loop iteration.
for (init_expr; loop_condition; increment_expr) {
statement;
}
 For example:
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
 What is the value of sum?
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
 Example 3:
for(int div = 0; div < 1000; div++){
if(div % 2 == 0) {
System.out.println("even: " + div);
} else {
System.out.println("odd: " + div);
}
}
 What will this for loop do?
prints out each integer from 0 to 999,
correctly labeling them even or odd
 If there is more than one variable to set up or
increment they are separated by a comma.
for(i=0, j=0; i*j < 100; i++, j+=2) {
System.out.println(i * j);
}
 You do not have to fill all three control expressions
but you must still have two semicolons.
int n = 0;
for(; n <= 100;) {
System.out.println(++n);
}
The while loop
Test condition
is true?
Execute loop
statement(?)
Next statement
y
n
Initialize count
Test condition
is true?
Execute loop
statement(s)
Increment
count
New statement
The for loop
y
n
The continue Statement
 The continue statement causes the program
to jump to the next iteration of the loop.
/**
* prints out "5689"
*/
for(int m = 5; m < 10; m++) {
if(m == 7) {
continue;
}
System.out.print(m);
}
 Another continue example:
int sum = 0;
for(int i = 1; i <= 10; i++){
if(i % 3 == 0) {
continue;
}
sum += i;
}
 What is the value of sum?
1 + 2 + 4 + 5 + 7 + 8 + 10 = 37
The break Statement
 We have seen the use of the break
statement in the switch statement.
 You can also use the break statement to exit
the loop entirely.
// prints out numbers unless
// num is ever exactly 400
while (num > 6) {
if(num == 400) {
break;
}
System.out.println(num);
num -= 8;
}
Nested Loops
 You can nest loops of any kind one inside
another to any depth. What does this print?
for(int i = 10; i > 0; i--) {
if (i > 7) {
continue;
}
while (i > 3) {
if(i == 5) {
break;
}
System.out.println(--i);
}
System.out.println(i);
}
6
5
5
4
3
2
1
POP QUIZ
1. In the switch statement, which types can
expression evaluate to?
2. What must be used to separate each
section of a for statement.
3. Which statement causes a program to
skip to the next iteration of a loop.
4. Write a for loop that outputs 100-1 in
reverse sequence.
5. Write a for loop that outputs all numbers
that are divisible by 3 between 0-50.
char, byte, short, int
semicolons
continue
Lecture 5
Arrays
A way to organize data
What are Arrays?
 An array is a series of compartments to store
data.
 Each compartment is appropriately sized for
the particular data type the array is declared
to store.
 An array can hold only one type of data!
E.g. int[] can hold only integers
char[] can hold only characters
Array Visualization
primes[0]
int[] primes = new int[10];
Specifies an array of
variables of type int
// An array of 10 integers
index values
We are creating
a new array object
The name of
the array
The array object is of
type int
and has ten elements
primes[1] primes[2] primes[3] primes[4] primes[9]
Declaring an Array Variable
 Array declarations use square brackets.
datatype[] label;
 For example:
int[] prices;
String[] names;
Creating a New "Empty"
Array
Use this syntax: new int[20]
 The new keyword creates an array of type
int that has 20 compartments
 The new array can then be assigned to an
array variable:
int[] prices = new int[20];
 When first created as above, the items in the
array are initialized to the zero value of the
datatype
int: 0 double: 0.0 String: null
Array Indexes
 Every compartment in an array is assigned an
integer reference.
 This number is called the index of the
compartment
 Important: In Java (and most other languages),
the index starts from 0 and ends at n-1, where n
is the size of the array
Accessing Array Elements
 To access an item in an array, type
the name of the array followed by
the item’s index in square brackets.
 For example, the expression:
names[0]
will return the first element in the
names array
Filling an Array
 Assign values to compartments:
prices[0] = 6.75;
prices[1] = 80.43;
prices[2] = 10.02;
Constructing Arrays
 To construct an array, you can declare a
new empty array and then assign values
to each of the compartments:
String[] names = new String[5];
names[0] = "David";
names[1] = "Qian";
names[2] = "Emina";
names[3] = "Jamal";
names[4] = "Ashenafi";
Another Way to Construct
Arrays
 You can also specify all of the items in an
array at its creation.
 Use curly brackets to surround the array’s
data and separate the values with commas:
String[] names = { "David", "Qian",
"Emina", "Jamal", "Ashenafi"};
 Note that all the items must be of the same
type. Here they are of type String.
 Another example:
int[] powers = {0, 1, 10, 100};
Length of array
String[] names = {
"David", "Qian", "Emina",
"Jamal", "Ashenafi" };
int numberOfNames = names.length;
System.out.println(numberOfNames);
Output: 5
 Important: Arrays are always of the
same size: their lengths cannot be
changed once they are created!
Example
String[] names = {
"Aisha", "Tamara", "Gikandi", "Ato", "Lauri"};
for(int i = 0; i < names.length; i++){
System.out.println("Hello " + names[i] + ".");
}
Output:
Hello Aisha.
Hello Tamara.
Hello Gikandi.
Hello Ato.
Hello Lauri.
Modifying Array Elements
 Example:
names[0] = “Bekele"
 Now the first name in names[] has been
changed from "Aisha" to "Bekele".
 So the expression names[0] now evaluates to
"Bekele".
 Note: The values of compartments can change,
but no new compartments may be added.
Example
int[] fibs = new int[10];
fibs[0] = 1;
fibs[1] = 1;
for(int i = 2; i < fibs.length; i++) {
fibs[i] = fibs[i-2] + fibs[i-1];
}
 After running this code, the array fibs[]
contains the first ten Fibonacci numbers:
1 1 2 3 5 8 13 21 34 55
Note: array indexes can be expressions
Exercise 1
 Which of the following sequences of
statements does not create a new array?
a. int[] arr = new int[4];
b. int[] arr;
arr = new int[4];
c. int[] arr = { 1, 2, 3, 4};
d. int[] arr; just declares an array variable
Exercise 2
 Given this code fragment,
int[] data = new int[10];
System.out.println(data[j]);
 Which of the following is a legal value of j?
a. -1
b. 0
c. 3.5
d. 10
// out of range
// legal value
// out of range
// out of range
Exercise 3
 Which set of data would not be
suitable for storing in an array?
a. the score for each of the four
quarters of a Football match
b. your name, date of birth, and score
on your physics test
c. temperature readings taken every
hour throughout a day
d. your expenses each month for an
entire year
// these are different types
Exercise 4
 What is the value of c after the following
code segment?
int [] a = {1, 2, 3, 4, 5};
int [] b = {11, 12, 13};
int [] c = new int[4];
for (int j = 0; j < 3; j++) {
c[j] = a[j] + b[j];
}
c = [12, 14, 16, 0]
2-Dimensional Arrays
 The arrays we've used so far can be
thought of as a single row of values.
 A 2-dimensional array can be thought
of as a grid (or matrix) of values
 Each element of the 2-D array is
accessed by providing two indexes:
a row index and a column index
 (A 2-D array is actually just an array of arrays)
0 1
0 8 4
1 9 7
2 3 6
value at row index 2,
column index 0 is 3
2-D Array Example
 Example:
A landscape grid of a 20 x 55 acre piece of land:
We want to store the height of the land at each
row and each column of the grid.
 We declare a 2D array two sets of square brackets:
double[][] heights = new double[20][55];
 This 2D array has 20 rows and 55 columns
 To access the acre at row index 11 and column index
23 user: heights[11][23]
MIT-AITI 2003
Lecture 6
Methods
Methods
 Methods also known as functions or procedures.
 Methods are a way of capturing a sequence of
computational steps into a reusable unit.
 Methods can accept inputs in the form of
arguments, perform some operations with the
arguments, and then can return a value the is the
output, or result of their computations.
The Concept of a Method
method
inputs outputs
 Square root is a good example of a method.
 The square root method accepts a single number as an
argument and returns the square root of that number.
 The computation of square roots involves many
intermediate steps between input and output.
 When we use square root, we don’t care about these
steps. All we need is to get the correct output.
 Hiding the internal workings of a method from a user but
providing the correct answer is known as abstraction
Square Root Method
 A method has 4 parts: the return type, the
name, the arguments, and the body:
double sqrt(double num) {
// a set of operations that compute
// the square root of a number
}
 The type, name and arguments together is
referred to as the signature of the method
Declaring Methods
type name arguments
body
The Return Type of a
Method
 The return type of a method may be
any data type.
 The type of a method designates the
data type of the output it produces.
 Methods can also return nothing in
which case they are declared void.
Return
Statements
 The return statement is used in a method to output
the result of the methods computation.
 It has the form: return expression_value;
 The type of the expression_value must be the
same as the type of the method:
double sqrt(double num){
double answer;
// Compute the square root of num and store
// the value into the variable answer
return answer;
}
Return Statements
 A method exits immediately after it
executes the return statement
 Therefore, the return statement is
usually the last statement in a method
 A method may have multiple return
statements. Can you think of an
example of such a case?
Brain Teaser Answer
 Example:
int absoluteValue (int num){
if (num < 0)
return –num;
else
return num;
}
void Methods
 A method of type void has a return statement
without any specified value. i.e. return;
 This may seem useless, but in practice void is
used often.
 A good example is when a methods only
purpose is to print to the screen.
 If no return statement is used in a method of type
void, it automatically returns at the end
Method Arguments
 Methods can take input in the form of
arguments.
 Arguments are used as variables inside the
method body.
 Like variables, arguments, must have their
type specified.
 Arguments are specified inside the paren-
theses that follow the name of the method.
 Here is an example of a method that
divides two doubles:
double divide(double a, double b) {
double answer;
answer = a / b;
return answer;
}
Example
Method
Method Arguments
 Multiple method arguments are
separated by commas:
double pow(double x, double y)
 Arguments may be of different types
int indexOf(String str, int fromIndex)
The Method Body
 The body of a method is a block
specified by curly brackets. The body
defines the actions of the method.
 The method arguments can be used
anywhere inside of the body.
 All methods must have curly brackets
to specify the body even if the body
contains only one or no statement.
Invoking Methods
 To call a method, specify the name of
the method followed by a list of comma
separated arguments in parentheses:
pow(2, 10); //Computes 210
 If the method has no arguments, you
still need to follow the method name
with empty parentheses:
size();
Static Methods
 Some methods have the keyword
static before the return type:
static double divide(double a, double b) {
return a / b;
}
 We'll learn what it means for a method to
be static in a later lecture
 For now, all the methods we write in lab
will be static.
main - A Special
Method
 The only method that we have used in lab up
until this point is the main method.
 The main method is where a Java program
always starts when you run a class file with
the java command
 The main method is static has a strict
signature which must be followed:
public static void main(String[] args) {
. . .
}
main
continued
class SayHi {
public static void main(String[] args) {
System.out.println("Hi, " + args[0]);
}
}
 When java Program arg1 arg2 … argN is typed on
the command line, anything after the name of the class file
is automatically entered into the args array:
java SayHi Sonia
 In this example args[0] will contain the String "Sonia",
and the output of the program will be "Hi, Sonia".
class Greetings {
public static void main(String args[]) {
String greeting = "";
for (int i=0; i < args.length; i++) {
greeting += "Jambo " + args[i] + "! ";
}
System.out.println(greeting);
}
}
 After compiling, if you type
java Greetings Alice Bob Charlie
prints out "Jambo Alice! Jambo Bob! Jambo Charlie!"
Example main method
class Factorial {
public static void main (String[] args) {
int num = Integer.parseInt(args[0]));
System.out.println(fact(num));
}
static int fact(int n) {
if (n <= 1) return 1;
else return n * fact(n – 1);
}
}
 After compiling, if you type java Factorial 4
the program will print out 24
Recursive Example
class Max {
public static void main(String args[]) {
if (args.length == 0) return;
int max = Integer.parseInt(args[0]);
for (int i=1; i < args.length; i++) {
if (Integer.parseInt(args[i]) > max) {
max = Integer.parseInt(args[i]);
}
}
System.out.println(max);
}
}
 After compiling, if you type java Max 3 2 9 2 4
the program will print out 9
Another Example
Summary
 Methods capture a piece of computation we wish to
perform repeatedly into a single abstraction
 Methods in Java have 4 parts: return type, name,
arguments, body.
 The return type and arguments may be either
primitive data types or complex data types (Objects)
 main is a special Java method which the java
interpreter looks for when you try to run a class file
 main has a strict signature that must be followed:
public static void main(String args[])
Lecture 7
Classes and Objects - Part I
What is an Object?
 An Object has two primary components:
 state – properties of the object
 behavior – operations the object can perform
 Examples
object state behavior
dog breed, isHungry eat, bark
grade book grades mean, median
light on/off switch
Objects in Java
 A class defines a new type of Object
 To create a Object type to represent a
light switch . . .
class LightSwitch {
// state and behavior here
}
Fields
 An Object's state is stored in variables
called fields
 Fields are declared (and optionally
initialized) inside the braces of the class
 Light switch example with a field . . .
class LightSwitch {
boolean on = true;
}
Methods
 An Object's behavior is defined by its
methods
 Methods, like fields, are written inside the
braces of the class
 Methods can access the fields (the state)
of their object and can change them
Light Switch Example
class LightSwitch {
boolean on = true; // field
boolean isOn() { // returns
return on; // the state
}
void switch() { // changes
on = !on; // the state
}
}
Constructing Objects
 We use the new keyword to construct a
new instance of an Object
 We can assign this instance to a variable
with the same type of the Object
 Note: classes define new datatypes !
LightSwitch ls = new LightSwitch();
LightSwitch ls = new LightSwitch();
ls.on;
ls.isOn();
ls.switch();
Using Fields and Methods
 To access the field of an instance of an
Object use instance.field
 To access the method of an instance use
instance.method(arguments)
Example Using Light
Switch
 What does this main method print out?
LightSwitch ls = new LightSwitch();
System.out.println(ls.on);
ls.switch();
System.out.println(ls.isOn());
true
false
Person Example
class Person {
String name = “Jamal”;
int age = 26;
String getName() { return name; }
void setName(String n) { name = n; }
int getAge() { return age; }
void setAge(int a) { age = a; }
boolean smellsBad(){return true;}
}
Constructing Person
Objects
 To create an instance of the Person class
with a name of "George" and an age of 22
 Can we create a Person that has the name
George and the age 22 from the moment it
is created?
 Answer: Yes!
Person george = new Person();
george.setName("George");
george.setAge(22);
Constructors
 Constructors are special methods used to
construct an instance of a class
 They have no return type
 They have the same name as the class of the
Object they are constructing
 They initialize the state of the Object
 Call the constructor by preceding it with the
new keyword
Person Constructor
 Now we can construct George as follows:
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
// . . .
}
Person george = new Person("George", 22);
Default Constructor
 When you do not write a constructor in a
class, it implicitly has a constructor with no
arguments and an empty body
 Result: every class has a constructor
class LightSwitch {
// Leaving out the constructor
// is the same as . . .
LightSwitch() {}
}
Multiple Constructors
 A class can have multiple constructors
class LightSwitch {
boolean on;
LightSwitch() {
on = true;
}
LightSwitch(boolean o) {
on = o;
}
}
This Keyword
 Instance can refer to itself with the
keyword this
class LightSwitch {
boolean on;
LightSwitch() {
this.on = true; //(same as
on=true;)
}
LightSwitch(boolean on) {
this.on = on;
}
Cascading Constructors
 A constructor can call another constructor with
this(arguments)
class LightSwitch {
boolean on;
LightSwitch() {
this(true);
}
LightSwitch(boolean on) {
this.on = on;
}
}
Classes Recap
 Classes have fields to store the state of the
objects in the class and methods to provide
the operations the objects can perform.
 We construct instances of a class with the
keyword new followed by a call a constructor
method of the class.
 We can assign an instance to a variable with a
datatype named the same as the class.
 If you do not provide a constructor, the class
will have one with no arguments and no
statements by default.
Apple Example
class Apple {
String color;
double price;
Apple(String color, double price) {
this.color = color;
this.price = price;
}
Apple(double price) {
this("green", price);
}
String getColor() { return color; }
double getPrice() { return price; }
void setPrice(double p) { price = p; }
}
Apple Quiz
 What will these lines print out?
Apple a = new Apple("red", 100.0);
System.out.println(a.getColor());
System.out.println(a.getPrice());
a.setPrice(50.5);
System.out.println(a.getPrice());
Apple b = new Apple(74.6);
System.out.println(b.getColor());
System.out.println(b.getPrice());
b.setPrice(a.getPrice());
System.out.println(b.getPrice());
red
100.0
50.5
green
74.6
50.5
Lecture 8
Classes And Objects II
Recall the LightSwitch
Class
class LightSwitch {
boolean on = true;
boolean isOn() {
return on;
}
void switch() {
on = !on;
}
}
A Different LightSwitch
Class
class LightSwitch {
int on = 1;
boolean isOn() {
return on == 1;
}
void switch() {
on = 1 - on;
}
}
Abstraction
 Both LightSwitch classes behave the same.
 We treat LightSwitch as an abstraction:
we do not care about the internal code of
LightSwitch, only the external behavior
 Internal code = implementation
 External behavior = interface
Why is Abstraction
Important?
 We can continue to refine and improve
the implementation of a class so long as
the interface remains the same.
 All we need is the interface to an Object
in order to use it, we do not need to know
anything about how it performs its
prescribed behavior.
Breaking the Abstraction
Barrier
 A user of LightSwitch that relied on the
boolean field would break if we changed
to an integer field
class AbstractionBreaker {
public static void main(String[] args) {
LightSwitch ls = new LightSwitch();
if (ls.on) // now broken!
System.out.println("light is on");
else
System.out.println("light is off");
}
}
Public versus Private
 Label fields and methods private to ensure
other classes can't access them
 Label fields and methods public to ensure
other classes can access them.
 If they are not labeled public or private, for
now consider them public.
A Better LightSwitch
class LightSwitch {
private boolean on = true;
public boolean isOn() {
return on;
}
public void switch() {
on = !on;
}
}
Enforcing the Abstraction
Barrier
 By labeling the on field private . . .
 Now AbstractionBreaker's attempt to
access the on field would not have
compiled to begin with.
class LightSwitch {
private boolean on = true;
// . . .
}
if (ls.on) // would never have compiled
Equality Quiz 1
 Is (a == b) ?
 Answer: Yes
 Is (g == h) ?
 Answer: No
int a = 7;
int b = 7;
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
Primitives vs Objects
 Two datatypes in Java: primitives and objects
 Primitives: byte, short, int, long, double, float,
boolean, char
== tests if two primitives have the same value
 Objects: defined in Java classes
== tests if two objects are the same object
References
 The new keyword always constructs a
new unique instance of a class
 When an instance is assigned to a
variable, that variable is said to hold
a reference or point to that object
 g and h hold references to two different
objects that happen to have identical state
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
Reference Inequality
 g != h because g and h hold references to
different objects
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
"Jamal"
26
"Jamal"
26
g h
Reference Equality
 greg1 == greg2 because greg1 and
greg2 hold references to the same object
Person greg1 = new Person("Greg", 23);
Person greg2 = greg1;
"Greg"
23
greg2
greg1
Equality Quiz 2
 true or false?
a) g == h
b) g.getAge() == h.getAge()
c) greg1 == greg2
d) greg1.getAge() == greg2.getAge();
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
Person greg1 = new Person("Greg", 23);
Person greg2 = greg1;
false
true
true
true
 You can get information on all in-built Java
classes/methods by browsing the Java
Application Programming Interface (API)
 This documentation is essential to building
any substantial Java application
 Available on your CD's
Java API
Lecture 9
Lists and Iterators
Arrays Review
 Arrays are a simple data structure
 Arrays store a row of values of the same type
 Primitive types (int, double, etc.)
// array that can hold 10 chars
char[] letters = new char[10];
 Objects (Students, Dates etc.)
// array that can hold 3 LightSwitches
LightSwitch[] switches = new
LightSwitch[3];
Arrays Review
 Access each value through an index:
int[] intArray = new int[20];
intArray[0] = 4 ; intArray[1] = 75;
 Array indices start at 0, not 1
 first element of intArray is intArray[0]
 last element of intArray is
intArray[19]
 Important: Array lengths cannot be
changed once they are declared!
Is there something better?
 As we learned in the Gradebook lab,
because of their fixed length, arrays
can be annoying to use.
 Is there something like an array but
that will handle all the resizing
automatically?
 YES!
ArrayList
 ArrayList stores its elements internally
as an array.
 get method is fast – just retrieves the
element at the specified index
 add method is slow – may have to create a
larger array and copy over all the elements.
Linked List Data Structure
 A linked list is like a freight train: each link
stores an item and is connected to the next
link
 The list holds a reference to the first (and
maybe the last) element
Linked List Link 1 Link 2 Link n
Item 1 Item 2 Item n
. . .
LinkedList
 LinkedList stores its elements
internally in a linked list data structure.
 add method is fast – just appends a new
link to the end of the list
 get method is slow – has to walk down
the list retrieve the element at the
specified index
iterator method
 Both ArrayList and LinkedList
have a method named iterator
 Returns an object of type Iterator
 We use the Iterator to iterate over
the elements of the list.
Iterators
 We use Iterators to iterate over
the elements of lists
 hasNext method returns true when
there are more elements to iterate
over
 next method returns the next
element in the iteration
Casting
 Because the next method returns type
Object, you must cast the return value
to the actual type of the value.
 "Casting" means "promising" the compiler
that the object will be of a particular type
 This allows you to use methods of the
actual type without the compiler
complaining
GradeBook Iteration
class GradeBook {
private ArrayList grades;
void printGrades() {
Iterator gradeIter =
grades.iterator();
while(gradeIter.hasNext()) {
Double g =
(Double)gradeIter.next();
System.out.println(g.doubleValue());
}
for(Iterator studentIter =
students.iterator();
studentIter.hasNext();) {
Student s = studentIter.next();
System.out.println(s.getDescription());
(Student)studentIter.next();
Quiz
 Which list implementation is fast when
accessing arbitrary indices?
 What is wrong with the iteration below?
ArrayList
Casting
Lecture 10
Static and Final
public class MyMath {
public double PI = 3.14159;
public double square (double x) {
return x * x;
}
public static void main(String[ ] args) {
MyMath m = new MyMath();
System.out.println("m: value of PI is " + m.PI);
System.out.println("m: square of 5 is " + m.square(5));
MyMath n = new MyMath();
System.out.println("n: value of PI is " + n.PI);
System.out.println("n: square of 5 is " + n.square(5));
}
}
MyMath Example
 In Example 1, to calculate the square of 5
we need to create an instance of MyMath
class:
MyMath m = new MyMath();
 Then we invoke it’s square() method with
the argument 5:
m.square(5);
Objects Review
MyMath Output
 The results of invoking square() method on
instances m and n are the same:
m: value of PI is 3.14159
m: square of 5 is 25
n: value of PI is 3.14159
n: square of 5 is 25
 square() behaves the same no matter which
instance it is called on.
 So . . . why not have one square() method
for the entire class?
Also . . .
 The value of PI = 3.14159 is the
same for all instances of MyMath class.
 Why do we need to store a value of PI
separately for each instance of MyMath?
 Instead, can we have only one common
value of PI for the whole MyMath class?
MyMath with static
public class MyMath {
// add keyword "static" to field declaration
public static double PI = 3.14159;
// add keyword "static" to method declaration
public static double square (double x) {
return x * x;
}
// main method is always declared "static"
public static void main( String[ ] args) {
// MyMath m = new MyMath(); - No longer need this line!
// MyMath n = new MyMath(); - No longer need this line!
// Now invoke square() method on the MyMath class
System.out.println("Value of PI is " + MyMath.PI);
System.out.println("Square of 5 is" + MyMath.square(5));
}
}
Static Pi Field
 We added word static to the declaration of
the final variable PI:
public static double PI = 3.14159;
 It means that now we have only one value of
variable PI for all instances of MyMath class;
PI is now a class data field
The final keyword
 We declared PI as
public static double PI = 3.14159;
but this does not prevent changing its value:
MyMath.PI = 999999999;
 Use keyword final to denote a constant :
public static final double PI = 3.14159;
 Once we declare a variable to be final, it's
value can no longer be changed!
Final References
 Consider this final reference to a Point:
public static final Point ORIGIN =
new Point(0,0);
 This prevents changing the reference ORIGIN:
MyMath.ORIGIN = new Point(3, 4);
 BUT! You can still call methods on ORIGIN that
change the state of ORIGIN.
MyMath.ORIGIN.setX(4);
MyMath with static &
final
public class MyMath {
// add keyword final to field declaration
public static final double PI = 3.14159;
public static double square (double x) {
return x * x;
}
public static void main( String[ ] args) {
System.out.println("Value of PI is " +
MyMath.PI);
System.out.println("Square of 5: " +
MyMath.square(5));
}
}
Static Fields
 Only one instance of a static field data
for the entire class, not one per object.
 "static" is a historic keyword from
C/C++
 "Class fields" is a better term
 As opposed to "instance fields"
Static Square Method
 We also added the word "static" to the
declaration of the method square():
public static double square(double x) {
return x * x;
}
 Now the method square() is shared by all
instances of the class—only one square
method for the class, not one for each instance.
Static Methods
 Static methods do not operate on a
specific instance of their class
 Have access only to static fields and
methods of the class
 Cannot access non-static ones
 "Class methods" is a better term
 As opposed to "instance methods"
 Let's take a look at Java's Math class in the API
 You cannot create an instance of the Math Class,
it's just a place to store useful static methods
 All the methods and fields are static:
Math.sqrt(16)
Math.PI
Math.abs(-3)
Java's Math Class
Static Field Examples
 Constants used by a class
(usually used with final keyword)
 Have one per class; don’t need one in each object
public static final double TEMP_CONVERT= 1.8;
 If this is in class Temperature, it is invoked by
 double t = Temperature.TEMP_CONVERT * temp;
 Constants are all capital letters by tradition (C, C++)
 For example: PI , TEMP_CONVERT etc.
Static Method Examples
 For methods that use only the arguments and
therefore do not operate on an instance
public static double pow(double b, double p)
// Math class, takes b to the p power
 For methods that only need static data fields
 Main method in the class that starts the
program
 No objects exist yet for it to operate on!
POP QUIZ
Should it be static or non-static?
 Speed of light field
 getName() method in a Person class
 A sum method that returns the
resulting of adding both its arguments
 Width data field in a Rectangle class
static
non
static
non
Lecture 11
Packages, Access, and Scope
Access & Organization
 Let’s say you have 100’s of files on your
PC. What kind of problems do you
encounter?
 can’t find particular files
 duplicate or similar file names
 hard to keep personal files private
 Solution: Sort and organize your files
into subdirectories
Packages
 Organize your classes into sets or units
 Reduce problems with name conflicts
 Identify your classes in a set with specific
functionality
How to specify the package for a class:
package <package name>;
Using Packages
 A class can always access other classes
in its own package
 A class can always access public
classes in other packages
Q: What happens if we don’t specify a
package as public or private?
A: the default level of access is package
Levels of Access Control
Visibility private package
(default)
public
From the same
class
yes yes yes
From any class
in same package
no yes yes
From any class
outside the
package
no no yes
Big line to cross!
Import Classes and
Packages
 Specify the class you want to import:
import java.util.Date;
 You can import multiple classes:
import java.util.ArrayList;
 You can also import whole packages:
import java.util.*;
 Default imported package:
import java.lang.*;
Package Example:
Person.java
package examples;
class Person {
String name;
// add a field to store a birthday
// write a method to set the birthday
// write a method to get the birthday
}
Using java.util.Date
package examples;
class Person {
String name;
java.util.Date birthday;
void setBirthday(java.util.Date d) {
birthday = d;
}
java.util.Date getBirthday() {
return birthday;
}
}
Importing java.util.Date
package examples;
import java.util.Date;
class Person {
String name;
Date birthday;
void setBirthday(Date d) {
birthday = d;
}
Date getBirthday() {
return birthday;
}
}
Importing java.util.ArrayList
package examples;
import java.util.Date;
import java.util.ArrayList;
class Person {
String name;
Date birthday;
ArrayList friends;
void setBirthday(Date d) {
birthday = d;
}
// . . .
}
Importing java.util.*
package examples;
import java.util.*;
class Person {
String name;
Date birthday;
ArrayList friends;
void setBirthday(Date d) {
birthday = d;
}
// . . .
}
Packages Quiz 1
package example1;
public class A {
public int a = 5;
}
package example1;
public class B {
int b = 5;
}
package example1;
public class C {
private int c = 5;
}
package example1;
public class quiz{
void main() {
A ant = new A();
B bug = new B();
C cat = new C();
// Which are correct?
int testa = ant.a;
int testb = bug.b;
int testc = cat.c;
}
}
Package Quiz 2
package example2;
import example1.*;
public class quiz{
void main() {
A ant = new A();
B bug = new B();
C cat = new C();
// Which are correct?
int testa = ant.a;
int testb = bug.b;
int testc = cat.c;
}
}
package example1;
public class A {
public int a = 5;
}
package example1;
public class B {
int b = 5;
}
package example1;
public class C {
private int c = 5;
}
SCOPE
Scope of a Variable
 Definition: the block (section) of code for
which your variable (identifier) exists
 The scope is set to the block in which you
defined your variable
 This is the block of code where you can
use the variable
Scope Quiz 1
class TestScope {
int x = 0;
void f() {
int y = 20;
x = 10;
}
void print() {
System.out.println(x);
f();
System.out.println(x);
System.out.println(y);
}
}
What is the output
of print()?
This file won't
compile, so print
will never execute
Method Scope
class TestScope {
int x = 0;
void f() {
int y = 20;
x = 10;
}
void print() {
System.out.println(x);
f();
System.out.println(x);
System.out.println(y); // ERROR
}
}
 x is defined for the
whole class block.
 y is defined inside
the method f().
Scope Quiz 2
class TestScope {
int x = 0;
void f() {
int y = 20;
x = 10;
}
void print() {
int y = 0;
System.out.println(x);
f();
System.out.println(x);
System.out.println(y);
}
}`
Does this fix the
problem?
What is the output
of print()?
0
10
0
Scope Quiz 3
class TestScope {
int x = 0;
int y = 0;
void f() {
int y;
y = 20;
x = 10;
}
void print() {
System.out.println(x);
f();
System.out.println(x);
System.out.println(y);
}
}
Now, we declare a
new field, y.
What is the output of
print()?
0
10
0
Scope Quiz 4
class TestScope {
int x = 0;
int y = 0;
void f() {
y = 20;
x = 10;
}
void print() {
System.out.println(x);
f();
System.out.println(x);
System.out.println(y);
}
}
Now, we change the
method f().
What is the output of
print()?
0
10
20
Scope Quiz 5
package examples;
class Operations{
int square(int a) {
a = a * a;
return a;
}
void print() {
int a = 5;
System.out.println(square(a));
System.out.println(a);
}
}
 What is the output of
print()?
25 <- square(a)
5 <- a
Scope Quiz 6
package examples;
class Operations{
int a = 5;
int square(int a) {
a = a * a;
return a;
}
void print() {
System.out.println(square(a));
System.out.println(a);
}
}
 What is the output of
print()?
25 <- square(a)
5 <- a
Scope Quiz 7
package examples;
class Operations{
int a = 5;
int square(int a) {
this.a = a*a;
return a;
}
void print() {
System.out.println(square(a));
System.out.println(a);
}
}
 What is the output of
print()?
5 <- square(a)
25 <- a
Loop Scope
void adding() {
for (int j = 0; j<5; j++) {
int sum += j;
}
System.out.println(sum);
}
 What’s wrong with the above segment of code?
ERROR: sum is only defined inside the for loop
Loop Scope Fixed
void adding() {
int sum = 0;
for (int j = 0; j<5; j++) {
sum += j;
}
System.out.println(sum);
}
 sum is now defined for the whole block of
code for the adding method
Summary of Scope
 Definition: the block (section) of code for
which your variable (identifier) exists
 The scope is set to the block in which
you defined your variable
 This is the block of code where you can
use the variable
Lecture 12
Inheritance
What is Inheritance?
 In the real world: We inherit traits from our
mother and father. We also inherit traits from
our grandmother, grandfather, and ancestors.
We might have similar eyes, the same smile,
a different height . . . but we are in many
ways "derived" from our parents.
 In software: Object inheritance is more well
defined! Objects that are derived from other
object "resemble" their parents by inheriting
both state (fields) and behavior (methods).
Dog Class
public class Dog {
private String name;
private int fleas;
public Dog(String n, int f) {
name = n;
fleas = f;
}
public String getName() { return name; }
public int getFleas() { return fleas; }
public void speak() {
System.out.println("Woof");
}
}
Cat Class
public class Cat {
private String name;
private int hairballs;
public Cat(String n, int h) {
name = n;
hairballs = h;
}
public String getName() { return name; }
public int getHairballs() { return hairballs; }
public void speak() {
System.out.println("Meow");
}
}
Problem: Code Duplication
 Dog and Cat have the name field
and the getName method in
common
 Classes often have a lot of state and
behavior in common
 Result: lots of duplicate code!
Solution: Inheritance
 Inheritance allows you to write new classes
that inherit from existing classes
 The existing class whose properties are
inherited is called the "parent" or superclass
 The new class that inherits from the super
class is called the "child" or subclass
 Result: Lots of code reuse!
Dog
String name
int fleas
String getName()
int getFleas()
void speak()
Cat
String name
int hairballs
String getName()
int getHairballs()
void speak()
Dog
int fleas
int getFleas()
void speak()
Cat
int hairballs
int getHairballs()
void speak()
Animal
String name
String getName()
using
inheritance
superclass
subclass
subclass
Animal Superclass
public class Animal {
private String name;
public Animal(String n) {
name = n;
}
public String getName() {
return name;
}
}
Dog Subclass
public class Dog extends Animal {
private int fleas;
public Dog(String n, int f) {
super(n); // calls Animal constructor
fleas = f;
}
public int getFleas() {
return fleas;
}
public void speak() {
return System.out.println("Woof");
}
}
Cat Subclass
public class Cat extends Animal {
private int hairballs;
public Cat(String n, int h) {
super(n); // calls Animal constructor
hairballs = h;
}
public int getHairballs() {
return hairballs;
}
public void speak() {
return System.out.println("Meow");
}
}
Inheritance Quiz 1
 What is the output of the following?
Dog d = new Dog("Rover" 3);
Cat c = new Cat("Kitty", 2);
System.out.println(d.getName() + " has " +
d.getFleas() + " fleas");
System.out.println(c.getName() + " has " +
c.getHairballs() + " hairballs");
Rover has 3 fleas
Kitty has 2 hairballs
(Dog and Cat inherit the getName method from Animal)
Inheritance Rules
 Use the extends keyword to indicate that
one class inherits from another
 The subclass inherits all the fields and
methods of the superclass
 Use the super keyword in the subclass
constructor to call the superclass
constructor
Subclass Constructor
 The first thing a subclass constructor must do
is call the superclass constructor
 This ensures that the superclass part of the
object is constructed before the subclass part
 If you do not call the superclass constructor
with the super keyword, and the superclass
has a constructor with no arguments, then that
superclass constructor will be called implicitly.
Implicit Super Constructor
Call
If I have this Food class:
public class Food {
private boolean raw;
public Food() {
raw = true;
}
}
then this Beef subclass:
public class Beef extends Food {
private double weight;
public Beef(double w) {
weight = w
}
}
is equivalent to:
public class Beef extends Food {
private double weight;
public Beef(double w) {
super();
weight = w
}
}
Inheritance Quiz 2
public class A {
public A() { System.out.println("I'm A"); }
}
public class B extends A {
public B() { System.out.println("I'm B"); }
}
public class C extends B {
public C() { System.out.println("I'm C"); }
}
What does this print out?
C x = new C();
I'm A
I'm B
I'm C
• Subclasses can override methods in their superclass
• What is the output of the following?
ThermUS thermometer = new ThermUS(100);
System.out.println(thermometer.getTemp());
Overriding Methods
class ThermUS extends Therm {
public ThermUS(double c) {
super(c);
}
// degrees in Fahrenheit
public double getTemp() {
return celsius * 1.8 + 32;
}
}
class Therm {
public double celsius;
public Therm(double c) {
celsius = c;
}
public double getTemp() {
return celcius;
}
}
212
Calling Superclass
Methods
 When you override a method, you can call
the superclass's copy of the method by
using the syntax super.method()
class Therm {
private double celsius;
public Therm(double c) {
celcius = c;
}
public double getTemp() {
return celcius;
}
}
class ThermUS extends Therm {
public ThermUS(double c) {
super(c);
}
public double getTemp() {
return super.getTemp()
* 1.8 + 32;
}
}
Access Level
• Classes can contain fields and methods
of four different access levels:
• private: access only to the class itself
• package: access only to classes in the
same package
• protected: access to classes in the
same package and to all subclasses
• public: access to all classes everywhere
Variable Type vs Object
Type
 Variables have the types they are given when
they are declared and objects have the type of
their class.
 For an object to be assigned to a variable is
must be of the same class or a subclass of the
type of the variable.
 You may not call a method on a variable if it's
type does not have that method, even if the
object it references has the method.
Which Lines Don't
Compile?
public static void main(String[] args) {
Animal a1 = new Animal();
a1.getName();
a1.getFleas();
a1.getHairballs();
a1.speak();
Animal a2 = new Dog();
a2.getName();
a2.getFleas();
a2.getHairballs();
a2.speak();
Dog d = new Dog();
d.getName();
d.getFleas();
d.getHairballs();
d.speak();
}
// Animal does not have getFleas
// Animal does not have getHairballs
// Animal does not have speak
// Animal does not have getFleas
// Animal does not have getHairballs
// Animal does not have speak
// Dog does not have getHairballs
Remember Casting?
 "Casting" means "promising" the compiler
that the object will be of a particular type
 You can cast a variable to the type of the
object that it references to use that
object's methods without the compiler
complaining.
 The cast will fail if the variable doesn't
reference an object of that type.
Which Castings Will Fail?
public static void main(String[] args) {
Animal a1 = new Animal();
((Dog)a1).getFleas();
((Cat)a1).getHairballs();
((Dog)a1).speak();
Animal a2 = new Dog();
((Dog)a2).getFleas();
((Cat)a2).getHairballs();
((Dog)a2).speak();
Dog d = new Dog();
((Cat)d).getHairballs();
}
// a1 is not a Dog
// a1 is not a Cat
// a1 is not a Dog
// a2 is not a Cat
// d is not a Cat
Programming Example
 A Company has a list of Employees. It asks
you to provide a payroll sheet for all
employees.
 Has extensive data (name, department, pay
amount, …) for all employees.
 Different types of employees – manager, engineer,
software engineer.
 You have an old Employee class but need to add
very different data and methods for managers and
engineers.
 Suppose someone wrote a name system, and already
provided a legacy Employee class. The old Employee
class had a printData() method for each Employee that
only printed the name. We want to reuse it, and print pay
Borrowed with permission from Course 1.00 Notes
public … Main(…){
Employee e1…("Mary","Wang");
...
e1.printData();
// Prints Employee names.
...
}
Employee e1
lastName
firstName
printData
Encapsulation Message passing "Main event loop"
private:
REVIEW PICTURE
Employee class
class Employee {
// Data
private String firstName, lastName;
// Constructor
public Employee(String fName, String lName) {
firstName= fName; lastName= lName;
}
// Method
public void printData() {
System.out.println(firstName + " " + lastName);}
}
This is a simple super or base class.
Inheritance
Class Employee
firstName
lastName
printData()
Class Manager
salary
firstName
lastName
Class Engineer
hoursWorked
wages
firstName
lastName
printData()
getPay()
is-a
printData()
getPay()
Already written:
is-a
You next write:
Engineer class
class Engineer extends Employee {
private double wage;
private double hoursWorked;
public Engineer(String fName, String lName,
double rate, double hours) {
super(fName, lName);
wage = rate;
hoursWorked = hours;
}
public double getPay() {
return wage * hoursWorked;
}
public void printData() {
super.printData(); // PRINT NAME
System.out.println("Weekly pay: $" + getPay(); }
Subclass or (directly) derived class
Manager class
class Manager extends Employee {
private double salary;
public Manager(String fName, String lName, double sal){
super(fName, lName);
salary = sal; }
public double getPay() {
return salary; }
public void printData() {
super.printData();
System.out.println("Monthly salary: $" + salary);}
}
Subclass or (directly) derived class
Inheritance…
Class Manager
Salary
firstName
lastName
printData
getPay
Class SalesManager
firstName
lastName
printData
getPay
Salary
salesBonus
is-a
SalesManager Class
class SalesManager extends Manager {
private double bonus; // Bonus Possible as commission.
// A SalesManager gets a constant salary of $1250.0
public SalesManager(String fName, String lName, double b) {
super(fName, lName, 1250.0);
bonus = b; }
public double getPay() {
return 1250.0; }
public void printData() {
super.printData();
System.out.println("Bonus Pay: $" + bonus; }
}
(Derived class from derived class)
Main method
public class PayRoll {
public static void main(String[] args) {
// Could get Data from tables in a Database.
Engineer fred = new Engineer("Fred", "Smith", 12.0, 8.0);
Manager ann = new Manager("Ann", "Brown", 1500.0);
SalesManager mary= new SalesManager("Mary", "Kate", 2000.0);
// Polymorphism, or late binding
Employee[] employees = new Employee[3];
employees[0]= fred;
employees[1]= ann;
employees[2]= mary;
for (int i=0; i < 3; i++)
employees[i].printData();
}
}
Java knows the
object type and
chooses the
appropriate method
at run time
Output from main method
Fred Smith
Weekly pay: $96.0
Ann Brown
Monthly salary: $1500.0
Mary Barrett
Monthly salary: $1250.0
Bonus: $2000.0
Note that we could not write:
employees[i].getPay();
because getPay() is not a method of the superclass Employee.
In contrast, printData() is a method of Employee, so Java can find the
appropriate version.
Object Class
 All Java classes implicitly inherit from
java.lang.Object
 So every class you write will automatically
have methods in Object such as equals,
hashCode, and toString.
 We'll learn about the importance of some
of these methods in later lectures.
Lecture 13
Abstract Classes and Interfaces
What is an Abstract
Class?
 An abstract class is a class that cannot be
instantiated—we cannot create instances
of an abstract class.
 One or more methods may be declared,
but not defined. (The programmer has not
yet written code for a few methods).
 The declared methods and classes have
the keyword abstract in their signature.
public class Employee {
private String name;
private double salary;
public Employee(String n, double s) {
name = n;
salary = s;
}
public String getName() { return name; }
public double getSalary() { return salary; }
public String description() {
return "employee with a salary of $ " + salary;
}
}
Employee Class
public class Student {
private String name;
private String course;
public Student(String n, String c) {
name = n;
course = c;
}
public String getName() { return name; }
public String getCourse() { return course; }
public String description() {
return "a student majoring in " + course;
}
}
Student Class
Common Functionality
 Student and Employee may have
common fields and methods.
private String name;
getName()
 Instead of repeating code, introduce
a superclass
Example Hierarchy
 Consider the following class structure:
Person
Employee Student
Superclass
Subclasses
public class Person {
String name;
public Person(String n) {
name = n;
}
public String getName() {
return name;
}
}
Person Class
public class Employee extends Person {
// private String name;
private double salary;
public Employee(String n, double s) {
super(n);
salary = s;
}
// public String getName() { return name; }
public double getSalary() {
return salary;
}
public String description() {
return "an employee with a salary of $" + salary;
}
}
Employee Subclass of
Person
public class Student extends Person{
// private String name;
private String course;
public Student(String n, String c) {
super(n);
course = c; }
// public String getName() { return name; }
public String getCourse() {
return course; }
public String description() {
return "a student majoring in " + course; }
}
Revised Student
description() Method
 Let’s create Person, Employee, and Student object
Person kwame = new Student("Kwame", "CS");
Employee kojo = new Employee("Kojo", 200000);
Student yaa = new Student("Yaa", "Math");
 Description of an Employee and a Student returns:
employee with a salary of ¢200000
student majoring in Math
 Can we say: kwame.description()
 NO! the variable kwame is of type Person, which does
not have a description() method defined
public class Person {
String name;
public Person(String n) {
name = n;
}
public String getName() {
return name;
}
// add a method to return the
// description of a Person
}
Let's Revise Person
public class Person {
String name;
public Person(String n) {
name = n;
}
public String getName() {
return name;
}
public String description() {
return "person named " + name;
}
}
Revised Person
description() Revisited
 Now we can call the description() method
on Objects that are of type Person (instances
of a Student, Employee, or Person)
Person kwame = new
Person("Kwame");
Person kojo = new
Employee("Kojo", 200000);
Person yaa = new Student("Yaa", "Math");
kwame.description();
kojo.description();
yaa.description();
description Method
Revisited
 Now we can call the description() method on
Objects that are of type Person (instances of a
Student, Employee, or Person)
Person kwame = new Person("Kwame");
Person kojo = new Employee("Kojo", 20000);
Person yaa = new Student("Yaa", "Math");
kwame.description(); // method in Person
kojo.description(); // method in Employee
yaa.description(); // method in Student
 PROBLEM: We don’t want to create instances of
Person, just Students and Employee
Abstract Methods
 Solution: Use the keyword abstract
 A method labeled abstract is declared
but not implemented
 Rule: An abstract class can have
zero or more abstract methods
 Make description() an abstract
method in the class Person
public abstract class Person {
String name;
public Person(String n) {
name = n;
}
public String getName() {
return name;
}
public abstract String description();
}
Abstract Person Class
Abstract Classes
 Cannot instantiate or create an object of an
abstract class
Person jacob = new Person("Jacob") // ERROR!!
 An abstract class can have both abstract and
non-abstract methods
 Abstract methods need to be defined in concrete
subclasses (classes that can be instantiated)
Using Abstract Classes
 Variables can be objects of abstract types
Person p = new Student("Greg", "CS");
 Here p has the type Person, but
references an instance of a non-abstract
class, Student
Calls to Abstract Methods
Person[] people = new Person[2];
people[0] = new Employee("Evita", 2000000.0);
people[1] = new Student("Greg", "CS");
for (int i = 0; i < people.length; i++) {
Person p = people[i];
System.out.println(p.getName() + ", " +
p.description());
}
What is the output?
Evita, an employee with a salary of $200000
Greg, a student majoring in CS
public abstract class Person {
String name;
public Person(String n) {
name = n;
}
public String getName() {
return name;
}
// must declare in order to call
// method on variable of type Person
public abstract String description();
}
Abstract Person Class
Advantages
 Classes can now be very general in a
class/type hierarchy.
 This allows more abstraction in object
oriented programming.
 Have more control over inheritance in a
class/type hierarchy.
 Make a class abstract even if there are no
abstract methods
Summary of Abstract
Classes
 Partial implementation of a class
 Cannot be instantiated
 Use the abstract keyword in their
signature.
 Abstract methods are defined in
subclasses
Problem Situation
 Consider creating an Object that
represents an Intern.
 An Intern behaves like both an
Employee and a Student.
 Problem: a class can only extend
ONE other class
Interfaces
 Solution: Use an interface, which is a
set of requirements for a class
 A class can implement more than one
interface
 Methods in an interface are automatically
public and abstract
 Make Employee an interface
Interface Details
 An interface is a contract for a class.
 An interface specifies a set of methods a
class must implement.
 An interface, similar to an abstract class,
cannot be instantiated
 An interface has no constructors, only
constants and method declarations.
 Classes implement interfaces using the
keyword implements
Employee Interface
public interface Employee {
// fields are public static final constants
double STARTING_SALARY = 200000.0;
// methods are automatically public and
// abstract; must be overridden in
// classes that implement the interface
String description();
double getSalary();
}
public class Student {
private String name;
private String course;
public Student(String n, String c) {
name = n;
course = c;
}
public String getName() { return name; }
public String getCourse() { return course; }
public String description() {
return "a student majoring in " + course;
}
}
Student Class Revisted
class Intern extends Student implements Employee {
private double income;
public Intern(String n, String c) {
super(n, c);
income = STARTING_SALARY;
}
public double getSalary() { return income; }
public String description() {
return "intern majoring in "+ super.getCourse() +
"with an income of $" + income;
}
}
Intern Class
Using Intern Class
public static void main(String[] args) {
Intern irish = new Intern("Conor", "Math");
System.out.println(irish.getName() + " ," +
irish.description());
}
Output:
Conor, intern majoring in Math
with an income of $200000.0
Variable Types
 A variable may have the type of an abstract
class, an interface, or a concrete class (a
non-abstract class).
 Because only a concrete class can be
instantiated, an object may only have the type
of a concrete class.
 All of these are valid variable declarations:
Intern a = new Intern("Conor", "Math");
Student b = new Intern("Conor", "Math");
Employee c = new Intern("Conor", "Math");
Variable vs Object Types
(Again)
Intern a = new Intern("Conor", "Math");
Student b = new Intern("Conor", "Math");
Employee c = new Intern("Conor", "Math");
 These expressions will not compile:
b.getSalary() // Student does not have getSalary
c.getCourse() // Employee does not have getCourse
 But all of these will:
((Employee)b).getSalary()
((Intern)b).getSalary()
((Student)c).getCourse()
((Intern)c).getCourse()
Interface Rules
 Interfaces may specify but do not
implement methods.
 A class that implements the interface
must implement all its methods.
 Interfaces cannot be instantiated.
 Interfaces may contain constants.
Lecture 14
Exceptions
Handling Errors with Exceptions
Attack of the Exception
 What happens when this method is used to
take the average of an array of length zero?
 Program throws an Exception and fails
java.lang.ArithmeticException: / by zero
public static int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}
What is an Exception?
 An error event that disrupts the program
flow and may cause a program to fail.
 Some examples:
 Performing illegal arithmetic
 Illegal arguments to methods
 Accessing an out-of-bounds array element
 Hardware failures
 Writing to a read-only file
Another Exception
Example
 What is the output of this program?
public class ExceptionExample {
public static void main(String args[]) {
String[] greek = {"Alpha", "Beta"};
System.out.println(greek[2]);
}
}
Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
Exception Message
Details
 What exception class?
 Which array index is out of bounds?
 What method throws the exception?
 What file contains the method?
 What line of the file throws the exception?
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])
Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
ArrayIndexOutOfBoundsException
2
main
ExceptionExample.java
4
Exception Handling
 Use a try-catch block to handle
exceptions that are thrown
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
Exception Handling
Example
public static int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}
public static void printAverage(int[] a) {
try {
int avg = average(a);
System.out.println("the average is: " + avg);
}
catch (ArithmeticException e) {
System.out.println("error calculating average");
}
}
Catching Multiple
Exceptions
 Handle multiple possible exceptions by
multiple successive catch blocks
try {
// code that might throw multiple exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
}
Exceptions Terminology
 When an exception happens we
say it was thrown or raised
 When an exception is dealt with,
we say the exception is was
handled or caught
Unchecked Exceptions
 All the exceptions we've seen so far
have been Unchecked Exceptions, or
Runtime Exceptions
 Usually occur because of
programming errors, when code is not
robust enough to prevent them
 They are numerous and can be
ignored by the programmer
Common Unchecked
Exceptions
 NullPointerException
reference is null and should not be
 IllegalArgumentException
method argument is improper is some way
 IllegalStateException
method called when class is in improper state
Checked Exceptions
 There are also Checked Exceptions
 Usually occur because of errors
programmer cannot control:
examples: hardware failures, unreadable files
 They are less frequent and they cannot
be ignored by the programmer . . .
Dealing With Checked
Exceptions
 Every method must catch (handle) checked
exceptions or specify that it may throw them
 Specify with the throws keyword
void readFile(String filename) {
try {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
} catch (FileNotFoundException e) {
System.out.println("file was not found");
}
}
void readFile(String filename) throws FileNotFoundException {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
}
or
Exception Class Hierarchy
Exception
RuntimeException IOException
FileNotFoundException
MalformedURLException
SocketException
ArrayIndexOutofBounds
NullPointerException
etc. etc.
SQLException
IllegalArgumentException
Unchecked Exceptions Checked Exceptions
 All exceptions are instances of
classes that are subclasses of
Exception
Checked and Unchecked
Exceptions
Checked Exception Unchecked Exception
not subclass of
RuntimeException
subclass of
RuntimeException
if not caught, method must
specify it to be thrown
if not caught, method may
specify it to be thrown
for errors that the
programmer cannot directly
prevent from occurring
for errors that the
programmer can directly
prevent from occurring,
IOException,
FileNotFoundException,
SocketException
NullPointerException,
IllegalArgumentException,
IllegalStateException
Exception Constructors
 Exceptions have at least two constructors:
1. no arguments
NullPointerException e = new NullPointerException();
2. single String argument descriptive
message that appears when exception error
message is printed
IllegalArgumentExceptione e =
new IllegalArgumentException("number must be positive");
Writing Your Own
Exception
 To write your own exception, write a
subclass of Exception and write both
types of constructors
public class MyCheckedException extends IOException {
public MyCheckedException() {}
public MyCheckedException(String m) {super(m);}
}
public class MyUncheckedException extends RuntimeException {
public MyUncheckedException() {}
public MyUncheckedException(String m) {super(m);}
}
Throwing Exceptions
 Throw exception with the throw keyword
public static int average(int[] a) {
if (a.length == 0) {
throw new IllegalArgumentException("array is empty");
}
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}
Keyword Summary
 Four new Java keywords
 try and catch – used to handle
exceptions that may be thrown
 throws – to specify which exceptions a
method throws in method declaration
 throw – to throw an exception
Throws and Inheritance
 A method can throw less exceptions, but
not more, than the method it is overriding
public class MyClass {
public void doSomething()
throws IOException, SQLException {
// do something here
}
}
public class MySubclass extends MyPlay {
public void doSomething() throws IOException {
// do something here
}
}
Line Intersection Example
 Consider this class Line, which has two
fields, a slope and a yIntercept
 Let's write an intersect method that returns
the x-coordinate at which the two lines
intersect.
sig Line {
private double slope;
private double yIntercept;
double getSlope() { return slope; }
double getYIntercept() { return yIntercept; }
}
 Calculating the x-coordinate at
which two lines intersect
 We could translate this directly into
the following intersect method:
Boring Math Stuff . . .
y = m1x + b1
y = m2x + b2
m1x + b1 = m2x + b2
m1x - m2x = b2 - b1
(m1 - m2)x = b2 - b1
x = (b2 - b1)/(m1 - m2)
double intersect(Line line1, Line line2) {
return (line2.getYIntercept() – line1.yIntercept()) /
(line1.slope() – line2.slope())
}
 Parallel lines will never intersect.
 If lines are parallel, then their slopes will be equal,
line1.slope() – line2.slope() = 0, and
our method will attempt to divide by zero
 Let's write a new exception ParallelException
to throw when this occurs.
What About Parallel
Lines?
ParallelException
 ParallelException will be a checked
exception because calculating whether lines
are parallel is not something we expect the
programmer to know how to do and prevent
in advance.
 Checked exceptions are a subclass of
Exception, but not RuntimeException
public class ParallelException extends Exception {
public ParallelException() {}
public ParallelException(String msg) { super(msg); }
}
Final Intersect Method
 Because it is a checked exception,
intersect must specify that it throws it
double intersect(Line line1, Line line2)
throws ParallelException
{
if (line1.slope() = line2.slope()) {
throw new ParallelException();
}
return (line2.getYIntercept() –
line1.yIntercept()) /
(line1.slope() – line2.slope())
}
Calling the intersect
Method
 A method that accepts two Lines as
arguments, calls intersect, and prints
out the results:
void printIntersect(Line line1, Line line2) {
try {
double x = intersect(line1, line2);
System.out.println("Intersect at " + x);
} catch (ParallelException e) {
System.out.println("They are parallel");
}
}
Lecture 15
I/O and Parsing
Reading and Writing with
Java's Input/Output Streams
and Parsing Utilities
Input/Output Basics
 Input/Output = I/O = communication
between a computer program and external
sources and destinations of information
 Involves Reading and Writing
 Reading input from a source
 Writing output to a destination
 Example Sources and Destinations:
 Files
 Network connections
 Other programs
Java I/O Streams
 Java uses an I/O system called
streams (pioneered in C++)
 Java provides java.io package to
implement streams
 Streams treat all external source and
destinations of data the same way: as
"streams" of information
Input vs. Output Streams
 Reading from an Input Stream
 Writing to an Output Stream
Byte vs. Character
Streams
 Byte Streams are used to read and write
data in binary format (1's and 0's)
example data: images, sounds, executable
programs, word-processing documents, etc.
 Character Streams are used to read and
write data in text format (characters)
example data: plain text files (txt extension),
web pages, user keyboard input, etc.
Java Classes
 Package java.io offers classes to connect
to streams
 To connect to a stream, instantiate a
subclass of one of these abstract
superclasses:
input output
byte InputStream OutputStream
character Reader Writer
Using a Stream Class
1. Open a stream by instantiating a
new stream object
2. While more information to read/write,
read/write that data
3. Close the stream by calling the
object’s close() method
Using a Reader
 Recall: a Reader is used to read a character
input stream
 Reader offers these methods to read single
characters and arrays of characters:
int read()
int read(char cbuf[])
int read(char cbuf[], int offset, int length)
 Reader is abstract so you must instantiate a
subclass of it to use these methods
How to Read from a Text
File
public void readFile() {
FileReader fileReader = null;
try {
fileReader = new FileReader("input.txt");
int c = fileReader.read();
while (c != -1) {
// cast c to char and use it
c = fileReader.read();
}
} catch (FileNotFoundException e) {
System.out.println("File was not found");
} catch (IOException e) {
System.out.println("Error reading from file");
}
if (fileReader != null) {
try { fileReader.close(); }
catch (IOException e) { /* ignore */ }
}
}
Wrap in a BufferedReader
 BufferedReader has a readLine() method to
read an entire line of characters efficiently
 Wrap a Reader with a BufferedReader by
passing the Reader as a constructor argument
FileReader fr = new FileReader("myFile.txt");
BufferedReader br = new BufferedReader(fr);
 The readLine() method returns null when there
are no more lines to read
Using BufferedReader
public void readFileWithBufferedReader() {
BufferedReader bufferedReader = null;
try {
FileReader fr = new FileReader("input.txt");
bufferedReader = new BufferedReader(fr);
String line = bufferedReader.readLine();
while (line != null) {
// do something with line
line = bufferedReader.readLine();
}
} catch (FileNotFoundException e) {
System.out.println("File was not found");
} catch (IOException e) {
System.out.println("Error reading from file");
}
if (bufferedReader != null) {
try { bufferedReader.close(); }
catch (IOException e) { /* ignore */ }
}
}
Writers
 Writer is an abstract class to write to character
streams
 Offers write methods to write single characters,
arrays of characters, and strings
void write(int c)
void write(char cbuf[])
void write(String str)
 BufferedWriter offers efficient writing and a
newLine() method to insert a blank line
 Close writers with close() method when done
How to Write to a Text
File
public void writeFileWithBufferedWriter() {
BufferedWriter buffWriter = null;
try {
FileWriter fw = new FileWriter("output.txt");
buffWriter = new BufferedWriter(fw);
while (/*still stuff to write */) {
String line = // get line to write
buffWriter.write(line);
buffWriter.newLine();
}
} catch (IOException e) {
System.out.println("Error writing to file");
}
if (buffWriter != null) {
try { buffWriter.close(); }
catch(IOException e) { /* ignore */ }
}
}
Example: Copying Text
Files
void copyFiles(String inFilename, String outFilename)
throws FileNotFoundException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(inFilename));
bw = new BufferedWriter(new FileWriter(outFilename));
String line = br.readLine();
while(line != null) {
bw.write(line);
bw.newLine();
line = br.readLine();
}
} catch (IOException e) {
System.out.println("Error copying files");
}
if (br != null) {try {br.close();} catch(IOException e) {}}
if (bw != null) {try {bw.close();} catch(IOException e) {}}
}
Reading from Keyboard
Input
 Keyboard input is sent over a stream referred
to as "standard" input
 Java "standard" input is the InputStream
object System.in (a byte stream)
 To read characters over an InputStream,
need to wrap it in an InputStreamReader
 To read line by line, wrap the Input-
StreamReader with a BufferedReader
Reading from Keyboard
Input
/**
* Returns a line read from keyboard input.
* Return null if there was an error reading the line.
*/
public void String readKeyboardLine() throws IOException {
BufferedReader br = null;
String line = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
line = br.readLine();
} catch (IOException e) {}
if (br != null) {
try { br.close(); }
catch (IOException e) { /* ignore */ }
}
return line;
}
What We've Learned So
Far
 Types of Streams
 Input vs. output streams
 Byte vs. character streams
 How to . . .
 Read from text files
 Write to text files
 Read text from keyboard input
 Use buffered streams
 You are left on your own to figure out
how to use other streams
Intro to Parsing
 Programs often encode data in text
format to store in files
 Programs later need to decode the text
in the files back into the original data
 Process of decoding text back into data
is known as parsing
Delimiters
 When data is stored in text format,
delimiter characters are used to
separate tokens of the data
 A list of first names stored
separated by the '#' delimiter:
Greg#Kwame#Sonya#Bobby
 Same list with a newline delimiter:
Greg
Kwame
Sonya
Bobby
StringTokenizer
 java.util.StringTokenizer separates
Strings at the delimiters to extract tokens
 Default constructor will assume any whitespace
(spaces, tabs, newlines) to be delimiters
 Second constructor accepts String of any
delimiter characters
 nextToken method returns the next data token
between delimiters in the text
 hasMoreTokens returns true if the text has
remaining tokens
Using StringTokenizer
 Printing out every name from a file where
names are delimited by whitespace:
public void printNamesFromFile(String filename) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
while(line != null) {
StringTokenizer st = new StringTokenizer(line);
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
line = br.readLine();
}
} catch (IOException e) {
System.out.println("Error reading from file.");
}
if (br != null) { try { br.close(); } catch(IOException e) {} }
}
Text → Numbers
 Often necessary to parse numbers
stored as text into Java primitives
 Wrapper classes for primitives
provide static methods to do so
int Integer.parseInt(String s)
double Double.parseDouble(String s)
 Throw NumberFormatException if
the specified String cannot be
converted into the primitive
Putting it All Together
 File 1: Employee_May.dat
Format: Name, SSN, Hourly Rate, Salary to Date
Paul Njoroge, 555-12-3456, 65, 20000
Evelyn Eastmond, 555-22-2222, 70, 30000
Peilei Fan, 555-33-4444, 60, 15000
Ethan Howe, 555-44-5555, 80, 40000
Naveen Goela, 555-66-8888, 75, 20000
. . .
 File 2: Hours_June.dat
Format: Consecutive integers, which are the number of hours
each employee has worked during June. The integers have the
same sequence as that of the employee records.
Content: 50 60 40 50 70 . . .
What We Need to Do . . .
1. For each employee, multiply the hours
worked by the hourly rate
2. Add this to the value of the salary to date
3. Write to a new file named
Employee_June.dat, in the same
format as Employee_May.dat, only it
includes the updated, increased value of
the salary to date.
 Create a StringTokenizer over the single
line in the Hours_June.dat file
BufferedReader empReader = null;
String hoursLine = null;
try {
empReader = new BufferedReader(
new FileReader("Hours_June.dat"));
hoursLine = empReader.readLine();
} catch(IOException e) {
System.out.println("Could not read Hours_June.dat");
}
if (empReader != null) {
try { empReader.close(); }
catch(IOException e) {}
}
if (line == null) // exit and report an error
StringTokenizer hoursST = new StringTokenizer(hoursLine);
BufferedReader mayReader = null;
BufferedWriter juneWriter = null;
try {
mayReader = new BufferedReader(
new FileReader("Employee_May.dat"));
juneWriter = new BufferedWriter(
new FileWriter("Employee_June.dat"));
// On next slide, we add code to parse the May data,
// do the salary calculation, and write the June data
} catch(IOException e) {
System.out.println("Error with employee files");
}
if (mayReader != null) {
try { mayReader.close(); } catch(IOException e) {}
}
if (juneWriter != null) {
try { juneWriter.close(); } catch(IOException e) {}
}
 Opening and closing the streams to
the employee files
Writing the June Data
String employeeStr = mayReader.readLine();
while(employeeStr != null) {
StringTokenizer empST =
new StringTokenizer(employeeStr, ",");
String name = empST.nextToken();
String ssn = empST.nextToken();
double rate = Double.parseDouble(empST.nextToken());
double salary = Double.parseDouble(empST.nextToken());
int hours = Integer.parseInt(hoursST.nextToken());
double newSalary = salary + hours * rate;
juneWriter.write(name + "," + ssn + "," +
rate + "," + newSalary);
juneWriter.newLine();
employeeStr = mayReader.readLine();
}
Lecture 16
Introduction to Swing
Lecture Summary
 Over the next 2 lectures, we will introduce you
to the techniques necessary to build graphical
user interfaces (GUI) for your applications.
 Learning Swing basic concepts: components and
containers, colors, layout;
 Constructing Swing interfaces;
 Using the Swing Event Model.
 Style: Mixture of lecture and lab
Swing Example
import java.awt.*;
import javax.swing.*;
public class MyTest extends JFrame {
JLabel myLabel = new JLabel("Hello, World!");
public MyTest() {
super("MyTest");
setSize(350, 100);
getContentPane().add(myLabel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main (String args[]) {
MyTest m = new MyTest();
}
}
WHAT IS SWING?
 So far, our user interfaces have only been
textual, meaning the user sees text and writes
text at the command prompt.
 Today we will learn to make our interfaces
graphical, so we can use our programs
through windows, click on buttons, etc.
 Graphical User Interface (GUI)
 Swing is Java's graphical user interface library
 You MUST import the following packages:
import java.awt.*;
import javax.swing.*;
Simple Swing Application
JFrame
 JFrame is the application window class
 It is special; it draws the window and
interacts with the operating system
 When a JFrame is created, an inner
container called the contentPane is
automatically created
 We don't draw graphics directly on
JFrame; we draw on the
contentPane
Anatomy of a JFrame
title bar
minimize
maximize
close
The contentPane holds your
content; created automatically
when a JFrame is created
Exercise 1: Empty Frame
package swinglab;
import java.awt.*;
import javax.swing.*;
// extends keyword makes Calc a JFrame
public class Calc extends JFrame{
public Calc() {
// get the contentPane and assign it to cp
Container cp = getContentPane();
// exit program when user closes the window
setDefaultCloseOperation(EXIT_ON_CLOSE);
// sets the layout; will be covered in later slide
cp.setLayout(new FlowLayout());
// sets title to "My Funky Calculator"
setTitle("My Funky Calculator");
setSize(1000,700); // Frame has 0 default size
}
Exercise 1 continued
. . .
public static void main (String[] args){
Calc trial = new Calc();
// Frame is invisible by default
trial.setVisible(true);
// main method exits but user
interface
// stays alive
}
}
Top Level Windows
 Top Level Windows are containers that
are not contained by any other containers
 They can be iconified or dragged and
interact with the native windowing system
 Examples: JFrame, JDialog (not
JComponents at all )
Categories of GUI classes
 Swing has a large set of classes that inherit from a
super and abstract class JComponent
 JComponent: The base class for all Swing
components except top-level containers
 Its subclasses present information or interact with
the user
 Examples:labels(JLabels), buttons(JButtons),
textfields(JTextField)
- Containers are some JComponents that are designed to
hold other components (no interaction with the user)
- Examples: JPanel, JScrollPane
Categories of GUI classes
 Swing has a large set of classes that inherit from a
super and abstract class JComponent
 JComponent: The base class for all Swing
components except top-level containers
 Its subclasses present information or interact with
the user
 Examples:labels(JLabels), buttons(JButtons),
textfields(JTextField)
- Containers are some JComponents that are designed to
hold other components (no interaction with the user)
- Examples: JPanel, JScrollPane
Coordinates
 The upper left hand corner of the screen
has coordinates (0,0)
 Like the cartesian system, the value of x
increases from left to right (the x-axis
goes from left to right)
 However, the value of y increases from
top to bottom (the y-axis goes from top to
bottom)
 Measured in pixels (such as 640 by 480)
Frames, Panes and Panels
Colors
 There are 13 predefined colors
 You can access them using Color.x where
x is
 orange, pink, cyan, magenta, yellow, black, blue,
white, gray, lightGray, darkGray, red, green
 You can define your own colors
Color ugly = new Color(30,90,120);
//RGB(red-green-blue); values between 0-255;
Exercise 2: JPanels with
color
 Set the background of the contentPane to white
using
<nameofobject>.setBackground(<color>);
 Create two JPanels in the constructor of Calc
 Set the background color of one to orange; set the
background color of the other to yellow
 Add the two JPanels to the contentPane using
<nameofobject>.add(<objecttobeadded>)
 add the orange JPanel first; NOTE: the order in
which you add your objects determine the way your
program looks
Exercise 2: Answer
package swinglab;
import java.awt.*;
import javax.swing.*;
public class Calc extends JFrame{
private JPanel entryPanel;
private JPanel answerPanel;
public Calc() {
Container cp = getContentPane();
setDefaultCloseOperation(EXIT_ON_CLOSE);
cp.setBackground(Color.white);
setTitle("My Funky Calculator");
setSize(1000,700);
entryPanel = new JPanel();
entryPanel.setBackground(Color.orange);
answerPanel = new JPanel();
answerPanel.setBackground(Color.yellow);
// . . .
Exercise 2: answer
continued
cp.add(entryPanel);
cp.add(answerPanel);
}
public static void main (String[] args){
Calc trial = new Calc();
trial.setVisible(true);
}
}
JLabels, JButtons,
JComboBox etc
 These are subclasses of JComponent
 You create them just as you create other
objects of a class:
JLabel sign = new JLabel ("Sign");
 When created, you need to add them to
the panel:
panel.add(sign);
// panel is the name of a created JPanel
Exercise 3: Adding a
JComboBox
JComboBox
We want to create a JComboBox (drop-down menu):
For items in the menu:- Declare and initialize the
following above the Calc constructor
private JComboBox operation;
public static String ADD_OP = "ADDITION";
public static String SUB_OP = "SUBTRACTION";
public static String MUL_OP = "MULTIPLICATION";
public static String DIV_OP = "DIVISION";
Exercise 3 continued
In Calc Constructor:
 Create a JComboBox:
operation = new JComboBox();
 Add the items in the menu using addItem() :
operation.addItem(ADD_OP);
operation.addItem(SUB_OP);
operation.addItem(MUL_OP);
operation.addItem(DIV_OP);
 Set its background to blue:
operation.setBackground(Color.blue);
 Add the JComboBox to the orange panel:
<nameofORANGEpanel>.add(operation);
Exercise 4: Adding labels,
buttons etc
JLabels
 Declare 2 JLabels: letLabel and answerLabel
 Create the two labels in the constructor using
their constructor that takes a String as an
argument and then set the FOREGROUND color
as follows:
letLabel: "Let's Calculate!" , green
answerLabel: "Answer" , red
 Add:
letLabel to the ORANGE JPanel
answerLabel to the ORANGE JPanel
Exercise 4 continued
JTextFields
 Declare 2 JTextFields: num1 and num2
 In the Calc constructor, create the 2 JTextFields
using their constructor that takes a String and an
int (for size) as arguments:
num1:"1st Number" , 10
num2:"2nd Number", 10
 Set their background color to lightGray
(predefined)
 Add them to the ORANGE JPanel
Exercise 4 continued
JButtons
 Declare 2 JButtons: calculate and quit
 In Calc constructor, create the two JButtons using their
constructor which takes a String as an argument
 calculate: "Calculate"
 quit : "Quit"
 Set their background color as follows:
calculate:pink
quit : create your color
HINT: first create the color then use it
Color leaf = new Color(50,100,50);
<nameofbutton>.setBackground(leaf);
 Add the buttons to the YELLOW JPanel;
Exercise 4 continued
 Compile and run the program.
 Note that the order in which you add objects to
the panel determine their positions
 Go back through the code and make sure that
the objects are added in the following order:
ORANGE JPanel: JLabel letLabel, JTextField
num1, JTextField num2, JComboBox operation,
JLabel answerLabel
YELLOW JPanel: JButton calculate, JButton quit
Exercise 4: answer
package swinglab;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class Calc extends JFrame{
private JLabel letLabel;
private JLabel answerLabel;
private JTextField num1;
private JTextField num2;
private JComboBox operation;
private JButton calculate;
private JButton quit;
private JPanel entryPanel;
private JPanel answerPanel;
letLabel = new JLabel("Let's Calculate!");
entryPanel.add(letLabel);
letLabel.setForeground(Color.GREEN);
num1 = new JTextField("1st Number", 10);
entryPanel.add(num1);
num1.setBackground(Color. LIGHT_GRAY);
num2= new JTextField("2nd Number", 10);
entryPanel.add(num2);
num2.setBackground(Color.LIGHT_GRAY);
operation = new JComboBox();
operation.addItem(ADD_OP);
operation.addItem(SUB_OP);
operation.addItem(MUL_OP);
operation.addItem(DIV_OP);
entryPanel.add(operation);
operation.setBackground(Color.BLUE);
answerLabel = new JLabel("Answer");
entryPanel.add(answerLabel);
answerLabel.setForeground(Color.red);
calculate = new JButton("Calculate");
calculate.setBackground(Color.pink);
answerPanel.add(calculate);
quit = new JButton("Quit");
answerPanel.add(quit);
Color quitter = new Color(50,100,50);
quit.setBackground(quitter);
cp.add(entryPanel);
cp.add(answerPanel);
}
public static void main(String[] args){
Calc trial = new Calc();
trial.setVisible(true);
}
}
Layout Manager
 Layout management is the process of
determining the size and location of a
container's components.
 Java containers do not handle their own layout.
They delegate that task to their layout manager,
an instance of another class.
 If you do not like a container's default layout
manager, you can change it.
Container content = getContentPane();
content.setLayout( new FlowLayout() );
FlowLayout
 FlowLayout, the simplest of the managers,
simply adds components left to right until it
can fit no more within its container's width.
 It then starts a second line of components,
fills that, starts a third, etc.
 Each line is centered in the container
 FlowLayout respects each component's
preferred size and will use it to override a
size set by setSize.
 FlowLayout is the default layout manager
for JPanel
BorderLayout Zones
 A border layout divides the container into five regions;
each region may contain only one component
 BorderLayout is the default LayoutManager for the
contentpane of a JFrame
North
South
West East
Center
Using Layout Managers
BorderLayout
<nameofcontainer>.setLayout(new BorderLayout());
When adding components to the container:
<nameofcontainer>.add(<nameofcomponent>,
BorderLayout.REGION);
where REGION is either NORTH, SOUTH, WEST,
CENTER OR EAST.
JPanel panel = new JPanel(); // default
// FlowLayout
panel.setLayout(new BorderLayout());
panel.add(button,BorderLayout.NORTH);
Using Layout Managers
FlowLayout
<nameofcontainer>.setLayout(new FlowLayout());
When adding components to the container:
<nameofcontainer>.add(<nameofcomponent>);
JPanel panel = new JPanel(); // default
// FlowLayout
//following line is redundant
panel.setLayout(new FlowLayout());
panel.add(button);
Exercise 5: Setting
Layouts
 Set the layout of the contentpane to
BorderLayout
 Add the ORANGE panel to the north
region of the contentpane
 Add the YELLOW panel to the south
region of the contentpane
Exercise 5: Answer
. . .
public Calc() {
Container cp = getContentPane();
setDefaultCloseOperation(EXIT_ON_CLOSE);
cp.setLayout(new BorderLayout());
cp.setBackground(Color.white);
setTitle("My Funky Calculator");
setSize(XSIZE,YSIZE);
. . .
cp.add(entryPanel, BorderLayout.NORTH);
cp.add(answerPanel,BorderLayout.SOUTH);
}
pack()
 pack() method rearranges components
such that any unused space is not shown
 Add pack(); to the constructor of Calc.
Make it the last statement in the
constructor
 Have you noticed a difference?
Summary
 When creating GUI, a JFrame is used; it interacts
with the native system
 A contentPane is automatically created when a
JFrame is created. It has 5 zones where you can
add a component (default layout is BorderLayout)
 JPanel is the workhorse of most complicated
interfaces. It is
 a good all purpose container
 the standard drawing surface
 Swing containers have default layout managers but
you can always change them
 Swing is HUGE! You must explore it further.
The End of the 16th
Lecture
Lecture 17
Swing Event Model
The Java Event Model
 In the last lecture, we learned how to
construct a GUI to present
information to the user.
 But how do GUIs interact with
users? How do applications
recognize when the user has done
something?
package swinglab;
import java.awt.*;
import javax.swing.*;
public class ClickReporter extends JFrame {
public ClickReporter() {
JButton myButton = new JButton("Click here");
Container cp = getContentPane();
cp.add(myButton);
setTitle("Click Printer");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
show();
}
public static void main(String[] args) {
ClickReporter cr = new ClickReporter();
}
}
ClickReporter
ClickPrinter Listener
package swinglab;
import java.awt.event.*;
class ClickPrinter implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button was pressed");
}
}
Adding a Listener
public ClickReporter() {
JButton myButton = new JButton("Click here");
ClickPrinter printer = new ClickPrinter();
click.addActionListener(printer);
Container cp = getContentPane();
cp.add(myButton);
setTitle("Click Printer");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
show();
}
ClickReporter
 Each time you click the button a
message is displayed in a console
window.
Button was pressed
Click here
Event Handling Diagram
e.g. button,
menu,
text fields
Event Handling
 To be able to handle events in Java we
need 3 things:
 event sources
 event objects
 event listeners
Event Sources
 Event sources are components that can
recognize user action: menus, buttons, text
fields etc.
 Event sources have methods to add event
listeners to them like addActionListener
 Event source reports on events and notifies
all its listeners
Event Source
 In our ClickReporter class we create an event
source, a JButton called myButton:
JButton myButton = new JButton("Click here");
Click here
Event Objects
 Objects that represent a user action
(e.g. mouse click) – contain detailed
information about the event.
 When an event happens an event
source sends an event object to its
event listeners
 EventObject is the superclass
 ActionEvent, MouseEvent, etc. are
the subclasses that we use
Event Objects
 In our example, the event source –
JButton myButton generates an
event object representing a mouse click.
 We are not going into details of
EventObjects – we will need them
only as arguments to the method
actionPerformed in event listeners.
Event Listeners
 Event listeners are objects that respond
when an event occurs
 Any object , whose class implements the
ActionListener interface, can be an
event listener.
 If the event listener has been added to an
event source, the listener will be called
when an event occurs on that source.
ActionListener interface
 Look it up at the API in the package
java.awt.event:
public interface ActionListener
extends EventListener {
public void actionPerformed(ActionEvent e);
}
Event Listener
In ClickReporter class we have an event
listener – ClickPrinter object called printer:
ClickPrinter printer = new ClickPrinter();
and add this listener to our JButton click:
click.addActionListener(printer);
 create an event source:
JButton myButton = new JButton("Click here");
 create an event listener:
ClickPrinter printer = new ClickPrinter();
 add listener to the source:
click.addActionListener(printer);
 Add the following data fields to your
ClickReporter class:
private JLabel counterLabel;
private int counter = 0;
 Add the following three lines to the
ClickReporter constructor:
cp.setLayout(new FlowLayout());
ClickCounter cc = new ClickCounter(this);
click.addActionListener(cc);
 Add these lines to your constructor:
counterLabel = new JLabel(
"The number of clicks is 0");
cp.add(counterLabel);
 Add this method to ClickReporter:
void incrementCounter(){
counterLabel.setText(
"The number of clicks is " +
(++counter));
pack();
}
In your swinglab package create ClickCounter:
package swinglab;
import java.awt.event.*;
class ClickCounter implements ActionListener {
private ClickReporter clickReporter;
ClickCounter(ClickReporter c) {
clickReporter = c;
}
public void actionPerformed(ActionEvent e){
clickReporter.incrementCounter();
}
}
ClickCounter Diagram
JButton
ClickCounter
ClickReporter
actionPerformed
incrementCounter
 Button is pressed and
notifies ClickCounter
 ClickCounter tells
ClickReporter to
increment its counter
A Calculator Listener
package swinglab;
import java.awt.event.*;
class CalcListener implements ActionListener {
private Calc calculator;
CalcListener(Calc c) { calculator = c; }
public void actionPerformed(ActionEvent e) {
calculator.calculatePressed();
}
}
void calculatePressed() {
double n1 = Double.parseDouble(num1.getText());
double n2 = Double.parseDouble(num2.getText());
String op = (String)operation.getSelectedItem();
double ans;
if (op.equals(Calc.ADD_OP)) ans = n1 + n2;
else if (op.equals(Calc.SUB_OP)) ans = n1 - n2;
else if (op.equals(Calc.MUL_OP)) ans = n1 * n2;
else ans = n1 / n2;
answerLabel.setText("Answer: " + ans);
pack();
}
 Add this method to Calc class:
Add the Calc Listener
 In the Calc constructor, add an
instance of CalcListener as a
listener to the calculate button
CalcListener cl = new CalcListener(this);
calculate.addActionListener(cl);
Quiz Question 1
 Q: It's annoying to make a separate
class for each listener. If any class
can implement an interface, can't
Calc implement ActionListener
and listen for the events itself?
 A: Yes
Quiz Question 2
 Q: Is it a good idea to have Calc be a
listener for itself?
 A: No. Calc is public, and if Calc
implements ActionListener, then
any outside class can use Calc to listen
for unrelated events. Calc is only
designed to handle Calc 's own events.
Uh oh . . .
 What happens when you type
letters into the textfields and click
the calculate button?
 Exceptions are thrown!
Exception Handling
 Catch those exceptions and display an
error message window describing the
error to the user.
 To show the error message window
use the method
JOptionPane.showMessageDialog
 Hint: the parentComponent should be
the Calc object itself
Solution
void calculatePressed() {
double n1 = 0, n2 = 0;
try {
n1 = Double.parseDouble(num1.getText());
n2 = Double.parseDouble(num2.getText());
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog(this,
"Must type two numbers, dummy!",
"Not Numbers!", JOptionPane.ERROR_MESSAGE);
}
String op = (String)operation.getSelectedItem();
double ans;
if (op.equals(Calc.ADD_OP)) ans = n1 + n2;
else if (op.equals(Calc.SUB_OP)) ans = n1 - n2;
else if (op.equals(Calc.MUL_OP)) ans = n1 * n2;
else ans = n1 / n2;
answerLabel.setText("Answer: " + ans);
}
Lecture 18
Collections - Part 1
Collections API
 The package java.util is often called
the "Collections API"
 Extremely useful classes that you must
understand to be a competent Java
programmer
 Divided into three main types of
collections: lists, sets, and maps
Collection Definitions
 list – an ordered collection of elements
that can have duplicates
 set – an unordered collection of elements
with no duplicates
 map – an association between keys and
values. Maps each key to a single value.
Interface Hierarchy
 Collections API organizes its classes into
a hierarchy of interfaces
Collection Map
List Set
Abstract Class Hierarchy
 Abstract collection classes provide skeletal
implementations of the interfaces
 To implement your own collection, just
subclass one of the abstract classes and
implement the few abstract methods
 No need to implement the entire interface
from scratch.
Concrete Collection
Classes
 The non-abstract (concrete) classes in the
collections API provide good
implementations of the interfaces
 Use these unless you really need to
implement your own.
 The most widely used are ArrayList,
LinkedList, HashSet, and HashMap
Collection
Map
List
Set
Abstract
Collection
Abstract
Map
Abstract
Set
Abstract
List
HashMap
Abstract
SequentialList
LinkedList
HashSet ArrayList
Classes
Interfaces
Lists
 list – an ordered collection of elements
that can have duplicates
 The List interface specifies the
behavior of a list collection.
 API provides two implementations of a
list: ArrayList and LinkedList
Collections Quiz 1
1. What type of collection would I use to
store the players on the Ghana football
team?
2. The schedule of the teams opponents for
the Ghana football team?
3. T/F. All classes in the Collections API
implement Collection?
4. T/F. If a class does not implement
Comparable the elements cannot be
sorted with Collections.sort
set
list
false, maps do not
false, w/ Comparator
Collections Quiz 2
 What's wrong with the equals method below?
class Person {
private int age;
private String name;
public boolean equals(Object o) {
if (!(o instanceof Person)) return
false;
Person p = (Person)o;
return age == p.age && name ==
p.name
}
name.equals(p.name)
The Equals Method: Pop
Quiz
 What will the following code print out?
Double a1 = new Double(95.0);
Double a2 = new Double(95.0);
ArrayList grades = new ArrayList();
grades.add(a1);
System.out.println(grades.contains(a2));
a1 != a2 but true because a1.equals(a2)
Two Forms of Equality
 Reference Equality
 objects are the same exact object
 test with == operator
 Logical Equality
 objects are logically equivalent
 test with the equals method
 the object determines what it means for other
objects to be logically equivalent to it
Equals Method
 Every class inherits an equals method from
the class Object
 The Object equals method just tests for
reference equality (==)
 For nearly all the classes you write, you
should override the .equals method to
provide a more useful test of logical equality
4 Steps to .equals Heaven
1. Use the instanceof keyword operator to
check that the argument is the correct
type. (This returns false if the argument
is null.)
2. If it is not of the correct type, return false;
otherwise cast the argument to that type
3. Check equality of each primitive data
field of the argument using ==
4. Check equality of each object data field
of the argument using .equals
ColorPoint .equals
public class ColorPoint {
private int x, y;
private Color c;
public boolean equals(Object o) {
if (!(o instanceof ColorPoint))
{
return false;
}
ColorPoint cp = (ColorPoint)o;
return x == cp.x && y == cp.y &&
c.equals(cp.c);
}
}
Comparing Objects
 Sometimes we want to test not only
equality, but whether one object is greater
than or less than another object.
 If a class implements the Comparable
interface, it can be compared in this way
 Or if there is a Comparator which
compares instances of that class
Comparable
 The Comparable interface has only a single
method compareTo
 If the object is greater than the argument, then
compareTo returns a positive integer
 If the object is less then the argument, then
compareTo returns a negative integer
 If the argument is equal, compareTo returns 0
Comparator
 The Comparator interface only has a single
method compareTo
 If the first argument is greater than the second,
compareTo returns a positive integer
 If the first argument is less than the second,
compareTo returns a negative integer
 If the arguments are equal, compareTo returns 0
Comparable Person
public class Person implements
Comparable {
private int age;
private String name;
// sorts people first by age, then
by name
public int compareTo(Object o) {
Person p = (Person)o;
if (age != p.age) return age –
p.age;
else return
Person Comparator
public class PersonComparator
implements Comparator
{
// sorts people first by age, then by
name
public int compareTo(Object o1, Object
o2) {
Person p1 = (Person)o1;
Person p2 = (Person)o2;
if (p1.age != p2.age) return p1.age –
p2.age;
Collections Class
 If an class implements Comparable or
has a Comparator, Lists of that class
can be sorted with Collections.sort
 The class Collections provides a lot
of useful static methods that operate on
and return collections.
 Look there before writing your own.
Lecture 19
Collections 2
Sets and Hashing
Overview of Sets
 Recall from Collections 1 that a set is an
unordered collection with no duplicates.
 Which of the following is sure to be a set?
 Students in this class
 Coins in my pocket
 Letters in the alphabet
 The Collections API provides a Set
Interface for you.
Yes
No, can have 2 of the same coin
Yes
The Set Interface
 The set interface provides the five
basic operations to manipulate sets.
 Add an element
 Remove an element
 Find the size of the set
 List all the elements in the set
 Check if an element is in the set
The Set Interface
 add(x)
 Adds element x to the set. If x was already
present, nothing changes.
 remove(x)
 Removes x from the set if x was present, else
leaves the set unchanged.
 size()
 Returns an int indicating the current size of
the set
The Set Interface
 iterator()
 Returns an Iterator object over the elements
in the set.
 This provides a way to ‘look’ at all the
elements in the set in turn. (Note: Remember
that the set has no specified order.)
 contains(x)
 Returns a boolean representing whether or
not the set contains x.
Hashing
 Hashing is a technique that can save on
search time and storage space.
 Java Objects such as HashSet and
HashMap are based on this technique.
 This section will teach you how these
classes work and how to use them
effectively.
Hashing Example
 Imagine each student at this school has
a sheet with their info on it.
 Someone wants to know whether or not
a person is a student here.
 If there is no order to the sheets we
would have to look through all of them.
 Can we improve upon this to reduce the
search time?
Hashing Example
 Lets say we have two bins, one for sheets of
male students and one for female.
 If we are told the sex of the person we need only
check in one bin.
 We could do the same for any characteristic
such as age, weight, eye color.
 Some of these will be more useful than others
depending on how many bins there are and how
many sheets in each bin.
Hashing Example
 An important property is that each bin has
approx the same number of student sheets.
 Suppose we want 100 bins. Which of the
following do you think has the above
property?
 Bin for each age from 1 – 100 years
 Bin for each height 100 – 199 cm
 Bin for each last two digits of phone no.
Hash Code
 A hash code is an integer associated with an object
that can be derived from the object.
 Every object in Java has a hashCode() method that
returns an int.
 Classes such as HashSet and HashMap use the
number to store objects in bins just like our student
example.
 If we call contains(x) on a HashSet, instead of
looking through the whole set for x, Java will only
look in the bin corresponding to x.hashcode()
Hash Code Problem
 As described, hashing divides elements
into many bins for quick retrieval and
lookup.
 What could happen if two equal elements
do not have the same hash code?
 You could put an element in a bin and
not be able to find it again because you
look in the wrong bin!
hashCode() and equals()
 If two elements are equal we need them
to map to the same bin!
 This must be true of any hash code:
x.equals(y) implies x.hashCode() =
y.hashCode()
 When you override hashCode you must
override equals
How to write hashCode()
 Return some computation on the hash
codes of each of the fields:
public class Student {
String name;
int year;
public int hashCode() {
return 7 * name.hashCode() +
year + 33;
}
}

More Related Content

PPTX
Java (1).ppt seminar topics engineering
PPT
Java SpringMVC SpringBOOT (Divergent).ppt
PPTX
JAVA Module 1______________________.pptx
PPT
skill lab-java interview preparation questions.ppt
PDF
Java Programming
PPT
Presentation on programming language on java.ppt
PPTX
Java fundamentals
PPTX
LECTURE 2 -Object oriented Java Basics.pptx
Java (1).ppt seminar topics engineering
Java SpringMVC SpringBOOT (Divergent).ppt
JAVA Module 1______________________.pptx
skill lab-java interview preparation questions.ppt
Java Programming
Presentation on programming language on java.ppt
Java fundamentals
LECTURE 2 -Object oriented Java Basics.pptx

Similar to Modern_2.pptx for java (20)

PPT
Java Simple Introduction in single course
PPT
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
PPTX
Chapter-introduction about java programming
PPT
CSL101_Ch1.ppt Computer Science
PPT
Programming with Java by Faizan Ahmed & Team
PPT
Introduction to java programming with Fundamentals
DOC
java handout.doc
PPT
Java Concepts with object oriented programming
PPT
java programming for engineering students_Ch1.ppt
PPT
Mobile computing for Bsc Computer Science
PPT
Programming with Java - Essentials to program
PDF
PPT
java01.ppt
PPT
JAVA ppt tutorial basics to learn java programming
PPT
PPTX
Introduction to java Programming Language
PDF
Core Java Tutorial
PPTX
Chapter 2 java
ODP
Synapse India Reviews
PPTX
Java programmingjsjdjdjdjdjdjdjdjdiidiei
Java Simple Introduction in single course
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
Chapter-introduction about java programming
CSL101_Ch1.ppt Computer Science
Programming with Java by Faizan Ahmed & Team
Introduction to java programming with Fundamentals
java handout.doc
Java Concepts with object oriented programming
java programming for engineering students_Ch1.ppt
Mobile computing for Bsc Computer Science
Programming with Java - Essentials to program
java01.ppt
JAVA ppt tutorial basics to learn java programming
Introduction to java Programming Language
Core Java Tutorial
Chapter 2 java
Synapse India Reviews
Java programmingjsjdjdjdjdjdjdjdjdiidiei
Ad

Recently uploaded (20)

PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
top salesforce developer skills in 2025.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Reimagine Home Health with the Power of Agentic AI​
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Upgrade and Innovation Strategies for SAP ERP Customers
PTS Company Brochure 2025 (1).pdf.......
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Softaken Excel to vCard Converter Software.pdf
Operating system designcfffgfgggggggvggggggggg
Design an Analysis of Algorithms II-SECS-1021-03
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Understanding Forklifts - TECH EHS Solution
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Wondershare Filmora 15 Crack With Activation Key [2025
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
top salesforce developer skills in 2025.pdf
ai tools demonstartion for schools and inter college
How Creative Agencies Leverage Project Management Software.pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Ad

Modern_2.pptx for java

  • 2. What is a Computer Program?  For a computer to be able to do anything (multiply, play a song, run a word processor), it must be given the instructions to do so.  A program is a set of instructions written by humans for computers to perform tasks.  The instructions are written in programming languages such as C, C++, Java, etc.
  • 3. Recipe Analogy Comparing a computer program to a food recipe Food Recipe  a chef writes a set of instructions called a recipe  the recipe requires specific ingredients  the cook follows the instruction step-by-step  the food will vary depending on the amount of ingredients and the cook Computer Program  a programmer writes a set of instructions called a program  the program requires specific inputs  the computer follows the instructions step-by-step  the output will vary depending on the values of the inputs and the computer
  • 4. Compiling Programs  Computers do not understand the languages (C++, Java, etc) that programs are written in.  Programs must first be compiled (converted) into machine code that the computer can run.  A compiler is a program that translates a programming language into machine code.
  • 5. Running Programs  All programs follow a simple format: Input Execution Output  Inputs can be from users, files, or other computer programs  Outputs can take on many forms: numbers, text, graphics, sound, or commands to other programs
  • 6. Multiple Compilers  Because different operating systems (Windows, Macs, Unix) require different machine code, you must compile most programming languages separately for each platform. program compiler compiler compiler Win MAC Unix
  • 7.  Java is a little different.  Java compiler produces bytecode not machine code.  Bytecode can be run on any computer with the Java interpreter installed. Java Program compiler Java Bytecode Win MAC Unix Interpreter Java Interpreter
  • 8. Advantages and Disadvantages of Java Advantages:  Java is platform independent. Once it's compiled, you can run the bytecode on any machine with a Java interpreter. You do not have to recompile for each platform.  Java is safe. Certain common programming bugs and dangerous operations are prevented by the language and compiler.  Java standardizes many useful operations like managing network connections and providing graphical user interfaces. Disadvantages:  Running bytecode through the interpreter is not as fast as running machine code, which is specific to that platform.  Because it is platform independent, it is difficult to use platform specific features (e.g., Windows taskbar, quick launch) in Java.  Java interpreter must be installed on the computer in order to run Java programs.
  • 9. Your First Java Program  Open your text-editor and type the following piece of Java code exactly: class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }  Save this file as HelloWorld.java (watch capitalization) in the following directory: c:java
  • 10. Compiling and Running Your First Program  Open the command prompt in Windows  To run the program that you just wrote, type at the command prompt: cd c:java  Your command prompt should now look like this: c:java>  To compile the program that you wrote, you need to run the Java Development Tool Kit Compiler as follows: At the command prompt type: c:java> javac HelloWorld.java  You have now created your first compiled Java program named HelloWorld.class  To run your first program, type the following at the command prompt: c:java>java HelloWorld Although the file name includes the .class extension , this part of the name must be left off when running the program with the Java interpreter.
  • 12. Object-Oriented Programming  Java is an object-oriented programming language  For the rest of this lecture, we’ll introduce you to the basic principles of object-oriented programming.  We won’t be using these principles immediately, but they will become important over the next few weeks.
  • 13. OOP Concepts  In object-oriented programming (OOP), programs are organized into objects  The properties of objects are determined by their class  Objects act on each other by passing messages
  • 14. Object  Definition: An object is a software bundle that has State and Behavior.  Software Objects are often used to model real-world objects.  Example: dogs have states (name, color, hungry, breed) and behaviors (bark, fetch, and wag tail).
  • 15. Object Examples  Example 1: Dogs  States: name, color, breed, and “is hungry?”  Behaviors: bark, run, and wag tail  Example 2: Cars  States: color, model, speed, direction  Behaviors: accelerate, turn, change gears
  • 16. Class  Definition: A class is a blueprint that defines the states and the behaviors common to all objects of a certain kind.  In the real world, you often have many objects of the same kind. For example, a guard dog, herding dog, snoop dog . . .  Even though all dogs have four legs, and bark, each dog’s behavior is independent of other dogs.  For example: Dog #1 is a black Poodle, Dog #2 is a red Irish Setter
  • 17. Message  Definition: Software objects interact and communicate with each other by sending messages to each other.  Example: when you want your dog to gather a herd of goats, you whistle and send him out.
  • 18. Summary of OOP  When writing an object-oriented program, we define classes, which describe categories of objects, and the states and behaviors that they have in common.  We then create objects which belong to classes, and share the common features of their class.  Objects interact with each other by passing messages.  You will be creating your own classes and objects soon!
  • 19. Lecture 2 Variables and Primitive Data Types
  • 20. What is a Variable?  Variables are places where information can be stored while a program is running.  Their values can be changed at any point over the course of a program
  • 21. Creating Variables  To create a variable, declare its name and the type of information that it will store.  The type is listed first, followed by the name.  Example: a variable that stores an integer representing the highest score on an exam could be declared as follows: int highScore ; type name
  • 22. Creating Variables (continued)  Now you have the variable (highScore), you will want to assign a value to it.  Example: the highest score in the class exam is 98. highScore = 98;  Examples of other types of variables: String studentName; boolean gameOver;
  • 23. Naming Variables  The name that you choose for a variable is called an identifier. In Java, an identifier can be of any length, but must start with: a letter (a – z), a dollar sign ($), or, an underscore ( _ ).  The rest of the identifier can include any character except those used as operators in Java such as + , - , * .  In addition, there are certain keywords reserved (e.g., "class") in the Java language which can never be used as identifiers.
  • 24.  Java is a case-sensitive language – the capitalization of letters in identifiers matters. A rose is not a Rose is not a ROSE  It is good practice to select variable names that give a good indication of the sort of data they hold  For example, if you want to record the size of a hat, hatSize is a good choice for a name whereas qqq would be a bad choice Naming (Continued)
  • 25.  When naming a variable, the following convention is commonly used:  The first letter of a variable name is lowercase  Each successive word in the variable name begins with a capital letter  All other letters are lowercase  Here are some examples: pageCount loadFile anyString threeWordVariable
  • 26. POP QUIZ  Which of the following are valid variable names? 1)$amount 2)6tally 3)my*Name 4)salary 5)_score 6)first Name 7)total#
  • 27. Statements  A statement is a command that causes something to happen.  All statements in Java are separated by semicolons ;  Example: System.out.println(“Hello, World”);  You have already used statements to create a variable and assign it a value.
  • 28. Variables and Statements  One way is to declare a variable and then assign a value to it with two statements: int e; // declaring a variable e = 5; // assigning a value to a variable  Another way is to write a single initialization statement: int e = 5; // declaring AND assigning
  • 29. Java is a Strongly-Typed Language  All variables must be declared with a data type before they are used.  Each variable's declared type does not change over the course of the program.  Certain operations are only allowed with certain data types.  If you try to perform an operation on an illegal data type (like multiplying Strings), the compiler will report an error.
  • 30. Primitive Data Types  There are eight built-in (primitive) data types in the Java language  4 integer types (byte, short, int, long)  2 floating point types (float, double)  Boolean (boolean)  Character (char) **see Appendix II: Summary of Primitive Data Types for a complete table of sizes and formats**
  • 31. Integer Data Types  There are four data types that can be used to store integers.  The one you choose to use depends on the size of the number that we want to store.  In this course, we will always use int when dealing with integers. Data Type Value Range byte -128 to +127 short -32768 to +32767 int -2147483648 to +2147483647 long -9223372036854775808 to +9223372036854775807
  • 32.  Here are some examples of when you would want to use integer types: - byte smallValue; smallValue = -55; - int pageCount = 1250; - long bigValue = 1823337144562L; Note: By adding an L to the end of the value in the last example, the program is “forced” to consider the value to be of a type long even if it was small enough to be an int
  • 33. Floating Point Data Types  There are two data types that can be used to store decimal values (real numbers).  The one you choose to use depends on the size of the number that we want to store.  In this course, we will always use double when dealing with decimal values. Data Type Value Range float 1.4×10-45 to 3.4×1038 double 4.9×10-324 to 1.7×10308
  • 34.  Here are some examples of when you would want to use floating point types:  double g = 7.7e100 ;  double tinyNumber = 5.82e-203;  float costOfBook = 49.99F;  Note: In the last example we added an F to the end of the value. Without the F, it would have automatically been considered a double instead.
  • 35. Boolean Data Type  Boolean is a data type that can be used in situations where there are two options, either true or false.  Example: boolean monsterHungry = true; boolean fileOpen = false;
  • 36. Character Data Types  Character is a data type that can be used to store a single characters such as a letter, number, punctuation mark, or other symbol.  Example:  char firstLetterOfName = 'e' ;  char myQuestion = '?' ;  Note that you need to use singular quotation marks when assigning char data types.
  • 37. Introduction to Strings  Strings consist of a series of characters inside double quotation marks.  Examples statements assign String variables: String coAuthor = "John Smith"; String password = "swordfish786";  Strings are not one of the primitive data types, although they are very commonly used.  Strings are constant; their values cannot be changed after they are created.
  • 38. POP QUIZ What data types would you use to store the following types of information?: 1)Population of Ethiopia 2)Approximation of π 3)Open/closed status of a file 4)Your name 5)First letter of your name 6)$237.66 int double boolean String char double
  • 39. Appendix I: Reserved Words The following keywords are reserved in the Java language. They can never be used as identifiers: abstract assert boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceo f int interfac e long native new package private protected public return short static strictfp super switch synchronize d this throw throws transient try void violate while
  • 40. Appendix II: Primitive Data Types The following tables show all of the primitive data types along with their sizes and formats: Data Type Description byte Variables of this kind can have a value from: -128 to +127 and occupy 8 bits in memory short Variables of this kind can have a value from: -32768 to +32767 and occupy 16 bits in memory int Variables of this kind can have a value from: -2147483648 to +2147483647 and occupy 32 bits in memory long Variables of this kind can have a value from: -9223372036854775808 to +9223372036854775807 and occupy 64 bits in memory Integers
  • 41. Appendix II: Primitive Data Types (cont) Data Type Description float Variables of this kind can have a value from: 1.4e(-45) to 3.4e(+38) double Variables of this kind can have a value from: 4.9e(-324) to 1.7e(+308) Real Numbers char Variables of this kind can have a value from: A single character boolean Variables of this kind can have a value from: True or False Other Primitive Data Types
  • 43. What are Operators? • Operators are special symbols used for – mathematical functions – assignment statements – logical comparisons • Examples: 3 + 5 // uses + operator 14 + 5 – 4 * (5 – 3) // uses +, -, * operators • Expressions can be combinations of variables, primitives and operators that result in a value
  • 44.  There are 5 different groups of operators:  Arithmetic operators  Assignment operator  Increment/Decrement operators  Relational operators  Conditional operators The Operator Groups
  • 45. Arithmetic Operators  Java has 6 basic arithmetic operators + add - subtract * multiply / divide % modulo (remainder) ^ exponent (to the power of)  Order of operations (or precedence) when evaluating an expression is the same as you learned in school (PEMDAS).
  • 46. Order of Operations  Example: 10 + 15 / 5;  The result is different depending on whether the addition or division is performed first (10 + 15) / 5 = 5 10 + (15 / 5) = 13 Without parentheses, Java will choose the second case  Note: you should be explicit and use parentheses to avoid confusion
  • 47. Integer Division  In the previous example, we were lucky that (10 + 15) / 5 gives an exact integer answer (5).  But what if we divide 63 by 35?  Depending on the data types of the variables that store the numbers, we will get different results.
  • 48. Integer Division Example  int i = 63; int j = 35; System.out.println(i / j); Output: 1  double x = 63; double y = 35; System.out.println(x / y); Ouput: 1.8  The result of integer division is just the integer part of the quotient!
  • 49. Assignment Operator  The basic assignment operator (=) assigns the value of var to expr var = expr ;  Java allows you to combine arithmetic and assignment operators into a single operator.  Examples: x = x + 5; is equivalent to x += 5; y = y * 7; is equivalent to y *= 7;
  • 50. Increment/Decrement Operators count = count + 1; can be written as: ++count; or count++; ++ is called the increment operator. count = count - 1; can be written as: --count; or count--; -- is called the decrement operator.
  • 51. The increment/decrement operator has two forms:  The prefix form ++count, --count first adds 1 to the variable and then continues to any other operator in the expression int numOranges = 5; int numApples = 10; int numFruit; numFruit = ++numOranges + numApples; numFruit has value 16 numOranges has value 6  The postfix form count++, count-- first evaluates the expression and then adds 1 to the variable int numOranges = 5; int numApples = 10; int numFruit; numFruit = numOranges++ + numApples; numFruit has value 15 numOranges has value 6
  • 52. Relational (Comparison) Operators operation is true when . . . a > b a is greater than b a >= b a is greater than or equal to b a == b a is equal to b a != b a is not equal to b a <= b a is less than or equal to b a < b a is less than b • Relational operators compare two values • Produces a boolean value (true or false) depending on the relationship
  • 53. int x = 3; int y = 5; boolean result; 1) result = (x > y); now result is assigned the value false because 3 is not greater than 5 2) result = (15 == x*y); now result is assigned the value true because the product of 3 and 5 equals 15 3) result = (x != x*y); now result is assigned the value true because the product of x and y (15) is not equal to x (3) Examples of Relational Operations
  • 54. Conditional Operators Symbol Name && AND || OR ! NOT  Conditional operators can be referred to as boolean operators, because they are only used to combine expressions that have a value of true or false.
  • 55. Truth Table for Conditional Operators x y x && y x || y !x True True True True False True False False True False False True False True True False False False False True
  • 56. boolean x = true; boolean y = false; boolean result; 1. Let result = (x && y); now result is assigned the value false (see truth table!) 2. Let result = ((x || y) && x); (x || y) evaluates to true (true && x) evaluates to true now result is assigned the value true Examples of Conditional Operators
  • 57.  Examples: (a && (b++ > 3)) (x || y)  Java will evaluate these expressions from left to right and so will evaluate a before (b++ > 3) x before y  Java performs short-circuit evaluation: it evaluates && and || expressions from left to right and once it finds the result, it stops. Using && and ||
  • 58. Short-Circuit Evaluations (a && (b++ > 3)) What happens if a is false?  Java will not evaluate the right-hand expression (b++ > 3) if the left-hand operator a is false, since the result is already determined in this case to be false. This means b will not be incremented! (x || y) What happens if x is true?  Similarly, Java will not evaluate the right-hand operator y if the left-hand operator x is true, since the result is already determined in this case to be true.
  • 59. POP QUIZ 1) What is the value of number? int number = 5 * 3 – 3 / 6 – 9 * 3; 2) What is the value of result? int x = 8; int y = 2; boolean result = (15 == x * y); 3) What is the value of result? boolean x = 7; boolean result = (x < 8) && (x > 4); 4) What is the value of numCars? int numBlueCars = 5; int numGreenCars = 10; int numCars = numGreenCars++ + numBlueCars + ++numGreeenCars; -12 false true 27
  • 60. References  Summary of Java operators http://java.sun.com/docs/books/tutorial/java/nutsandbolts/opsummary.html  Order of Operations (PEMDAS) 1. Parentheses 2. Exponents 3. Multiplication and Division from left to right 4. Addition and Subtraction from left to right
  • 62. Program Flow  Java will execute the statements in your code in a specific sequence, or "flow".  The "flow" of the program and can be described through a "flow diagram": a more sophisticated program a simple program statement statement statement statement statement statement statement statement statement statement
  • 63. What are Control Structures?  Control structures alter the flow of the program, the sequence of statements that are executed in a program.  They act as "direction signals" to control the path a program takes.  Two types of control structures in Java:  decision statements  loops
  • 64. Decision Statements  A decision statement allows the code to execute a statement or block of statements conditionally.  Two types of decisions statements in Java:  if statements  switch statements
  • 65. If Statement if (expression) { statement; } rest_of_program;  expression must evaluate to a boolean value, either true or false  If expression is true, statement is executed and then rest_of_program  If expression is false, statement is not executed and the program continues at rest_of_program
  • 66. If Statement Flow Diagram The if decision statement executes a statement if an expression is true execute statement execute rest_of_program Is expression true? yes no if (expression) { statement1; } rest_of_program
  • 67. If-Else Statement if (expression) { statement1; } else{ statement2; } next_statement;  Again, expression must produce a boolean value  If expression is true, statement1 is executed and then next_statement is executed.  If expression is false, statement2 is executed and then next_statement is executed.
  • 68. If-Else Flow Diagram if (expression){ statement1; } else { statement2; } rest_of_program The if-else decision statement executes a statement if an expression is true and a different statement if it is not true. is “expression” true? execute statement1 execute rest_of_program no yes execute statement2
  • 69. Chained If-Else Statements if (grade == 'A') System.out.println("You got an A."); else if (grade == 'B') System.out.println("You got a B."); else if (grade == 'C') System.out.println("You got a C."); else System.out.println("You got an F.");
  • 70. Switch Statements  The switch statement enables you to test several cases generated by a given expression.  For example: switch (expression) { case value1: statement1; case value2: statement2; default: default_statement; } Every statement after the true case is executed  The expression must evaluate to a char, byte, short or int, but not long, float, or double.
  • 71. y y n n switch (expression){ case value1: // Do value1 thing case value2: // Do value2 thing ... default: // Do default action } // Continue the program expression equals value1? Do value1 thing Do value2 thing Do default action expression equals value2? Continue the program
  • 72. Break Statements in Switch Statements  The break statement tells the computer to exit the switch statement  For example: switch (expression) { case value1: statement1; break; case value2: statement2; break; default: default_statement; break; }
  • 73. switch (expression){ case value1: // Do value1 thing break; case value2: // Do value2 thing break; ... default: // Do default action break; } // Continue the program expression equals value1? expression equals value2? do default action Do value1 thing Do value2 thing break break break Continue the program y y n n
  • 74. Remember the Chained If-Else . . . if (grade == 'A') System.out.println("You got an A."); else if (grade == 'B') System.out.println("You got a B."); else if (grade == 'C') System.out.println("You got a C."); else System.out.println("You got an F.");
  • 75.  This is how it is accomplished with a switch:  if-else chains can be sometimes be rewritten as a “switch” statement.  switches are usually simpler and faster switch (grade) { case 'A': System.out.println("You got an A."); break; case 'B': System.out.println("You got a B."); break; case 'C': System.out.println("You got a C."); break; default: System.out.println("You got an F."); }
  • 76. Loops  A loop allows you to execute a statement or block of statements repeatedly.  Three types of loops in Java: 1. while loops 2. for loops 3. do-while loops (not discussed in this course)
  • 77. The while Loop while (expression){ statement }  This while loop executes as long as the given logical expression between parentheses is true. When expression is false, execution continues with the statement following the loop block.  The expression is tested at the beginning of the loop, so if it is initially false, the loop will not be executed at all.
  • 78.  For example: int sum = 0; int i = 1; while (i <= 10){ sum += i; i++; }  What is the value of sum? 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
  • 79. The for Loop The control of the for loop appear in parentheses and is made up of three parts: 1. The first part, the init_expression,sets the initial conditions for the loop and is executed before the loop starts. 2. Loop executes so long as the loop_condition is true and exits otherwise. 3. The third part of the control information, the increment_expr, is usually used to increment the loop counter. This is executed at the end of each loop iteration. for (init_expr; loop_condition; increment_expr) { statement; }
  • 80.  For example: int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; }  What is the value of sum? 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
  • 81.  Example 3: for(int div = 0; div < 1000; div++){ if(div % 2 == 0) { System.out.println("even: " + div); } else { System.out.println("odd: " + div); } }  What will this for loop do? prints out each integer from 0 to 999, correctly labeling them even or odd
  • 82.  If there is more than one variable to set up or increment they are separated by a comma. for(i=0, j=0; i*j < 100; i++, j+=2) { System.out.println(i * j); }  You do not have to fill all three control expressions but you must still have two semicolons. int n = 0; for(; n <= 100;) { System.out.println(++n); }
  • 83. The while loop Test condition is true? Execute loop statement(?) Next statement y n Initialize count Test condition is true? Execute loop statement(s) Increment count New statement The for loop y n
  • 84. The continue Statement  The continue statement causes the program to jump to the next iteration of the loop. /** * prints out "5689" */ for(int m = 5; m < 10; m++) { if(m == 7) { continue; } System.out.print(m); }
  • 85.  Another continue example: int sum = 0; for(int i = 1; i <= 10; i++){ if(i % 3 == 0) { continue; } sum += i; }  What is the value of sum? 1 + 2 + 4 + 5 + 7 + 8 + 10 = 37
  • 86. The break Statement  We have seen the use of the break statement in the switch statement.  You can also use the break statement to exit the loop entirely. // prints out numbers unless // num is ever exactly 400 while (num > 6) { if(num == 400) { break; } System.out.println(num); num -= 8; }
  • 87. Nested Loops  You can nest loops of any kind one inside another to any depth. What does this print? for(int i = 10; i > 0; i--) { if (i > 7) { continue; } while (i > 3) { if(i == 5) { break; } System.out.println(--i); } System.out.println(i); } 6 5 5 4 3 2 1
  • 88. POP QUIZ 1. In the switch statement, which types can expression evaluate to? 2. What must be used to separate each section of a for statement. 3. Which statement causes a program to skip to the next iteration of a loop. 4. Write a for loop that outputs 100-1 in reverse sequence. 5. Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int semicolons continue
  • 89. Lecture 5 Arrays A way to organize data
  • 90. What are Arrays?  An array is a series of compartments to store data.  Each compartment is appropriately sized for the particular data type the array is declared to store.  An array can hold only one type of data! E.g. int[] can hold only integers char[] can hold only characters
  • 91. Array Visualization primes[0] int[] primes = new int[10]; Specifies an array of variables of type int // An array of 10 integers index values We are creating a new array object The name of the array The array object is of type int and has ten elements primes[1] primes[2] primes[3] primes[4] primes[9]
  • 92. Declaring an Array Variable  Array declarations use square brackets. datatype[] label;  For example: int[] prices; String[] names;
  • 93. Creating a New "Empty" Array Use this syntax: new int[20]  The new keyword creates an array of type int that has 20 compartments  The new array can then be assigned to an array variable: int[] prices = new int[20];  When first created as above, the items in the array are initialized to the zero value of the datatype int: 0 double: 0.0 String: null
  • 94. Array Indexes  Every compartment in an array is assigned an integer reference.  This number is called the index of the compartment  Important: In Java (and most other languages), the index starts from 0 and ends at n-1, where n is the size of the array
  • 95. Accessing Array Elements  To access an item in an array, type the name of the array followed by the item’s index in square brackets.  For example, the expression: names[0] will return the first element in the names array
  • 96. Filling an Array  Assign values to compartments: prices[0] = 6.75; prices[1] = 80.43; prices[2] = 10.02;
  • 97. Constructing Arrays  To construct an array, you can declare a new empty array and then assign values to each of the compartments: String[] names = new String[5]; names[0] = "David"; names[1] = "Qian"; names[2] = "Emina"; names[3] = "Jamal"; names[4] = "Ashenafi";
  • 98. Another Way to Construct Arrays  You can also specify all of the items in an array at its creation.  Use curly brackets to surround the array’s data and separate the values with commas: String[] names = { "David", "Qian", "Emina", "Jamal", "Ashenafi"};  Note that all the items must be of the same type. Here they are of type String.  Another example: int[] powers = {0, 1, 10, 100};
  • 99. Length of array String[] names = { "David", "Qian", "Emina", "Jamal", "Ashenafi" }; int numberOfNames = names.length; System.out.println(numberOfNames); Output: 5  Important: Arrays are always of the same size: their lengths cannot be changed once they are created!
  • 100. Example String[] names = { "Aisha", "Tamara", "Gikandi", "Ato", "Lauri"}; for(int i = 0; i < names.length; i++){ System.out.println("Hello " + names[i] + "."); } Output: Hello Aisha. Hello Tamara. Hello Gikandi. Hello Ato. Hello Lauri.
  • 101. Modifying Array Elements  Example: names[0] = “Bekele"  Now the first name in names[] has been changed from "Aisha" to "Bekele".  So the expression names[0] now evaluates to "Bekele".  Note: The values of compartments can change, but no new compartments may be added.
  • 102. Example int[] fibs = new int[10]; fibs[0] = 1; fibs[1] = 1; for(int i = 2; i < fibs.length; i++) { fibs[i] = fibs[i-2] + fibs[i-1]; }  After running this code, the array fibs[] contains the first ten Fibonacci numbers: 1 1 2 3 5 8 13 21 34 55 Note: array indexes can be expressions
  • 103. Exercise 1  Which of the following sequences of statements does not create a new array? a. int[] arr = new int[4]; b. int[] arr; arr = new int[4]; c. int[] arr = { 1, 2, 3, 4}; d. int[] arr; just declares an array variable
  • 104. Exercise 2  Given this code fragment, int[] data = new int[10]; System.out.println(data[j]);  Which of the following is a legal value of j? a. -1 b. 0 c. 3.5 d. 10 // out of range // legal value // out of range // out of range
  • 105. Exercise 3  Which set of data would not be suitable for storing in an array? a. the score for each of the four quarters of a Football match b. your name, date of birth, and score on your physics test c. temperature readings taken every hour throughout a day d. your expenses each month for an entire year // these are different types
  • 106. Exercise 4  What is the value of c after the following code segment? int [] a = {1, 2, 3, 4, 5}; int [] b = {11, 12, 13}; int [] c = new int[4]; for (int j = 0; j < 3; j++) { c[j] = a[j] + b[j]; } c = [12, 14, 16, 0]
  • 107. 2-Dimensional Arrays  The arrays we've used so far can be thought of as a single row of values.  A 2-dimensional array can be thought of as a grid (or matrix) of values  Each element of the 2-D array is accessed by providing two indexes: a row index and a column index  (A 2-D array is actually just an array of arrays) 0 1 0 8 4 1 9 7 2 3 6 value at row index 2, column index 0 is 3
  • 108. 2-D Array Example  Example: A landscape grid of a 20 x 55 acre piece of land: We want to store the height of the land at each row and each column of the grid.  We declare a 2D array two sets of square brackets: double[][] heights = new double[20][55];  This 2D array has 20 rows and 55 columns  To access the acre at row index 11 and column index 23 user: heights[11][23]
  • 110.  Methods also known as functions or procedures.  Methods are a way of capturing a sequence of computational steps into a reusable unit.  Methods can accept inputs in the form of arguments, perform some operations with the arguments, and then can return a value the is the output, or result of their computations. The Concept of a Method method inputs outputs
  • 111.  Square root is a good example of a method.  The square root method accepts a single number as an argument and returns the square root of that number.  The computation of square roots involves many intermediate steps between input and output.  When we use square root, we don’t care about these steps. All we need is to get the correct output.  Hiding the internal workings of a method from a user but providing the correct answer is known as abstraction Square Root Method
  • 112.  A method has 4 parts: the return type, the name, the arguments, and the body: double sqrt(double num) { // a set of operations that compute // the square root of a number }  The type, name and arguments together is referred to as the signature of the method Declaring Methods type name arguments body
  • 113. The Return Type of a Method  The return type of a method may be any data type.  The type of a method designates the data type of the output it produces.  Methods can also return nothing in which case they are declared void.
  • 114. Return Statements  The return statement is used in a method to output the result of the methods computation.  It has the form: return expression_value;  The type of the expression_value must be the same as the type of the method: double sqrt(double num){ double answer; // Compute the square root of num and store // the value into the variable answer return answer; }
  • 115. Return Statements  A method exits immediately after it executes the return statement  Therefore, the return statement is usually the last statement in a method  A method may have multiple return statements. Can you think of an example of such a case?
  • 116. Brain Teaser Answer  Example: int absoluteValue (int num){ if (num < 0) return –num; else return num; }
  • 117. void Methods  A method of type void has a return statement without any specified value. i.e. return;  This may seem useless, but in practice void is used often.  A good example is when a methods only purpose is to print to the screen.  If no return statement is used in a method of type void, it automatically returns at the end
  • 118. Method Arguments  Methods can take input in the form of arguments.  Arguments are used as variables inside the method body.  Like variables, arguments, must have their type specified.  Arguments are specified inside the paren- theses that follow the name of the method.
  • 119.  Here is an example of a method that divides two doubles: double divide(double a, double b) { double answer; answer = a / b; return answer; } Example Method
  • 120. Method Arguments  Multiple method arguments are separated by commas: double pow(double x, double y)  Arguments may be of different types int indexOf(String str, int fromIndex)
  • 121. The Method Body  The body of a method is a block specified by curly brackets. The body defines the actions of the method.  The method arguments can be used anywhere inside of the body.  All methods must have curly brackets to specify the body even if the body contains only one or no statement.
  • 122. Invoking Methods  To call a method, specify the name of the method followed by a list of comma separated arguments in parentheses: pow(2, 10); //Computes 210  If the method has no arguments, you still need to follow the method name with empty parentheses: size();
  • 123. Static Methods  Some methods have the keyword static before the return type: static double divide(double a, double b) { return a / b; }  We'll learn what it means for a method to be static in a later lecture  For now, all the methods we write in lab will be static.
  • 124. main - A Special Method  The only method that we have used in lab up until this point is the main method.  The main method is where a Java program always starts when you run a class file with the java command  The main method is static has a strict signature which must be followed: public static void main(String[] args) { . . . }
  • 125. main continued class SayHi { public static void main(String[] args) { System.out.println("Hi, " + args[0]); } }  When java Program arg1 arg2 … argN is typed on the command line, anything after the name of the class file is automatically entered into the args array: java SayHi Sonia  In this example args[0] will contain the String "Sonia", and the output of the program will be "Hi, Sonia".
  • 126. class Greetings { public static void main(String args[]) { String greeting = ""; for (int i=0; i < args.length; i++) { greeting += "Jambo " + args[i] + "! "; } System.out.println(greeting); } }  After compiling, if you type java Greetings Alice Bob Charlie prints out "Jambo Alice! Jambo Bob! Jambo Charlie!" Example main method
  • 127. class Factorial { public static void main (String[] args) { int num = Integer.parseInt(args[0])); System.out.println(fact(num)); } static int fact(int n) { if (n <= 1) return 1; else return n * fact(n – 1); } }  After compiling, if you type java Factorial 4 the program will print out 24 Recursive Example
  • 128. class Max { public static void main(String args[]) { if (args.length == 0) return; int max = Integer.parseInt(args[0]); for (int i=1; i < args.length; i++) { if (Integer.parseInt(args[i]) > max) { max = Integer.parseInt(args[i]); } } System.out.println(max); } }  After compiling, if you type java Max 3 2 9 2 4 the program will print out 9 Another Example
  • 129. Summary  Methods capture a piece of computation we wish to perform repeatedly into a single abstraction  Methods in Java have 4 parts: return type, name, arguments, body.  The return type and arguments may be either primitive data types or complex data types (Objects)  main is a special Java method which the java interpreter looks for when you try to run a class file  main has a strict signature that must be followed: public static void main(String args[])
  • 130. Lecture 7 Classes and Objects - Part I
  • 131. What is an Object?  An Object has two primary components:  state – properties of the object  behavior – operations the object can perform  Examples object state behavior dog breed, isHungry eat, bark grade book grades mean, median light on/off switch
  • 132. Objects in Java  A class defines a new type of Object  To create a Object type to represent a light switch . . . class LightSwitch { // state and behavior here }
  • 133. Fields  An Object's state is stored in variables called fields  Fields are declared (and optionally initialized) inside the braces of the class  Light switch example with a field . . . class LightSwitch { boolean on = true; }
  • 134. Methods  An Object's behavior is defined by its methods  Methods, like fields, are written inside the braces of the class  Methods can access the fields (the state) of their object and can change them
  • 135. Light Switch Example class LightSwitch { boolean on = true; // field boolean isOn() { // returns return on; // the state } void switch() { // changes on = !on; // the state } }
  • 136. Constructing Objects  We use the new keyword to construct a new instance of an Object  We can assign this instance to a variable with the same type of the Object  Note: classes define new datatypes ! LightSwitch ls = new LightSwitch();
  • 137. LightSwitch ls = new LightSwitch(); ls.on; ls.isOn(); ls.switch(); Using Fields and Methods  To access the field of an instance of an Object use instance.field  To access the method of an instance use instance.method(arguments)
  • 138. Example Using Light Switch  What does this main method print out? LightSwitch ls = new LightSwitch(); System.out.println(ls.on); ls.switch(); System.out.println(ls.isOn()); true false
  • 139. Person Example class Person { String name = “Jamal”; int age = 26; String getName() { return name; } void setName(String n) { name = n; } int getAge() { return age; } void setAge(int a) { age = a; } boolean smellsBad(){return true;} }
  • 140. Constructing Person Objects  To create an instance of the Person class with a name of "George" and an age of 22  Can we create a Person that has the name George and the age 22 from the moment it is created?  Answer: Yes! Person george = new Person(); george.setName("George"); george.setAge(22);
  • 141. Constructors  Constructors are special methods used to construct an instance of a class  They have no return type  They have the same name as the class of the Object they are constructing  They initialize the state of the Object  Call the constructor by preceding it with the new keyword
  • 142. Person Constructor  Now we can construct George as follows: class Person { String name; int age; Person(String n, int a) { name = n; age = a; } // . . . } Person george = new Person("George", 22);
  • 143. Default Constructor  When you do not write a constructor in a class, it implicitly has a constructor with no arguments and an empty body  Result: every class has a constructor class LightSwitch { // Leaving out the constructor // is the same as . . . LightSwitch() {} }
  • 144. Multiple Constructors  A class can have multiple constructors class LightSwitch { boolean on; LightSwitch() { on = true; } LightSwitch(boolean o) { on = o; } }
  • 145. This Keyword  Instance can refer to itself with the keyword this class LightSwitch { boolean on; LightSwitch() { this.on = true; //(same as on=true;) } LightSwitch(boolean on) { this.on = on; }
  • 146. Cascading Constructors  A constructor can call another constructor with this(arguments) class LightSwitch { boolean on; LightSwitch() { this(true); } LightSwitch(boolean on) { this.on = on; } }
  • 147. Classes Recap  Classes have fields to store the state of the objects in the class and methods to provide the operations the objects can perform.  We construct instances of a class with the keyword new followed by a call a constructor method of the class.  We can assign an instance to a variable with a datatype named the same as the class.  If you do not provide a constructor, the class will have one with no arguments and no statements by default.
  • 148. Apple Example class Apple { String color; double price; Apple(String color, double price) { this.color = color; this.price = price; } Apple(double price) { this("green", price); } String getColor() { return color; } double getPrice() { return price; } void setPrice(double p) { price = p; } }
  • 149. Apple Quiz  What will these lines print out? Apple a = new Apple("red", 100.0); System.out.println(a.getColor()); System.out.println(a.getPrice()); a.setPrice(50.5); System.out.println(a.getPrice()); Apple b = new Apple(74.6); System.out.println(b.getColor()); System.out.println(b.getPrice()); b.setPrice(a.getPrice()); System.out.println(b.getPrice()); red 100.0 50.5 green 74.6 50.5
  • 150. Lecture 8 Classes And Objects II
  • 151. Recall the LightSwitch Class class LightSwitch { boolean on = true; boolean isOn() { return on; } void switch() { on = !on; } }
  • 152. A Different LightSwitch Class class LightSwitch { int on = 1; boolean isOn() { return on == 1; } void switch() { on = 1 - on; } }
  • 153. Abstraction  Both LightSwitch classes behave the same.  We treat LightSwitch as an abstraction: we do not care about the internal code of LightSwitch, only the external behavior  Internal code = implementation  External behavior = interface
  • 154. Why is Abstraction Important?  We can continue to refine and improve the implementation of a class so long as the interface remains the same.  All we need is the interface to an Object in order to use it, we do not need to know anything about how it performs its prescribed behavior.
  • 155. Breaking the Abstraction Barrier  A user of LightSwitch that relied on the boolean field would break if we changed to an integer field class AbstractionBreaker { public static void main(String[] args) { LightSwitch ls = new LightSwitch(); if (ls.on) // now broken! System.out.println("light is on"); else System.out.println("light is off"); } }
  • 156. Public versus Private  Label fields and methods private to ensure other classes can't access them  Label fields and methods public to ensure other classes can access them.  If they are not labeled public or private, for now consider them public.
  • 157. A Better LightSwitch class LightSwitch { private boolean on = true; public boolean isOn() { return on; } public void switch() { on = !on; } }
  • 158. Enforcing the Abstraction Barrier  By labeling the on field private . . .  Now AbstractionBreaker's attempt to access the on field would not have compiled to begin with. class LightSwitch { private boolean on = true; // . . . } if (ls.on) // would never have compiled
  • 159. Equality Quiz 1  Is (a == b) ?  Answer: Yes  Is (g == h) ?  Answer: No int a = 7; int b = 7; Person g = new Person("Jamal", 26); Person h = new Person("Jamal", 26);
  • 160. Primitives vs Objects  Two datatypes in Java: primitives and objects  Primitives: byte, short, int, long, double, float, boolean, char == tests if two primitives have the same value  Objects: defined in Java classes == tests if two objects are the same object
  • 161. References  The new keyword always constructs a new unique instance of a class  When an instance is assigned to a variable, that variable is said to hold a reference or point to that object  g and h hold references to two different objects that happen to have identical state Person g = new Person("Jamal", 26); Person h = new Person("Jamal", 26);
  • 162. Reference Inequality  g != h because g and h hold references to different objects Person g = new Person("Jamal", 26); Person h = new Person("Jamal", 26); "Jamal" 26 "Jamal" 26 g h
  • 163. Reference Equality  greg1 == greg2 because greg1 and greg2 hold references to the same object Person greg1 = new Person("Greg", 23); Person greg2 = greg1; "Greg" 23 greg2 greg1
  • 164. Equality Quiz 2  true or false? a) g == h b) g.getAge() == h.getAge() c) greg1 == greg2 d) greg1.getAge() == greg2.getAge(); Person g = new Person("Jamal", 26); Person h = new Person("Jamal", 26); Person greg1 = new Person("Greg", 23); Person greg2 = greg1; false true true true
  • 165.  You can get information on all in-built Java classes/methods by browsing the Java Application Programming Interface (API)  This documentation is essential to building any substantial Java application  Available on your CD's Java API
  • 166. Lecture 9 Lists and Iterators
  • 167. Arrays Review  Arrays are a simple data structure  Arrays store a row of values of the same type  Primitive types (int, double, etc.) // array that can hold 10 chars char[] letters = new char[10];  Objects (Students, Dates etc.) // array that can hold 3 LightSwitches LightSwitch[] switches = new LightSwitch[3];
  • 168. Arrays Review  Access each value through an index: int[] intArray = new int[20]; intArray[0] = 4 ; intArray[1] = 75;  Array indices start at 0, not 1  first element of intArray is intArray[0]  last element of intArray is intArray[19]  Important: Array lengths cannot be changed once they are declared!
  • 169. Is there something better?  As we learned in the Gradebook lab, because of their fixed length, arrays can be annoying to use.  Is there something like an array but that will handle all the resizing automatically?  YES!
  • 170. ArrayList  ArrayList stores its elements internally as an array.  get method is fast – just retrieves the element at the specified index  add method is slow – may have to create a larger array and copy over all the elements.
  • 171. Linked List Data Structure  A linked list is like a freight train: each link stores an item and is connected to the next link  The list holds a reference to the first (and maybe the last) element Linked List Link 1 Link 2 Link n Item 1 Item 2 Item n . . .
  • 172. LinkedList  LinkedList stores its elements internally in a linked list data structure.  add method is fast – just appends a new link to the end of the list  get method is slow – has to walk down the list retrieve the element at the specified index
  • 173. iterator method  Both ArrayList and LinkedList have a method named iterator  Returns an object of type Iterator  We use the Iterator to iterate over the elements of the list.
  • 174. Iterators  We use Iterators to iterate over the elements of lists  hasNext method returns true when there are more elements to iterate over  next method returns the next element in the iteration
  • 175. Casting  Because the next method returns type Object, you must cast the return value to the actual type of the value.  "Casting" means "promising" the compiler that the object will be of a particular type  This allows you to use methods of the actual type without the compiler complaining
  • 176. GradeBook Iteration class GradeBook { private ArrayList grades; void printGrades() { Iterator gradeIter = grades.iterator(); while(gradeIter.hasNext()) { Double g = (Double)gradeIter.next(); System.out.println(g.doubleValue()); }
  • 177. for(Iterator studentIter = students.iterator(); studentIter.hasNext();) { Student s = studentIter.next(); System.out.println(s.getDescription()); (Student)studentIter.next(); Quiz  Which list implementation is fast when accessing arbitrary indices?  What is wrong with the iteration below? ArrayList Casting
  • 179. public class MyMath { public double PI = 3.14159; public double square (double x) { return x * x; } public static void main(String[ ] args) { MyMath m = new MyMath(); System.out.println("m: value of PI is " + m.PI); System.out.println("m: square of 5 is " + m.square(5)); MyMath n = new MyMath(); System.out.println("n: value of PI is " + n.PI); System.out.println("n: square of 5 is " + n.square(5)); } } MyMath Example
  • 180.  In Example 1, to calculate the square of 5 we need to create an instance of MyMath class: MyMath m = new MyMath();  Then we invoke it’s square() method with the argument 5: m.square(5); Objects Review
  • 181. MyMath Output  The results of invoking square() method on instances m and n are the same: m: value of PI is 3.14159 m: square of 5 is 25 n: value of PI is 3.14159 n: square of 5 is 25  square() behaves the same no matter which instance it is called on.  So . . . why not have one square() method for the entire class?
  • 182. Also . . .  The value of PI = 3.14159 is the same for all instances of MyMath class.  Why do we need to store a value of PI separately for each instance of MyMath?  Instead, can we have only one common value of PI for the whole MyMath class?
  • 183. MyMath with static public class MyMath { // add keyword "static" to field declaration public static double PI = 3.14159; // add keyword "static" to method declaration public static double square (double x) { return x * x; } // main method is always declared "static" public static void main( String[ ] args) { // MyMath m = new MyMath(); - No longer need this line! // MyMath n = new MyMath(); - No longer need this line! // Now invoke square() method on the MyMath class System.out.println("Value of PI is " + MyMath.PI); System.out.println("Square of 5 is" + MyMath.square(5)); } }
  • 184. Static Pi Field  We added word static to the declaration of the final variable PI: public static double PI = 3.14159;  It means that now we have only one value of variable PI for all instances of MyMath class; PI is now a class data field
  • 185. The final keyword  We declared PI as public static double PI = 3.14159; but this does not prevent changing its value: MyMath.PI = 999999999;  Use keyword final to denote a constant : public static final double PI = 3.14159;  Once we declare a variable to be final, it's value can no longer be changed!
  • 186. Final References  Consider this final reference to a Point: public static final Point ORIGIN = new Point(0,0);  This prevents changing the reference ORIGIN: MyMath.ORIGIN = new Point(3, 4);  BUT! You can still call methods on ORIGIN that change the state of ORIGIN. MyMath.ORIGIN.setX(4);
  • 187. MyMath with static & final public class MyMath { // add keyword final to field declaration public static final double PI = 3.14159; public static double square (double x) { return x * x; } public static void main( String[ ] args) { System.out.println("Value of PI is " + MyMath.PI); System.out.println("Square of 5: " + MyMath.square(5)); } }
  • 188. Static Fields  Only one instance of a static field data for the entire class, not one per object.  "static" is a historic keyword from C/C++  "Class fields" is a better term  As opposed to "instance fields"
  • 189. Static Square Method  We also added the word "static" to the declaration of the method square(): public static double square(double x) { return x * x; }  Now the method square() is shared by all instances of the class—only one square method for the class, not one for each instance.
  • 190. Static Methods  Static methods do not operate on a specific instance of their class  Have access only to static fields and methods of the class  Cannot access non-static ones  "Class methods" is a better term  As opposed to "instance methods"
  • 191.  Let's take a look at Java's Math class in the API  You cannot create an instance of the Math Class, it's just a place to store useful static methods  All the methods and fields are static: Math.sqrt(16) Math.PI Math.abs(-3) Java's Math Class
  • 192. Static Field Examples  Constants used by a class (usually used with final keyword)  Have one per class; don’t need one in each object public static final double TEMP_CONVERT= 1.8;  If this is in class Temperature, it is invoked by  double t = Temperature.TEMP_CONVERT * temp;  Constants are all capital letters by tradition (C, C++)  For example: PI , TEMP_CONVERT etc.
  • 193. Static Method Examples  For methods that use only the arguments and therefore do not operate on an instance public static double pow(double b, double p) // Math class, takes b to the p power  For methods that only need static data fields  Main method in the class that starts the program  No objects exist yet for it to operate on!
  • 194. POP QUIZ Should it be static or non-static?  Speed of light field  getName() method in a Person class  A sum method that returns the resulting of adding both its arguments  Width data field in a Rectangle class static non static non
  • 196. Access & Organization  Let’s say you have 100’s of files on your PC. What kind of problems do you encounter?  can’t find particular files  duplicate or similar file names  hard to keep personal files private  Solution: Sort and organize your files into subdirectories
  • 197. Packages  Organize your classes into sets or units  Reduce problems with name conflicts  Identify your classes in a set with specific functionality How to specify the package for a class: package <package name>;
  • 198. Using Packages  A class can always access other classes in its own package  A class can always access public classes in other packages Q: What happens if we don’t specify a package as public or private? A: the default level of access is package
  • 199. Levels of Access Control Visibility private package (default) public From the same class yes yes yes From any class in same package no yes yes From any class outside the package no no yes Big line to cross!
  • 200. Import Classes and Packages  Specify the class you want to import: import java.util.Date;  You can import multiple classes: import java.util.ArrayList;  You can also import whole packages: import java.util.*;  Default imported package: import java.lang.*;
  • 201. Package Example: Person.java package examples; class Person { String name; // add a field to store a birthday // write a method to set the birthday // write a method to get the birthday }
  • 202. Using java.util.Date package examples; class Person { String name; java.util.Date birthday; void setBirthday(java.util.Date d) { birthday = d; } java.util.Date getBirthday() { return birthday; } }
  • 203. Importing java.util.Date package examples; import java.util.Date; class Person { String name; Date birthday; void setBirthday(Date d) { birthday = d; } Date getBirthday() { return birthday; } }
  • 204. Importing java.util.ArrayList package examples; import java.util.Date; import java.util.ArrayList; class Person { String name; Date birthday; ArrayList friends; void setBirthday(Date d) { birthday = d; } // . . . }
  • 205. Importing java.util.* package examples; import java.util.*; class Person { String name; Date birthday; ArrayList friends; void setBirthday(Date d) { birthday = d; } // . . . }
  • 206. Packages Quiz 1 package example1; public class A { public int a = 5; } package example1; public class B { int b = 5; } package example1; public class C { private int c = 5; } package example1; public class quiz{ void main() { A ant = new A(); B bug = new B(); C cat = new C(); // Which are correct? int testa = ant.a; int testb = bug.b; int testc = cat.c; } }
  • 207. Package Quiz 2 package example2; import example1.*; public class quiz{ void main() { A ant = new A(); B bug = new B(); C cat = new C(); // Which are correct? int testa = ant.a; int testb = bug.b; int testc = cat.c; } } package example1; public class A { public int a = 5; } package example1; public class B { int b = 5; } package example1; public class C { private int c = 5; }
  • 208. SCOPE
  • 209. Scope of a Variable  Definition: the block (section) of code for which your variable (identifier) exists  The scope is set to the block in which you defined your variable  This is the block of code where you can use the variable
  • 210. Scope Quiz 1 class TestScope { int x = 0; void f() { int y = 20; x = 10; } void print() { System.out.println(x); f(); System.out.println(x); System.out.println(y); } } What is the output of print()? This file won't compile, so print will never execute
  • 211. Method Scope class TestScope { int x = 0; void f() { int y = 20; x = 10; } void print() { System.out.println(x); f(); System.out.println(x); System.out.println(y); // ERROR } }  x is defined for the whole class block.  y is defined inside the method f().
  • 212. Scope Quiz 2 class TestScope { int x = 0; void f() { int y = 20; x = 10; } void print() { int y = 0; System.out.println(x); f(); System.out.println(x); System.out.println(y); } }` Does this fix the problem? What is the output of print()? 0 10 0
  • 213. Scope Quiz 3 class TestScope { int x = 0; int y = 0; void f() { int y; y = 20; x = 10; } void print() { System.out.println(x); f(); System.out.println(x); System.out.println(y); } } Now, we declare a new field, y. What is the output of print()? 0 10 0
  • 214. Scope Quiz 4 class TestScope { int x = 0; int y = 0; void f() { y = 20; x = 10; } void print() { System.out.println(x); f(); System.out.println(x); System.out.println(y); } } Now, we change the method f(). What is the output of print()? 0 10 20
  • 215. Scope Quiz 5 package examples; class Operations{ int square(int a) { a = a * a; return a; } void print() { int a = 5; System.out.println(square(a)); System.out.println(a); } }  What is the output of print()? 25 <- square(a) 5 <- a
  • 216. Scope Quiz 6 package examples; class Operations{ int a = 5; int square(int a) { a = a * a; return a; } void print() { System.out.println(square(a)); System.out.println(a); } }  What is the output of print()? 25 <- square(a) 5 <- a
  • 217. Scope Quiz 7 package examples; class Operations{ int a = 5; int square(int a) { this.a = a*a; return a; } void print() { System.out.println(square(a)); System.out.println(a); } }  What is the output of print()? 5 <- square(a) 25 <- a
  • 218. Loop Scope void adding() { for (int j = 0; j<5; j++) { int sum += j; } System.out.println(sum); }  What’s wrong with the above segment of code? ERROR: sum is only defined inside the for loop
  • 219. Loop Scope Fixed void adding() { int sum = 0; for (int j = 0; j<5; j++) { sum += j; } System.out.println(sum); }  sum is now defined for the whole block of code for the adding method
  • 220. Summary of Scope  Definition: the block (section) of code for which your variable (identifier) exists  The scope is set to the block in which you defined your variable  This is the block of code where you can use the variable
  • 222. What is Inheritance?  In the real world: We inherit traits from our mother and father. We also inherit traits from our grandmother, grandfather, and ancestors. We might have similar eyes, the same smile, a different height . . . but we are in many ways "derived" from our parents.  In software: Object inheritance is more well defined! Objects that are derived from other object "resemble" their parents by inheriting both state (fields) and behavior (methods).
  • 223. Dog Class public class Dog { private String name; private int fleas; public Dog(String n, int f) { name = n; fleas = f; } public String getName() { return name; } public int getFleas() { return fleas; } public void speak() { System.out.println("Woof"); } }
  • 224. Cat Class public class Cat { private String name; private int hairballs; public Cat(String n, int h) { name = n; hairballs = h; } public String getName() { return name; } public int getHairballs() { return hairballs; } public void speak() { System.out.println("Meow"); } }
  • 225. Problem: Code Duplication  Dog and Cat have the name field and the getName method in common  Classes often have a lot of state and behavior in common  Result: lots of duplicate code!
  • 226. Solution: Inheritance  Inheritance allows you to write new classes that inherit from existing classes  The existing class whose properties are inherited is called the "parent" or superclass  The new class that inherits from the super class is called the "child" or subclass  Result: Lots of code reuse!
  • 227. Dog String name int fleas String getName() int getFleas() void speak() Cat String name int hairballs String getName() int getHairballs() void speak() Dog int fleas int getFleas() void speak() Cat int hairballs int getHairballs() void speak() Animal String name String getName() using inheritance superclass subclass subclass
  • 228. Animal Superclass public class Animal { private String name; public Animal(String n) { name = n; } public String getName() { return name; } }
  • 229. Dog Subclass public class Dog extends Animal { private int fleas; public Dog(String n, int f) { super(n); // calls Animal constructor fleas = f; } public int getFleas() { return fleas; } public void speak() { return System.out.println("Woof"); } }
  • 230. Cat Subclass public class Cat extends Animal { private int hairballs; public Cat(String n, int h) { super(n); // calls Animal constructor hairballs = h; } public int getHairballs() { return hairballs; } public void speak() { return System.out.println("Meow"); } }
  • 231. Inheritance Quiz 1  What is the output of the following? Dog d = new Dog("Rover" 3); Cat c = new Cat("Kitty", 2); System.out.println(d.getName() + " has " + d.getFleas() + " fleas"); System.out.println(c.getName() + " has " + c.getHairballs() + " hairballs"); Rover has 3 fleas Kitty has 2 hairballs (Dog and Cat inherit the getName method from Animal)
  • 232. Inheritance Rules  Use the extends keyword to indicate that one class inherits from another  The subclass inherits all the fields and methods of the superclass  Use the super keyword in the subclass constructor to call the superclass constructor
  • 233. Subclass Constructor  The first thing a subclass constructor must do is call the superclass constructor  This ensures that the superclass part of the object is constructed before the subclass part  If you do not call the superclass constructor with the super keyword, and the superclass has a constructor with no arguments, then that superclass constructor will be called implicitly.
  • 234. Implicit Super Constructor Call If I have this Food class: public class Food { private boolean raw; public Food() { raw = true; } } then this Beef subclass: public class Beef extends Food { private double weight; public Beef(double w) { weight = w } } is equivalent to: public class Beef extends Food { private double weight; public Beef(double w) { super(); weight = w } }
  • 235. Inheritance Quiz 2 public class A { public A() { System.out.println("I'm A"); } } public class B extends A { public B() { System.out.println("I'm B"); } } public class C extends B { public C() { System.out.println("I'm C"); } } What does this print out? C x = new C(); I'm A I'm B I'm C
  • 236. • Subclasses can override methods in their superclass • What is the output of the following? ThermUS thermometer = new ThermUS(100); System.out.println(thermometer.getTemp()); Overriding Methods class ThermUS extends Therm { public ThermUS(double c) { super(c); } // degrees in Fahrenheit public double getTemp() { return celsius * 1.8 + 32; } } class Therm { public double celsius; public Therm(double c) { celsius = c; } public double getTemp() { return celcius; } } 212
  • 237. Calling Superclass Methods  When you override a method, you can call the superclass's copy of the method by using the syntax super.method() class Therm { private double celsius; public Therm(double c) { celcius = c; } public double getTemp() { return celcius; } } class ThermUS extends Therm { public ThermUS(double c) { super(c); } public double getTemp() { return super.getTemp() * 1.8 + 32; } }
  • 238. Access Level • Classes can contain fields and methods of four different access levels: • private: access only to the class itself • package: access only to classes in the same package • protected: access to classes in the same package and to all subclasses • public: access to all classes everywhere
  • 239. Variable Type vs Object Type  Variables have the types they are given when they are declared and objects have the type of their class.  For an object to be assigned to a variable is must be of the same class or a subclass of the type of the variable.  You may not call a method on a variable if it's type does not have that method, even if the object it references has the method.
  • 240. Which Lines Don't Compile? public static void main(String[] args) { Animal a1 = new Animal(); a1.getName(); a1.getFleas(); a1.getHairballs(); a1.speak(); Animal a2 = new Dog(); a2.getName(); a2.getFleas(); a2.getHairballs(); a2.speak(); Dog d = new Dog(); d.getName(); d.getFleas(); d.getHairballs(); d.speak(); } // Animal does not have getFleas // Animal does not have getHairballs // Animal does not have speak // Animal does not have getFleas // Animal does not have getHairballs // Animal does not have speak // Dog does not have getHairballs
  • 241. Remember Casting?  "Casting" means "promising" the compiler that the object will be of a particular type  You can cast a variable to the type of the object that it references to use that object's methods without the compiler complaining.  The cast will fail if the variable doesn't reference an object of that type.
  • 242. Which Castings Will Fail? public static void main(String[] args) { Animal a1 = new Animal(); ((Dog)a1).getFleas(); ((Cat)a1).getHairballs(); ((Dog)a1).speak(); Animal a2 = new Dog(); ((Dog)a2).getFleas(); ((Cat)a2).getHairballs(); ((Dog)a2).speak(); Dog d = new Dog(); ((Cat)d).getHairballs(); } // a1 is not a Dog // a1 is not a Cat // a1 is not a Dog // a2 is not a Cat // d is not a Cat
  • 243. Programming Example  A Company has a list of Employees. It asks you to provide a payroll sheet for all employees.  Has extensive data (name, department, pay amount, …) for all employees.  Different types of employees – manager, engineer, software engineer.  You have an old Employee class but need to add very different data and methods for managers and engineers.  Suppose someone wrote a name system, and already provided a legacy Employee class. The old Employee class had a printData() method for each Employee that only printed the name. We want to reuse it, and print pay Borrowed with permission from Course 1.00 Notes
  • 244. public … Main(…){ Employee e1…("Mary","Wang"); ... e1.printData(); // Prints Employee names. ... } Employee e1 lastName firstName printData Encapsulation Message passing "Main event loop" private: REVIEW PICTURE
  • 245. Employee class class Employee { // Data private String firstName, lastName; // Constructor public Employee(String fName, String lName) { firstName= fName; lastName= lName; } // Method public void printData() { System.out.println(firstName + " " + lastName);} } This is a simple super or base class.
  • 246. Inheritance Class Employee firstName lastName printData() Class Manager salary firstName lastName Class Engineer hoursWorked wages firstName lastName printData() getPay() is-a printData() getPay() Already written: is-a You next write:
  • 247. Engineer class class Engineer extends Employee { private double wage; private double hoursWorked; public Engineer(String fName, String lName, double rate, double hours) { super(fName, lName); wage = rate; hoursWorked = hours; } public double getPay() { return wage * hoursWorked; } public void printData() { super.printData(); // PRINT NAME System.out.println("Weekly pay: $" + getPay(); } Subclass or (directly) derived class
  • 248. Manager class class Manager extends Employee { private double salary; public Manager(String fName, String lName, double sal){ super(fName, lName); salary = sal; } public double getPay() { return salary; } public void printData() { super.printData(); System.out.println("Monthly salary: $" + salary);} } Subclass or (directly) derived class
  • 250. SalesManager Class class SalesManager extends Manager { private double bonus; // Bonus Possible as commission. // A SalesManager gets a constant salary of $1250.0 public SalesManager(String fName, String lName, double b) { super(fName, lName, 1250.0); bonus = b; } public double getPay() { return 1250.0; } public void printData() { super.printData(); System.out.println("Bonus Pay: $" + bonus; } } (Derived class from derived class)
  • 251. Main method public class PayRoll { public static void main(String[] args) { // Could get Data from tables in a Database. Engineer fred = new Engineer("Fred", "Smith", 12.0, 8.0); Manager ann = new Manager("Ann", "Brown", 1500.0); SalesManager mary= new SalesManager("Mary", "Kate", 2000.0); // Polymorphism, or late binding Employee[] employees = new Employee[3]; employees[0]= fred; employees[1]= ann; employees[2]= mary; for (int i=0; i < 3; i++) employees[i].printData(); } } Java knows the object type and chooses the appropriate method at run time
  • 252. Output from main method Fred Smith Weekly pay: $96.0 Ann Brown Monthly salary: $1500.0 Mary Barrett Monthly salary: $1250.0 Bonus: $2000.0 Note that we could not write: employees[i].getPay(); because getPay() is not a method of the superclass Employee. In contrast, printData() is a method of Employee, so Java can find the appropriate version.
  • 253. Object Class  All Java classes implicitly inherit from java.lang.Object  So every class you write will automatically have methods in Object such as equals, hashCode, and toString.  We'll learn about the importance of some of these methods in later lectures.
  • 254. Lecture 13 Abstract Classes and Interfaces
  • 255. What is an Abstract Class?  An abstract class is a class that cannot be instantiated—we cannot create instances of an abstract class.  One or more methods may be declared, but not defined. (The programmer has not yet written code for a few methods).  The declared methods and classes have the keyword abstract in their signature.
  • 256. public class Employee { private String name; private double salary; public Employee(String n, double s) { name = n; salary = s; } public String getName() { return name; } public double getSalary() { return salary; } public String description() { return "employee with a salary of $ " + salary; } } Employee Class
  • 257. public class Student { private String name; private String course; public Student(String n, String c) { name = n; course = c; } public String getName() { return name; } public String getCourse() { return course; } public String description() { return "a student majoring in " + course; } } Student Class
  • 258. Common Functionality  Student and Employee may have common fields and methods. private String name; getName()  Instead of repeating code, introduce a superclass
  • 259. Example Hierarchy  Consider the following class structure: Person Employee Student Superclass Subclasses
  • 260. public class Person { String name; public Person(String n) { name = n; } public String getName() { return name; } } Person Class
  • 261. public class Employee extends Person { // private String name; private double salary; public Employee(String n, double s) { super(n); salary = s; } // public String getName() { return name; } public double getSalary() { return salary; } public String description() { return "an employee with a salary of $" + salary; } } Employee Subclass of Person
  • 262. public class Student extends Person{ // private String name; private String course; public Student(String n, String c) { super(n); course = c; } // public String getName() { return name; } public String getCourse() { return course; } public String description() { return "a student majoring in " + course; } } Revised Student
  • 263. description() Method  Let’s create Person, Employee, and Student object Person kwame = new Student("Kwame", "CS"); Employee kojo = new Employee("Kojo", 200000); Student yaa = new Student("Yaa", "Math");  Description of an Employee and a Student returns: employee with a salary of ¢200000 student majoring in Math  Can we say: kwame.description()  NO! the variable kwame is of type Person, which does not have a description() method defined
  • 264. public class Person { String name; public Person(String n) { name = n; } public String getName() { return name; } // add a method to return the // description of a Person } Let's Revise Person
  • 265. public class Person { String name; public Person(String n) { name = n; } public String getName() { return name; } public String description() { return "person named " + name; } } Revised Person
  • 266. description() Revisited  Now we can call the description() method on Objects that are of type Person (instances of a Student, Employee, or Person) Person kwame = new Person("Kwame"); Person kojo = new Employee("Kojo", 200000); Person yaa = new Student("Yaa", "Math"); kwame.description(); kojo.description(); yaa.description();
  • 267. description Method Revisited  Now we can call the description() method on Objects that are of type Person (instances of a Student, Employee, or Person) Person kwame = new Person("Kwame"); Person kojo = new Employee("Kojo", 20000); Person yaa = new Student("Yaa", "Math"); kwame.description(); // method in Person kojo.description(); // method in Employee yaa.description(); // method in Student  PROBLEM: We don’t want to create instances of Person, just Students and Employee
  • 268. Abstract Methods  Solution: Use the keyword abstract  A method labeled abstract is declared but not implemented  Rule: An abstract class can have zero or more abstract methods  Make description() an abstract method in the class Person
  • 269. public abstract class Person { String name; public Person(String n) { name = n; } public String getName() { return name; } public abstract String description(); } Abstract Person Class
  • 270. Abstract Classes  Cannot instantiate or create an object of an abstract class Person jacob = new Person("Jacob") // ERROR!!  An abstract class can have both abstract and non-abstract methods  Abstract methods need to be defined in concrete subclasses (classes that can be instantiated)
  • 271. Using Abstract Classes  Variables can be objects of abstract types Person p = new Student("Greg", "CS");  Here p has the type Person, but references an instance of a non-abstract class, Student
  • 272. Calls to Abstract Methods Person[] people = new Person[2]; people[0] = new Employee("Evita", 2000000.0); people[1] = new Student("Greg", "CS"); for (int i = 0; i < people.length; i++) { Person p = people[i]; System.out.println(p.getName() + ", " + p.description()); } What is the output? Evita, an employee with a salary of $200000 Greg, a student majoring in CS
  • 273. public abstract class Person { String name; public Person(String n) { name = n; } public String getName() { return name; } // must declare in order to call // method on variable of type Person public abstract String description(); } Abstract Person Class
  • 274. Advantages  Classes can now be very general in a class/type hierarchy.  This allows more abstraction in object oriented programming.  Have more control over inheritance in a class/type hierarchy.  Make a class abstract even if there are no abstract methods
  • 275. Summary of Abstract Classes  Partial implementation of a class  Cannot be instantiated  Use the abstract keyword in their signature.  Abstract methods are defined in subclasses
  • 276. Problem Situation  Consider creating an Object that represents an Intern.  An Intern behaves like both an Employee and a Student.  Problem: a class can only extend ONE other class
  • 277. Interfaces  Solution: Use an interface, which is a set of requirements for a class  A class can implement more than one interface  Methods in an interface are automatically public and abstract  Make Employee an interface
  • 278. Interface Details  An interface is a contract for a class.  An interface specifies a set of methods a class must implement.  An interface, similar to an abstract class, cannot be instantiated  An interface has no constructors, only constants and method declarations.  Classes implement interfaces using the keyword implements
  • 279. Employee Interface public interface Employee { // fields are public static final constants double STARTING_SALARY = 200000.0; // methods are automatically public and // abstract; must be overridden in // classes that implement the interface String description(); double getSalary(); }
  • 280. public class Student { private String name; private String course; public Student(String n, String c) { name = n; course = c; } public String getName() { return name; } public String getCourse() { return course; } public String description() { return "a student majoring in " + course; } } Student Class Revisted
  • 281. class Intern extends Student implements Employee { private double income; public Intern(String n, String c) { super(n, c); income = STARTING_SALARY; } public double getSalary() { return income; } public String description() { return "intern majoring in "+ super.getCourse() + "with an income of $" + income; } } Intern Class
  • 282. Using Intern Class public static void main(String[] args) { Intern irish = new Intern("Conor", "Math"); System.out.println(irish.getName() + " ," + irish.description()); } Output: Conor, intern majoring in Math with an income of $200000.0
  • 283. Variable Types  A variable may have the type of an abstract class, an interface, or a concrete class (a non-abstract class).  Because only a concrete class can be instantiated, an object may only have the type of a concrete class.  All of these are valid variable declarations: Intern a = new Intern("Conor", "Math"); Student b = new Intern("Conor", "Math"); Employee c = new Intern("Conor", "Math");
  • 284. Variable vs Object Types (Again) Intern a = new Intern("Conor", "Math"); Student b = new Intern("Conor", "Math"); Employee c = new Intern("Conor", "Math");  These expressions will not compile: b.getSalary() // Student does not have getSalary c.getCourse() // Employee does not have getCourse  But all of these will: ((Employee)b).getSalary() ((Intern)b).getSalary() ((Student)c).getCourse() ((Intern)c).getCourse()
  • 285. Interface Rules  Interfaces may specify but do not implement methods.  A class that implements the interface must implement all its methods.  Interfaces cannot be instantiated.  Interfaces may contain constants.
  • 287. Attack of the Exception  What happens when this method is used to take the average of an array of length zero?  Program throws an Exception and fails java.lang.ArithmeticException: / by zero public static int average(int[] a) { int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / a.length; }
  • 288. What is an Exception?  An error event that disrupts the program flow and may cause a program to fail.  Some examples:  Performing illegal arithmetic  Illegal arguments to methods  Accessing an out-of-bounds array element  Hardware failures  Writing to a read-only file
  • 289. Another Exception Example  What is the output of this program? public class ExceptionExample { public static void main(String args[]) { String[] greek = {"Alpha", "Beta"}; System.out.println(greek[2]); } } Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4)
  • 290. Exception Message Details  What exception class?  Which array index is out of bounds?  What method throws the exception?  What file contains the method?  What line of the file throws the exception? Exception message format: [exception class]: [additional description of exception] at [class].[method]([file]:[line number]) Example: java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4) ArrayIndexOutOfBoundsException 2 main ExceptionExample.java 4
  • 291. Exception Handling  Use a try-catch block to handle exceptions that are thrown try { // code that might throw exception } catch ([Type of Exception] e) { // what to do if exception is thrown }
  • 292. Exception Handling Example public static int average(int[] a) { int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / a.length; } public static void printAverage(int[] a) { try { int avg = average(a); System.out.println("the average is: " + avg); } catch (ArithmeticException e) { System.out.println("error calculating average"); } }
  • 293. Catching Multiple Exceptions  Handle multiple possible exceptions by multiple successive catch blocks try { // code that might throw multiple exception } catch (IOException e) { // handle IOException and all subclasses } catch (ClassNotFoundException e2) { // handle ClassNotFoundException }
  • 294. Exceptions Terminology  When an exception happens we say it was thrown or raised  When an exception is dealt with, we say the exception is was handled or caught
  • 295. Unchecked Exceptions  All the exceptions we've seen so far have been Unchecked Exceptions, or Runtime Exceptions  Usually occur because of programming errors, when code is not robust enough to prevent them  They are numerous and can be ignored by the programmer
  • 296. Common Unchecked Exceptions  NullPointerException reference is null and should not be  IllegalArgumentException method argument is improper is some way  IllegalStateException method called when class is in improper state
  • 297. Checked Exceptions  There are also Checked Exceptions  Usually occur because of errors programmer cannot control: examples: hardware failures, unreadable files  They are less frequent and they cannot be ignored by the programmer . . .
  • 298. Dealing With Checked Exceptions  Every method must catch (handle) checked exceptions or specify that it may throw them  Specify with the throws keyword void readFile(String filename) { try { FileReader reader = new FileReader("myfile.txt"); // read from file . . . } catch (FileNotFoundException e) { System.out.println("file was not found"); } } void readFile(String filename) throws FileNotFoundException { FileReader reader = new FileReader("myfile.txt"); // read from file . . . } or
  • 299. Exception Class Hierarchy Exception RuntimeException IOException FileNotFoundException MalformedURLException SocketException ArrayIndexOutofBounds NullPointerException etc. etc. SQLException IllegalArgumentException Unchecked Exceptions Checked Exceptions  All exceptions are instances of classes that are subclasses of Exception
  • 300. Checked and Unchecked Exceptions Checked Exception Unchecked Exception not subclass of RuntimeException subclass of RuntimeException if not caught, method must specify it to be thrown if not caught, method may specify it to be thrown for errors that the programmer cannot directly prevent from occurring for errors that the programmer can directly prevent from occurring, IOException, FileNotFoundException, SocketException NullPointerException, IllegalArgumentException, IllegalStateException
  • 301. Exception Constructors  Exceptions have at least two constructors: 1. no arguments NullPointerException e = new NullPointerException(); 2. single String argument descriptive message that appears when exception error message is printed IllegalArgumentExceptione e = new IllegalArgumentException("number must be positive");
  • 302. Writing Your Own Exception  To write your own exception, write a subclass of Exception and write both types of constructors public class MyCheckedException extends IOException { public MyCheckedException() {} public MyCheckedException(String m) {super(m);} } public class MyUncheckedException extends RuntimeException { public MyUncheckedException() {} public MyUncheckedException(String m) {super(m);} }
  • 303. Throwing Exceptions  Throw exception with the throw keyword public static int average(int[] a) { if (a.length == 0) { throw new IllegalArgumentException("array is empty"); } int total = 0; for(int i = 0; i < a.length; i++) { total += a[i]; } return total / a.length; }
  • 304. Keyword Summary  Four new Java keywords  try and catch – used to handle exceptions that may be thrown  throws – to specify which exceptions a method throws in method declaration  throw – to throw an exception
  • 305. Throws and Inheritance  A method can throw less exceptions, but not more, than the method it is overriding public class MyClass { public void doSomething() throws IOException, SQLException { // do something here } } public class MySubclass extends MyPlay { public void doSomething() throws IOException { // do something here } }
  • 306. Line Intersection Example  Consider this class Line, which has two fields, a slope and a yIntercept  Let's write an intersect method that returns the x-coordinate at which the two lines intersect. sig Line { private double slope; private double yIntercept; double getSlope() { return slope; } double getYIntercept() { return yIntercept; } }
  • 307.  Calculating the x-coordinate at which two lines intersect  We could translate this directly into the following intersect method: Boring Math Stuff . . . y = m1x + b1 y = m2x + b2 m1x + b1 = m2x + b2 m1x - m2x = b2 - b1 (m1 - m2)x = b2 - b1 x = (b2 - b1)/(m1 - m2) double intersect(Line line1, Line line2) { return (line2.getYIntercept() – line1.yIntercept()) / (line1.slope() – line2.slope()) }
  • 308.  Parallel lines will never intersect.  If lines are parallel, then their slopes will be equal, line1.slope() – line2.slope() = 0, and our method will attempt to divide by zero  Let's write a new exception ParallelException to throw when this occurs. What About Parallel Lines?
  • 309. ParallelException  ParallelException will be a checked exception because calculating whether lines are parallel is not something we expect the programmer to know how to do and prevent in advance.  Checked exceptions are a subclass of Exception, but not RuntimeException public class ParallelException extends Exception { public ParallelException() {} public ParallelException(String msg) { super(msg); } }
  • 310. Final Intersect Method  Because it is a checked exception, intersect must specify that it throws it double intersect(Line line1, Line line2) throws ParallelException { if (line1.slope() = line2.slope()) { throw new ParallelException(); } return (line2.getYIntercept() – line1.yIntercept()) / (line1.slope() – line2.slope()) }
  • 311. Calling the intersect Method  A method that accepts two Lines as arguments, calls intersect, and prints out the results: void printIntersect(Line line1, Line line2) { try { double x = intersect(line1, line2); System.out.println("Intersect at " + x); } catch (ParallelException e) { System.out.println("They are parallel"); } }
  • 312. Lecture 15 I/O and Parsing Reading and Writing with Java's Input/Output Streams and Parsing Utilities
  • 313. Input/Output Basics  Input/Output = I/O = communication between a computer program and external sources and destinations of information  Involves Reading and Writing  Reading input from a source  Writing output to a destination  Example Sources and Destinations:  Files  Network connections  Other programs
  • 314. Java I/O Streams  Java uses an I/O system called streams (pioneered in C++)  Java provides java.io package to implement streams  Streams treat all external source and destinations of data the same way: as "streams" of information
  • 315. Input vs. Output Streams  Reading from an Input Stream  Writing to an Output Stream
  • 316. Byte vs. Character Streams  Byte Streams are used to read and write data in binary format (1's and 0's) example data: images, sounds, executable programs, word-processing documents, etc.  Character Streams are used to read and write data in text format (characters) example data: plain text files (txt extension), web pages, user keyboard input, etc.
  • 317. Java Classes  Package java.io offers classes to connect to streams  To connect to a stream, instantiate a subclass of one of these abstract superclasses: input output byte InputStream OutputStream character Reader Writer
  • 318. Using a Stream Class 1. Open a stream by instantiating a new stream object 2. While more information to read/write, read/write that data 3. Close the stream by calling the object’s close() method
  • 319. Using a Reader  Recall: a Reader is used to read a character input stream  Reader offers these methods to read single characters and arrays of characters: int read() int read(char cbuf[]) int read(char cbuf[], int offset, int length)  Reader is abstract so you must instantiate a subclass of it to use these methods
  • 320. How to Read from a Text File public void readFile() { FileReader fileReader = null; try { fileReader = new FileReader("input.txt"); int c = fileReader.read(); while (c != -1) { // cast c to char and use it c = fileReader.read(); } } catch (FileNotFoundException e) { System.out.println("File was not found"); } catch (IOException e) { System.out.println("Error reading from file"); } if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { /* ignore */ } } }
  • 321. Wrap in a BufferedReader  BufferedReader has a readLine() method to read an entire line of characters efficiently  Wrap a Reader with a BufferedReader by passing the Reader as a constructor argument FileReader fr = new FileReader("myFile.txt"); BufferedReader br = new BufferedReader(fr);  The readLine() method returns null when there are no more lines to read
  • 322. Using BufferedReader public void readFileWithBufferedReader() { BufferedReader bufferedReader = null; try { FileReader fr = new FileReader("input.txt"); bufferedReader = new BufferedReader(fr); String line = bufferedReader.readLine(); while (line != null) { // do something with line line = bufferedReader.readLine(); } } catch (FileNotFoundException e) { System.out.println("File was not found"); } catch (IOException e) { System.out.println("Error reading from file"); } if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { /* ignore */ } } }
  • 323. Writers  Writer is an abstract class to write to character streams  Offers write methods to write single characters, arrays of characters, and strings void write(int c) void write(char cbuf[]) void write(String str)  BufferedWriter offers efficient writing and a newLine() method to insert a blank line  Close writers with close() method when done
  • 324. How to Write to a Text File public void writeFileWithBufferedWriter() { BufferedWriter buffWriter = null; try { FileWriter fw = new FileWriter("output.txt"); buffWriter = new BufferedWriter(fw); while (/*still stuff to write */) { String line = // get line to write buffWriter.write(line); buffWriter.newLine(); } } catch (IOException e) { System.out.println("Error writing to file"); } if (buffWriter != null) { try { buffWriter.close(); } catch(IOException e) { /* ignore */ } } }
  • 325. Example: Copying Text Files void copyFiles(String inFilename, String outFilename) throws FileNotFoundException { BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader(inFilename)); bw = new BufferedWriter(new FileWriter(outFilename)); String line = br.readLine(); while(line != null) { bw.write(line); bw.newLine(); line = br.readLine(); } } catch (IOException e) { System.out.println("Error copying files"); } if (br != null) {try {br.close();} catch(IOException e) {}} if (bw != null) {try {bw.close();} catch(IOException e) {}} }
  • 326. Reading from Keyboard Input  Keyboard input is sent over a stream referred to as "standard" input  Java "standard" input is the InputStream object System.in (a byte stream)  To read characters over an InputStream, need to wrap it in an InputStreamReader  To read line by line, wrap the Input- StreamReader with a BufferedReader
  • 327. Reading from Keyboard Input /** * Returns a line read from keyboard input. * Return null if there was an error reading the line. */ public void String readKeyboardLine() throws IOException { BufferedReader br = null; String line = null; try { br = new BufferedReader(new InputStreamReader(System.in)); line = br.readLine(); } catch (IOException e) {} if (br != null) { try { br.close(); } catch (IOException e) { /* ignore */ } } return line; }
  • 328. What We've Learned So Far  Types of Streams  Input vs. output streams  Byte vs. character streams  How to . . .  Read from text files  Write to text files  Read text from keyboard input  Use buffered streams  You are left on your own to figure out how to use other streams
  • 329. Intro to Parsing  Programs often encode data in text format to store in files  Programs later need to decode the text in the files back into the original data  Process of decoding text back into data is known as parsing
  • 330. Delimiters  When data is stored in text format, delimiter characters are used to separate tokens of the data  A list of first names stored separated by the '#' delimiter: Greg#Kwame#Sonya#Bobby  Same list with a newline delimiter: Greg Kwame Sonya Bobby
  • 331. StringTokenizer  java.util.StringTokenizer separates Strings at the delimiters to extract tokens  Default constructor will assume any whitespace (spaces, tabs, newlines) to be delimiters  Second constructor accepts String of any delimiter characters  nextToken method returns the next data token between delimiters in the text  hasMoreTokens returns true if the text has remaining tokens
  • 332. Using StringTokenizer  Printing out every name from a file where names are delimited by whitespace: public void printNamesFromFile(String filename) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filename)); String line = br.readLine(); while(line != null) { StringTokenizer st = new StringTokenizer(line); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); } line = br.readLine(); } } catch (IOException e) { System.out.println("Error reading from file."); } if (br != null) { try { br.close(); } catch(IOException e) {} } }
  • 333. Text → Numbers  Often necessary to parse numbers stored as text into Java primitives  Wrapper classes for primitives provide static methods to do so int Integer.parseInt(String s) double Double.parseDouble(String s)  Throw NumberFormatException if the specified String cannot be converted into the primitive
  • 334. Putting it All Together  File 1: Employee_May.dat Format: Name, SSN, Hourly Rate, Salary to Date Paul Njoroge, 555-12-3456, 65, 20000 Evelyn Eastmond, 555-22-2222, 70, 30000 Peilei Fan, 555-33-4444, 60, 15000 Ethan Howe, 555-44-5555, 80, 40000 Naveen Goela, 555-66-8888, 75, 20000 . . .  File 2: Hours_June.dat Format: Consecutive integers, which are the number of hours each employee has worked during June. The integers have the same sequence as that of the employee records. Content: 50 60 40 50 70 . . .
  • 335. What We Need to Do . . . 1. For each employee, multiply the hours worked by the hourly rate 2. Add this to the value of the salary to date 3. Write to a new file named Employee_June.dat, in the same format as Employee_May.dat, only it includes the updated, increased value of the salary to date.
  • 336.  Create a StringTokenizer over the single line in the Hours_June.dat file BufferedReader empReader = null; String hoursLine = null; try { empReader = new BufferedReader( new FileReader("Hours_June.dat")); hoursLine = empReader.readLine(); } catch(IOException e) { System.out.println("Could not read Hours_June.dat"); } if (empReader != null) { try { empReader.close(); } catch(IOException e) {} } if (line == null) // exit and report an error StringTokenizer hoursST = new StringTokenizer(hoursLine);
  • 337. BufferedReader mayReader = null; BufferedWriter juneWriter = null; try { mayReader = new BufferedReader( new FileReader("Employee_May.dat")); juneWriter = new BufferedWriter( new FileWriter("Employee_June.dat")); // On next slide, we add code to parse the May data, // do the salary calculation, and write the June data } catch(IOException e) { System.out.println("Error with employee files"); } if (mayReader != null) { try { mayReader.close(); } catch(IOException e) {} } if (juneWriter != null) { try { juneWriter.close(); } catch(IOException e) {} }  Opening and closing the streams to the employee files
  • 338. Writing the June Data String employeeStr = mayReader.readLine(); while(employeeStr != null) { StringTokenizer empST = new StringTokenizer(employeeStr, ","); String name = empST.nextToken(); String ssn = empST.nextToken(); double rate = Double.parseDouble(empST.nextToken()); double salary = Double.parseDouble(empST.nextToken()); int hours = Integer.parseInt(hoursST.nextToken()); double newSalary = salary + hours * rate; juneWriter.write(name + "," + ssn + "," + rate + "," + newSalary); juneWriter.newLine(); employeeStr = mayReader.readLine(); }
  • 340. Lecture Summary  Over the next 2 lectures, we will introduce you to the techniques necessary to build graphical user interfaces (GUI) for your applications.  Learning Swing basic concepts: components and containers, colors, layout;  Constructing Swing interfaces;  Using the Swing Event Model.  Style: Mixture of lecture and lab
  • 341. Swing Example import java.awt.*; import javax.swing.*; public class MyTest extends JFrame { JLabel myLabel = new JLabel("Hello, World!"); public MyTest() { super("MyTest"); setSize(350, 100); getContentPane().add(myLabel); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public static void main (String args[]) { MyTest m = new MyTest(); } }
  • 342. WHAT IS SWING?  So far, our user interfaces have only been textual, meaning the user sees text and writes text at the command prompt.  Today we will learn to make our interfaces graphical, so we can use our programs through windows, click on buttons, etc.  Graphical User Interface (GUI)  Swing is Java's graphical user interface library  You MUST import the following packages: import java.awt.*; import javax.swing.*;
  • 344. JFrame  JFrame is the application window class  It is special; it draws the window and interacts with the operating system  When a JFrame is created, an inner container called the contentPane is automatically created  We don't draw graphics directly on JFrame; we draw on the contentPane
  • 345. Anatomy of a JFrame title bar minimize maximize close The contentPane holds your content; created automatically when a JFrame is created
  • 346. Exercise 1: Empty Frame package swinglab; import java.awt.*; import javax.swing.*; // extends keyword makes Calc a JFrame public class Calc extends JFrame{ public Calc() { // get the contentPane and assign it to cp Container cp = getContentPane(); // exit program when user closes the window setDefaultCloseOperation(EXIT_ON_CLOSE); // sets the layout; will be covered in later slide cp.setLayout(new FlowLayout()); // sets title to "My Funky Calculator" setTitle("My Funky Calculator"); setSize(1000,700); // Frame has 0 default size }
  • 347. Exercise 1 continued . . . public static void main (String[] args){ Calc trial = new Calc(); // Frame is invisible by default trial.setVisible(true); // main method exits but user interface // stays alive } }
  • 348. Top Level Windows  Top Level Windows are containers that are not contained by any other containers  They can be iconified or dragged and interact with the native windowing system  Examples: JFrame, JDialog (not JComponents at all )
  • 349. Categories of GUI classes  Swing has a large set of classes that inherit from a super and abstract class JComponent  JComponent: The base class for all Swing components except top-level containers  Its subclasses present information or interact with the user  Examples:labels(JLabels), buttons(JButtons), textfields(JTextField) - Containers are some JComponents that are designed to hold other components (no interaction with the user) - Examples: JPanel, JScrollPane
  • 350. Categories of GUI classes  Swing has a large set of classes that inherit from a super and abstract class JComponent  JComponent: The base class for all Swing components except top-level containers  Its subclasses present information or interact with the user  Examples:labels(JLabels), buttons(JButtons), textfields(JTextField) - Containers are some JComponents that are designed to hold other components (no interaction with the user) - Examples: JPanel, JScrollPane
  • 351. Coordinates  The upper left hand corner of the screen has coordinates (0,0)  Like the cartesian system, the value of x increases from left to right (the x-axis goes from left to right)  However, the value of y increases from top to bottom (the y-axis goes from top to bottom)  Measured in pixels (such as 640 by 480)
  • 352. Frames, Panes and Panels
  • 353. Colors  There are 13 predefined colors  You can access them using Color.x where x is  orange, pink, cyan, magenta, yellow, black, blue, white, gray, lightGray, darkGray, red, green  You can define your own colors Color ugly = new Color(30,90,120); //RGB(red-green-blue); values between 0-255;
  • 354. Exercise 2: JPanels with color  Set the background of the contentPane to white using <nameofobject>.setBackground(<color>);  Create two JPanels in the constructor of Calc  Set the background color of one to orange; set the background color of the other to yellow  Add the two JPanels to the contentPane using <nameofobject>.add(<objecttobeadded>)  add the orange JPanel first; NOTE: the order in which you add your objects determine the way your program looks
  • 355. Exercise 2: Answer package swinglab; import java.awt.*; import javax.swing.*; public class Calc extends JFrame{ private JPanel entryPanel; private JPanel answerPanel; public Calc() { Container cp = getContentPane(); setDefaultCloseOperation(EXIT_ON_CLOSE); cp.setBackground(Color.white); setTitle("My Funky Calculator"); setSize(1000,700); entryPanel = new JPanel(); entryPanel.setBackground(Color.orange); answerPanel = new JPanel(); answerPanel.setBackground(Color.yellow); // . . .
  • 356. Exercise 2: answer continued cp.add(entryPanel); cp.add(answerPanel); } public static void main (String[] args){ Calc trial = new Calc(); trial.setVisible(true); } }
  • 357. JLabels, JButtons, JComboBox etc  These are subclasses of JComponent  You create them just as you create other objects of a class: JLabel sign = new JLabel ("Sign");  When created, you need to add them to the panel: panel.add(sign); // panel is the name of a created JPanel
  • 358. Exercise 3: Adding a JComboBox JComboBox We want to create a JComboBox (drop-down menu): For items in the menu:- Declare and initialize the following above the Calc constructor private JComboBox operation; public static String ADD_OP = "ADDITION"; public static String SUB_OP = "SUBTRACTION"; public static String MUL_OP = "MULTIPLICATION"; public static String DIV_OP = "DIVISION";
  • 359. Exercise 3 continued In Calc Constructor:  Create a JComboBox: operation = new JComboBox();  Add the items in the menu using addItem() : operation.addItem(ADD_OP); operation.addItem(SUB_OP); operation.addItem(MUL_OP); operation.addItem(DIV_OP);  Set its background to blue: operation.setBackground(Color.blue);  Add the JComboBox to the orange panel: <nameofORANGEpanel>.add(operation);
  • 360. Exercise 4: Adding labels, buttons etc JLabels  Declare 2 JLabels: letLabel and answerLabel  Create the two labels in the constructor using their constructor that takes a String as an argument and then set the FOREGROUND color as follows: letLabel: "Let's Calculate!" , green answerLabel: "Answer" , red  Add: letLabel to the ORANGE JPanel answerLabel to the ORANGE JPanel
  • 361. Exercise 4 continued JTextFields  Declare 2 JTextFields: num1 and num2  In the Calc constructor, create the 2 JTextFields using their constructor that takes a String and an int (for size) as arguments: num1:"1st Number" , 10 num2:"2nd Number", 10  Set their background color to lightGray (predefined)  Add them to the ORANGE JPanel
  • 362. Exercise 4 continued JButtons  Declare 2 JButtons: calculate and quit  In Calc constructor, create the two JButtons using their constructor which takes a String as an argument  calculate: "Calculate"  quit : "Quit"  Set their background color as follows: calculate:pink quit : create your color HINT: first create the color then use it Color leaf = new Color(50,100,50); <nameofbutton>.setBackground(leaf);  Add the buttons to the YELLOW JPanel;
  • 363. Exercise 4 continued  Compile and run the program.  Note that the order in which you add objects to the panel determine their positions  Go back through the code and make sure that the objects are added in the following order: ORANGE JPanel: JLabel letLabel, JTextField num1, JTextField num2, JComboBox operation, JLabel answerLabel YELLOW JPanel: JButton calculate, JButton quit
  • 364. Exercise 4: answer package swinglab; import java.awt.*; import javax.swing.*; import java.util.*; public class Calc extends JFrame{ private JLabel letLabel; private JLabel answerLabel; private JTextField num1; private JTextField num2; private JComboBox operation; private JButton calculate; private JButton quit; private JPanel entryPanel; private JPanel answerPanel;
  • 365. letLabel = new JLabel("Let's Calculate!"); entryPanel.add(letLabel); letLabel.setForeground(Color.GREEN); num1 = new JTextField("1st Number", 10); entryPanel.add(num1); num1.setBackground(Color. LIGHT_GRAY); num2= new JTextField("2nd Number", 10); entryPanel.add(num2); num2.setBackground(Color.LIGHT_GRAY); operation = new JComboBox(); operation.addItem(ADD_OP); operation.addItem(SUB_OP); operation.addItem(MUL_OP); operation.addItem(DIV_OP); entryPanel.add(operation); operation.setBackground(Color.BLUE); answerLabel = new JLabel("Answer");
  • 366. entryPanel.add(answerLabel); answerLabel.setForeground(Color.red); calculate = new JButton("Calculate"); calculate.setBackground(Color.pink); answerPanel.add(calculate); quit = new JButton("Quit"); answerPanel.add(quit); Color quitter = new Color(50,100,50); quit.setBackground(quitter); cp.add(entryPanel); cp.add(answerPanel); } public static void main(String[] args){ Calc trial = new Calc(); trial.setVisible(true); } }
  • 367. Layout Manager  Layout management is the process of determining the size and location of a container's components.  Java containers do not handle their own layout. They delegate that task to their layout manager, an instance of another class.  If you do not like a container's default layout manager, you can change it. Container content = getContentPane(); content.setLayout( new FlowLayout() );
  • 368. FlowLayout  FlowLayout, the simplest of the managers, simply adds components left to right until it can fit no more within its container's width.  It then starts a second line of components, fills that, starts a third, etc.  Each line is centered in the container  FlowLayout respects each component's preferred size and will use it to override a size set by setSize.  FlowLayout is the default layout manager for JPanel
  • 369. BorderLayout Zones  A border layout divides the container into five regions; each region may contain only one component  BorderLayout is the default LayoutManager for the contentpane of a JFrame North South West East Center
  • 370. Using Layout Managers BorderLayout <nameofcontainer>.setLayout(new BorderLayout()); When adding components to the container: <nameofcontainer>.add(<nameofcomponent>, BorderLayout.REGION); where REGION is either NORTH, SOUTH, WEST, CENTER OR EAST. JPanel panel = new JPanel(); // default // FlowLayout panel.setLayout(new BorderLayout()); panel.add(button,BorderLayout.NORTH);
  • 371. Using Layout Managers FlowLayout <nameofcontainer>.setLayout(new FlowLayout()); When adding components to the container: <nameofcontainer>.add(<nameofcomponent>); JPanel panel = new JPanel(); // default // FlowLayout //following line is redundant panel.setLayout(new FlowLayout()); panel.add(button);
  • 372. Exercise 5: Setting Layouts  Set the layout of the contentpane to BorderLayout  Add the ORANGE panel to the north region of the contentpane  Add the YELLOW panel to the south region of the contentpane
  • 373. Exercise 5: Answer . . . public Calc() { Container cp = getContentPane(); setDefaultCloseOperation(EXIT_ON_CLOSE); cp.setLayout(new BorderLayout()); cp.setBackground(Color.white); setTitle("My Funky Calculator"); setSize(XSIZE,YSIZE); . . . cp.add(entryPanel, BorderLayout.NORTH); cp.add(answerPanel,BorderLayout.SOUTH); }
  • 374. pack()  pack() method rearranges components such that any unused space is not shown  Add pack(); to the constructor of Calc. Make it the last statement in the constructor  Have you noticed a difference?
  • 375. Summary  When creating GUI, a JFrame is used; it interacts with the native system  A contentPane is automatically created when a JFrame is created. It has 5 zones where you can add a component (default layout is BorderLayout)  JPanel is the workhorse of most complicated interfaces. It is  a good all purpose container  the standard drawing surface  Swing containers have default layout managers but you can always change them  Swing is HUGE! You must explore it further.
  • 376. The End of the 16th Lecture
  • 378. The Java Event Model  In the last lecture, we learned how to construct a GUI to present information to the user.  But how do GUIs interact with users? How do applications recognize when the user has done something?
  • 379. package swinglab; import java.awt.*; import javax.swing.*; public class ClickReporter extends JFrame { public ClickReporter() { JButton myButton = new JButton("Click here"); Container cp = getContentPane(); cp.add(myButton); setTitle("Click Printer"); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); show(); } public static void main(String[] args) { ClickReporter cr = new ClickReporter(); } } ClickReporter
  • 380. ClickPrinter Listener package swinglab; import java.awt.event.*; class ClickPrinter implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button was pressed"); } }
  • 381. Adding a Listener public ClickReporter() { JButton myButton = new JButton("Click here"); ClickPrinter printer = new ClickPrinter(); click.addActionListener(printer); Container cp = getContentPane(); cp.add(myButton); setTitle("Click Printer"); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); show(); }
  • 382. ClickReporter  Each time you click the button a message is displayed in a console window. Button was pressed Click here
  • 383. Event Handling Diagram e.g. button, menu, text fields
  • 384. Event Handling  To be able to handle events in Java we need 3 things:  event sources  event objects  event listeners
  • 385. Event Sources  Event sources are components that can recognize user action: menus, buttons, text fields etc.  Event sources have methods to add event listeners to them like addActionListener  Event source reports on events and notifies all its listeners
  • 386. Event Source  In our ClickReporter class we create an event source, a JButton called myButton: JButton myButton = new JButton("Click here"); Click here
  • 387. Event Objects  Objects that represent a user action (e.g. mouse click) – contain detailed information about the event.  When an event happens an event source sends an event object to its event listeners  EventObject is the superclass  ActionEvent, MouseEvent, etc. are the subclasses that we use
  • 388. Event Objects  In our example, the event source – JButton myButton generates an event object representing a mouse click.  We are not going into details of EventObjects – we will need them only as arguments to the method actionPerformed in event listeners.
  • 389. Event Listeners  Event listeners are objects that respond when an event occurs  Any object , whose class implements the ActionListener interface, can be an event listener.  If the event listener has been added to an event source, the listener will be called when an event occurs on that source.
  • 390. ActionListener interface  Look it up at the API in the package java.awt.event: public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); }
  • 391. Event Listener In ClickReporter class we have an event listener – ClickPrinter object called printer: ClickPrinter printer = new ClickPrinter(); and add this listener to our JButton click: click.addActionListener(printer);
  • 392.  create an event source: JButton myButton = new JButton("Click here");  create an event listener: ClickPrinter printer = new ClickPrinter();  add listener to the source: click.addActionListener(printer);
  • 393.  Add the following data fields to your ClickReporter class: private JLabel counterLabel; private int counter = 0;  Add the following three lines to the ClickReporter constructor: cp.setLayout(new FlowLayout()); ClickCounter cc = new ClickCounter(this); click.addActionListener(cc);
  • 394.  Add these lines to your constructor: counterLabel = new JLabel( "The number of clicks is 0"); cp.add(counterLabel);  Add this method to ClickReporter: void incrementCounter(){ counterLabel.setText( "The number of clicks is " + (++counter)); pack(); }
  • 395. In your swinglab package create ClickCounter: package swinglab; import java.awt.event.*; class ClickCounter implements ActionListener { private ClickReporter clickReporter; ClickCounter(ClickReporter c) { clickReporter = c; } public void actionPerformed(ActionEvent e){ clickReporter.incrementCounter(); } }
  • 396. ClickCounter Diagram JButton ClickCounter ClickReporter actionPerformed incrementCounter  Button is pressed and notifies ClickCounter  ClickCounter tells ClickReporter to increment its counter
  • 397. A Calculator Listener package swinglab; import java.awt.event.*; class CalcListener implements ActionListener { private Calc calculator; CalcListener(Calc c) { calculator = c; } public void actionPerformed(ActionEvent e) { calculator.calculatePressed(); } }
  • 398. void calculatePressed() { double n1 = Double.parseDouble(num1.getText()); double n2 = Double.parseDouble(num2.getText()); String op = (String)operation.getSelectedItem(); double ans; if (op.equals(Calc.ADD_OP)) ans = n1 + n2; else if (op.equals(Calc.SUB_OP)) ans = n1 - n2; else if (op.equals(Calc.MUL_OP)) ans = n1 * n2; else ans = n1 / n2; answerLabel.setText("Answer: " + ans); pack(); }  Add this method to Calc class:
  • 399. Add the Calc Listener  In the Calc constructor, add an instance of CalcListener as a listener to the calculate button CalcListener cl = new CalcListener(this); calculate.addActionListener(cl);
  • 400. Quiz Question 1  Q: It's annoying to make a separate class for each listener. If any class can implement an interface, can't Calc implement ActionListener and listen for the events itself?  A: Yes
  • 401. Quiz Question 2  Q: Is it a good idea to have Calc be a listener for itself?  A: No. Calc is public, and if Calc implements ActionListener, then any outside class can use Calc to listen for unrelated events. Calc is only designed to handle Calc 's own events.
  • 402. Uh oh . . .  What happens when you type letters into the textfields and click the calculate button?  Exceptions are thrown!
  • 403. Exception Handling  Catch those exceptions and display an error message window describing the error to the user.  To show the error message window use the method JOptionPane.showMessageDialog  Hint: the parentComponent should be the Calc object itself
  • 404. Solution void calculatePressed() { double n1 = 0, n2 = 0; try { n1 = Double.parseDouble(num1.getText()); n2 = Double.parseDouble(num2.getText()); } catch(NumberFormatException e) { JOptionPane.showMessageDialog(this, "Must type two numbers, dummy!", "Not Numbers!", JOptionPane.ERROR_MESSAGE); } String op = (String)operation.getSelectedItem(); double ans; if (op.equals(Calc.ADD_OP)) ans = n1 + n2; else if (op.equals(Calc.SUB_OP)) ans = n1 - n2; else if (op.equals(Calc.MUL_OP)) ans = n1 * n2; else ans = n1 / n2; answerLabel.setText("Answer: " + ans); }
  • 406. Collections API  The package java.util is often called the "Collections API"  Extremely useful classes that you must understand to be a competent Java programmer  Divided into three main types of collections: lists, sets, and maps
  • 407. Collection Definitions  list – an ordered collection of elements that can have duplicates  set – an unordered collection of elements with no duplicates  map – an association between keys and values. Maps each key to a single value.
  • 408. Interface Hierarchy  Collections API organizes its classes into a hierarchy of interfaces Collection Map List Set
  • 409. Abstract Class Hierarchy  Abstract collection classes provide skeletal implementations of the interfaces  To implement your own collection, just subclass one of the abstract classes and implement the few abstract methods  No need to implement the entire interface from scratch.
  • 410. Concrete Collection Classes  The non-abstract (concrete) classes in the collections API provide good implementations of the interfaces  Use these unless you really need to implement your own.  The most widely used are ArrayList, LinkedList, HashSet, and HashMap
  • 412. Lists  list – an ordered collection of elements that can have duplicates  The List interface specifies the behavior of a list collection.  API provides two implementations of a list: ArrayList and LinkedList
  • 413. Collections Quiz 1 1. What type of collection would I use to store the players on the Ghana football team? 2. The schedule of the teams opponents for the Ghana football team? 3. T/F. All classes in the Collections API implement Collection? 4. T/F. If a class does not implement Comparable the elements cannot be sorted with Collections.sort set list false, maps do not false, w/ Comparator
  • 414. Collections Quiz 2  What's wrong with the equals method below? class Person { private int age; private String name; public boolean equals(Object o) { if (!(o instanceof Person)) return false; Person p = (Person)o; return age == p.age && name == p.name } name.equals(p.name)
  • 415. The Equals Method: Pop Quiz  What will the following code print out? Double a1 = new Double(95.0); Double a2 = new Double(95.0); ArrayList grades = new ArrayList(); grades.add(a1); System.out.println(grades.contains(a2)); a1 != a2 but true because a1.equals(a2)
  • 416. Two Forms of Equality  Reference Equality  objects are the same exact object  test with == operator  Logical Equality  objects are logically equivalent  test with the equals method  the object determines what it means for other objects to be logically equivalent to it
  • 417. Equals Method  Every class inherits an equals method from the class Object  The Object equals method just tests for reference equality (==)  For nearly all the classes you write, you should override the .equals method to provide a more useful test of logical equality
  • 418. 4 Steps to .equals Heaven 1. Use the instanceof keyword operator to check that the argument is the correct type. (This returns false if the argument is null.) 2. If it is not of the correct type, return false; otherwise cast the argument to that type 3. Check equality of each primitive data field of the argument using == 4. Check equality of each object data field of the argument using .equals
  • 419. ColorPoint .equals public class ColorPoint { private int x, y; private Color c; public boolean equals(Object o) { if (!(o instanceof ColorPoint)) { return false; } ColorPoint cp = (ColorPoint)o; return x == cp.x && y == cp.y && c.equals(cp.c); } }
  • 420. Comparing Objects  Sometimes we want to test not only equality, but whether one object is greater than or less than another object.  If a class implements the Comparable interface, it can be compared in this way  Or if there is a Comparator which compares instances of that class
  • 421. Comparable  The Comparable interface has only a single method compareTo  If the object is greater than the argument, then compareTo returns a positive integer  If the object is less then the argument, then compareTo returns a negative integer  If the argument is equal, compareTo returns 0
  • 422. Comparator  The Comparator interface only has a single method compareTo  If the first argument is greater than the second, compareTo returns a positive integer  If the first argument is less than the second, compareTo returns a negative integer  If the arguments are equal, compareTo returns 0
  • 423. Comparable Person public class Person implements Comparable { private int age; private String name; // sorts people first by age, then by name public int compareTo(Object o) { Person p = (Person)o; if (age != p.age) return age – p.age; else return
  • 424. Person Comparator public class PersonComparator implements Comparator { // sorts people first by age, then by name public int compareTo(Object o1, Object o2) { Person p1 = (Person)o1; Person p2 = (Person)o2; if (p1.age != p2.age) return p1.age – p2.age;
  • 425. Collections Class  If an class implements Comparable or has a Comparator, Lists of that class can be sorted with Collections.sort  The class Collections provides a lot of useful static methods that operate on and return collections.  Look there before writing your own.
  • 428. Overview of Sets  Recall from Collections 1 that a set is an unordered collection with no duplicates.  Which of the following is sure to be a set?  Students in this class  Coins in my pocket  Letters in the alphabet  The Collections API provides a Set Interface for you. Yes No, can have 2 of the same coin Yes
  • 429. The Set Interface  The set interface provides the five basic operations to manipulate sets.  Add an element  Remove an element  Find the size of the set  List all the elements in the set  Check if an element is in the set
  • 430. The Set Interface  add(x)  Adds element x to the set. If x was already present, nothing changes.  remove(x)  Removes x from the set if x was present, else leaves the set unchanged.  size()  Returns an int indicating the current size of the set
  • 431. The Set Interface  iterator()  Returns an Iterator object over the elements in the set.  This provides a way to ‘look’ at all the elements in the set in turn. (Note: Remember that the set has no specified order.)  contains(x)  Returns a boolean representing whether or not the set contains x.
  • 432. Hashing  Hashing is a technique that can save on search time and storage space.  Java Objects such as HashSet and HashMap are based on this technique.  This section will teach you how these classes work and how to use them effectively.
  • 433. Hashing Example  Imagine each student at this school has a sheet with their info on it.  Someone wants to know whether or not a person is a student here.  If there is no order to the sheets we would have to look through all of them.  Can we improve upon this to reduce the search time?
  • 434. Hashing Example  Lets say we have two bins, one for sheets of male students and one for female.  If we are told the sex of the person we need only check in one bin.  We could do the same for any characteristic such as age, weight, eye color.  Some of these will be more useful than others depending on how many bins there are and how many sheets in each bin.
  • 435. Hashing Example  An important property is that each bin has approx the same number of student sheets.  Suppose we want 100 bins. Which of the following do you think has the above property?  Bin for each age from 1 – 100 years  Bin for each height 100 – 199 cm  Bin for each last two digits of phone no.
  • 436. Hash Code  A hash code is an integer associated with an object that can be derived from the object.  Every object in Java has a hashCode() method that returns an int.  Classes such as HashSet and HashMap use the number to store objects in bins just like our student example.  If we call contains(x) on a HashSet, instead of looking through the whole set for x, Java will only look in the bin corresponding to x.hashcode()
  • 437. Hash Code Problem  As described, hashing divides elements into many bins for quick retrieval and lookup.  What could happen if two equal elements do not have the same hash code?  You could put an element in a bin and not be able to find it again because you look in the wrong bin!
  • 438. hashCode() and equals()  If two elements are equal we need them to map to the same bin!  This must be true of any hash code: x.equals(y) implies x.hashCode() = y.hashCode()  When you override hashCode you must override equals
  • 439. How to write hashCode()  Return some computation on the hash codes of each of the fields: public class Student { String name; int year; public int hashCode() { return 7 * name.hashCode() + year + 33; } }