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!
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
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!
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[])
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.
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
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
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
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.*;
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;
}
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
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.
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.
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
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
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