Lec 00 Java Revision
Lec 00 Java Revision
2
Copyright 2008 by Pearson Education
System.out.println
A statement that prints a line of output on the console.
pronounced "print-linn"
sometimes called a "println statement" for short
• System.out.println("text");
• System.out.println();
3
Copyright 2008 by Pearson Education
Static methods (1.4)
static method: A named group of statements.
denotes the structure of a program
class
eliminates redundancy by code reuse
method A
statement
procedural decomposition:
statement
dividing a problem into methods
statement
method B
statement
Writing a static method is like
statement
adding a new command to Java. method C
statement
statement
statement
4
Copyright 2008 by Pearson Education
Declaring a method
Gives your method a name so it can be executed
Syntax:
public static void name() {
statement;
statement;
...
statement;
}
Example:
public static void printWarning() {
System.out.println("This product causes cancer");
System.out.println("in lab rats and humans.");
}
5
Copyright 2008 by Pearson Education
Calling a method
Executes the method's code
Syntax:
name();
You can call the same method many times if you like.
Example:
printWarning();
Output:
6
Copyright 2008 by Pearson Education
Control flow
When a method is called, the program's execution...
"jumps" into that method, executing its statements, then
"jumps" back to the point where the method was called.
System.out.println("Done System.out.println("Done
with main."); with message2.");
} }
8
Copyright 2008 by Pearson Education
Expressions
expression: A value or operation that computes a value.
• Examples: 1 + 4 * 5
(7 + 2) * 6 / 3
42
The simplest expression is a literal value.
A complex expression can use operators and parentheses.
9
Copyright 2008 by Pearson Education
Integer division with /
When we divide integers, the quotient is also an integer.
14 / 4 is 3, not 3.5
3 4 52
4 ) 14 10 ) 45 27 ) 1425
12 40 135
2 5 75
54
21
More examples:
32 / 5 is 6
84 / 10 is 8
156 / 100 is 1
10
Copyright 2008 by Pearson Education
Integer remainder with %
The % operator computes the remainder from integer division.
14 % 4 is 2
218 % 5 is 3 What is the result?
3 43 45 % 6
4 ) 14 5 ) 218 2 % 2
12 20 8 % 20
2 18
15 11 % 0
3
Applications of % operator:
Obtain last digit of a number: 230857 % 10 is 7
Obtain last 4 digits: 658236489 % 10000 is
6489
See whether a number is odd: 7 % 2 is 1, 42 % 2 is 0
11
Copyright 2008 by Pearson Education
Precedence
precedence: Order in which operators are evaluated.
Generally operators evaluate left-to-right.
1 - 2 - 3 is (1 - 2) - 3 which is -4
1 + 3 * 4 is 13
6 + 8 / 2 * 3
6 + 4 * 3
6 + 12 is 18
13
Copyright 2008 by Pearson Education
Variables (2.2)
variable: A piece of the computer's memory that is given a
name and type, and can store a value.
Syntax:
type name = value;
x 14
double myGPA = 3.95;
14
Copyright 2008 by Pearson Education
Type casting
type cast: A conversion from one type to another.
To promote an int into a double to get exact division from /
To truncate a double from a real number to an integer
Syntax:
(type) expression
Examples:
double result = (double) 19 / 5; // 3.8
int result2 = (int) result; // 3
int x = (int) Math.pow(10, 3); // 1000
15
Copyright 2008 by Pearson Education
Increment and decrement
shortcuts to increase or decrease a variable's value by 1
int x = 2;
x++; // x = x + 1;
// x now stores 3
double gpa = 2.5;
gpa--; // gpa = gpa - 1;
// gpa now stores 1.5
16
Copyright 2008 by Pearson Education
Modify-and-assign operators
shortcuts to modify a variable's value
x += 3; // x = x + 3;
gpa -= 0.5; // gpa = gpa - 0.5;
number *= 2; // number = number * 2;
17
Copyright 2008 by Pearson Education
for loops (2.3)
for (initialization; test; update) { header
statement;
statement;
... body
statement;
}
18
Copyright 2008 by Pearson Education
System.out.print
Prints without moving to a new line
allows you to print partial messages on the same line
int highestTemp = 5;
for (int i = -3; i <= highestTemp / 2; i++) {
System.out.print((i * 1.8 + 32) + " ");
}
• Output:
26.6 28.4 30.2 32.0 33.8 35.6
19
Copyright 2008 by Pearson Education
Nested loops
nested loop: A loop placed inside another loop.
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print((i * j) + "\t");
}
System.out.println(); // to end the line
}
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
20
Copyright 2008 by Pearson Education
Variable scope
scope: The part of a program where a variable exists.
From its declaration to the end of the { } braces
A variable declared in a for loop exists only in that loop.
A variable declared in a method exists only in that method.
21
Copyright 2008 by Pearson Education
Class constants (2.4)
class constant: A value visible to the whole program.
value can only be set at declaration
value can't be changed while the program is running
Syntax:
public static final type name = value;
name is usually in ALL_UPPER_CASE
Examples:
public static final int DAYS_IN_WEEK = 7;
public static final double INTEREST_RATE = 3.5;
public static final int SSN = 658234569;
22
Copyright 2008 by Pearson Education
Parameters (3.1)
parameter: A value passed to a method by its caller.
7
mai lin ******
n e *
1 lin ************
3 e *
23
Copyright 2008 by Pearson Education
Passing parameters
Declaration:
public static void name (type name, ..., type name) {
statement(s);
}
Call:
methodName (value, value, ..., value);
Example:
public static void main(String[] args) {
sayPassword(42); // The password is: 42
sayPassword(12345); // The password is: 12345
}
public static void sayPassword(int code) {
System.out.println("The password is: " + code);
} 24
Copyright 2008 by Pearson Education
Java's Math class (3.2)
Method name Description
Math.abs(value) absolute value
Math.round(value) nearest whole number
Math.ceil(value) rounds up
Math.floor(value) rounds down
Math.log10(value) logarithm, base 10
Math.max(value1, value2) larger of two values
Math.min(value1, value2) smaller of two values
Math.pow(base, exp) base to the exp power
Math.sqrt(value) square root
Math.sin(value) sine/cosine/tangent of
Math.cos(value) an angle in radians Constant Description
Math.tan(value) Math.E 2.7182818...
Math.toDegrees(value) convert degrees to Math.PI 3.1415926...
Math.toRadians(value) radians and back
Math.random() random double between 0 and 1
25
Copyright 2008 by Pearson Education
Return (3.2)
return: To send out a value as the result of a method.
The opposite of a parameter:
Parameters send information in from the caller to the method.
Return values send information out from a method to its caller.
- Math.abs(42
42 )
4
mai 2
n 2.7
1
3
Math.round(2.71
)
26
Copyright 2008 by Pearson Education
Returning a value
public static type name(parameters) {
statements;
...
return expression;
}
Example:
// Returns the slope of the line between the given points.
public static double slope(int x1, int y1, int x2, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
return dy / dx;
}
27
Copyright 2008 by Pearson Education
Strings (3.3)
string: An object storing a sequence of text characters.
String name = "text";
String name = expression;
28
Copyright 2008 by Pearson Education
String methods
Method name Description
indexOf(str) index where the start of the given string
appears in this string (-1 if it is not there)
length() number of characters in this string
substring(index1, index2) the characters in this string from index1
or (inclusive) to index2 (exclusive);
substring(index1) if index2 omitted, grabs till end of string
toLowerCase() a new string with all lowercase letters
toUpperCase() a new string with all uppercase letters
29
Copyright 2008 by Pearson Education
String test methods
Method Description
equals(str) whether two strings contain the same characters
equalsIgnoreCase(str) whether two strings contain the same characters,
ignoring upper vs. lower case
startsWith(str) whether one contains other's characters at start
endsWith(str) whether one contains other's characters at end
contains(str) whether the given string is found within this one
31
Copyright 2008 by Pearson Education
Type char (4.4)
char : A primitive type representing single characters.
Each character inside a String is stored as a char value.
Literal char values are surrounded with apostrophe
(single-quote) marks, such as 'a' or '4' or '\n' or '\''
32
Copyright 2008 by Pearson Education
char vs. String
"h" is a String
'h' is a char (the two behave differently)
What is s + 1 ? What is c + 1 ?
What is s + s ? What is c + c ?
33
Copyright 2008 by Pearson Education
System.out.printf (4.4)
System.out.printf("format string", parameters);
A format string contains placeholders to insert parameters into it:
%d an integer
%f a real number
%s a string
%8d an integer, 8 characters wide, right-aligned
%-8d an integer, 8 characters wide, left-aligned
%.4f a real number, 4 characters after decimal
%6.2f a real number, 6 characters wide, 2 after
decimal
Example:
int x = 3, y = 2;
System.out.printf("(%d, %d)\n", x, y); // (3, 2)
System.out.printf("%4d %4.2f\n", x, y); // 3 2.00
34
Copyright 2008 by Pearson Education
DrawingPanel (3G)
"Canvas" objects that represents windows/drawing surfaces
Example:
DrawingPanel panel = new DrawingPanel(300, 200);
(0, 0)
x+
The window has nothing on it.
We can draw shapes and lines
on it using another object of
type Graphics. y+
35
Copyright 2008 by Pearson Education
Graphics
"Pen" objects that can draw lines and shapes
36
Copyright 2008 by Pearson Education
Graphics methods
Method name Description
g.drawLine(x1, y1, x2, y2); line between points (x1, y1), (x2, y2)
g.drawOval(x, y, width, height); outline largest oval that fits in a box of
size width * height with top-left at (x, y)
g.drawRect(x, y, width, height); outline of rectangle of size
width * height with top-left at (x, y)
g.drawString(text, x, y); text with bottom-left at (x, y)
g.fillOval(x, y, width, height); fill largest oval that fits in a box of size
width * height with top-left at (x, y)
g.fillRect(x, y, width, height); fill rectangle of size width * height with
top-left at (x, y)
g.setColor(Color); set Graphics to paint any following
shapes in the given color
37
Copyright 2008 by Pearson Education
Color
Create one using Red-Green-Blue (RGB) values from 0-255
Color name = new Color(red, green, blue);
Example:
Color brown = new Color(192, 128, 64);
System.in
not intended to be used directly
We use a second object, from a class Scanner, to help us.
39
Copyright 2008 by Pearson Education
Scanner methods
Method Description
nextInt() reads a token of user input as an int
nextDouble() reads a token of user input as a double
next() reads a token of user input as a String
nextLine() reads a line of user input as a String
Each method waits until the user presses Enter.
The value typed is returned.
40
Copyright 2008 by Pearson Education
Testing for valid input (5.3)
Scanner methods to see what the next token will be:
Method Description
hasNext() returns true if there are any more tokens of
input to read (always true for console input)
hasNextInt() returns true if there is a next token
and it can be read as an int
hasNextDouble() returns true if there is a next token
and it can be read as a double
hasNextLine() returns true if there are any more lines of
input to read (always true for console input)
These methods do not consume input;
they just give information about the next token.
Useful to see what input is coming, and to avoid crashes.
41
Copyright 2008 by Pearson Education
Cumulative sum (4.1)
A loop that adds the numbers from 1-1000:
int sum = 0;
for (int i = 1; i <= 1000; i++) {
sum = sum + i;
}
System.out.println("The sum is " + sum);
Key idea:
Cumulative sum variables must be declared outside the loops
that update them, so that they will exist after the loop.
42
Copyright 2008 by Pearson Education
if/else (4.2)
Executes one block if a test is true, another if false
if (test) {
statement(s);
} else {
statement(s);
}
Example:
double gpa = console.nextDouble();
if (gpa >= 2.0) {
System.out.println("Welcome to Mars University!");
} else {
System.out.println("Application denied.");
}
43
Copyright 2008 by Pearson Education
Relational expressions
A test in an if is the same as in a for loop.
for (int i = 1; i <= 10; i++) { ...
if (i <= 10) { ...
These are boolean expressions, seen in Ch. 5.
46
Copyright 2008 by Pearson Education
De Morgan's Law
De Morgan's Law:
Rules used to negate or reverse boolean expressions.
Useful when you want the opposite of a known boolean test.
48
Copyright 2008 by Pearson Education
Fencepost loops (4.1)
fencepost problem: When we want to repeat two tasks,
one of them n times, another n-1 or n+1 times.
Add a statement outside the loop to place the initial "post."
Also called a fencepost loop or a "loop-and-a-half" solution.
Algorithm template:
place a post.
for (length of fence - 1) {
place some wire.
place a post.
}
49
Copyright 2008 by Pearson Education
Fencepost method solution
Write a method printNumbers that prints each number
from 1 to a given maximum, separated by commas.
For example, the call:
printNumbers(5);
should print:
1, 2, 3, 4, 5
Solution:
public static void printNumbers(int max) {
System.out.print(1);
for (int i = 2; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line
} 50
Copyright 2008 by Pearson Education
while loops (5.1)
while loop: Repeatedly executes its
body as long as a logical test is true.
while (test) {
statement(s);
}
Example:
int num = 1; // initialization
while (num <= 200) { // test
System.out.print(num + " ");
num = num * 2; // update
}
OUTPUT:
1 2 4 8 16 32 64 128
51
Copyright 2008 by Pearson Education
do/while loops (5.4)
do/while loop: Executes statements repeatedly while a
condition is true, testing it at the end of each repetition.
do {
statement(s);
} while (test);
Example:
52
Copyright 2008 by Pearson Education
The Random class (5.1)
A Random object generates pseudo-random* numbers.
Class Random is found in the java.util package.
import java.util.*;
Method name Description
nextInt() returns a random integer
nextInt(max) returns a random integer in the range [0, max)
in other words, 0 to max-1 inclusive
nextDouble() returns a random real number in the range [0.0, 1.0)
Example:
53
Copyright 2008 by Pearson Education
"Boolean Zen"
Students new to boolean often test if a result is true:
if (bothOdd(7, 13) == true) { // bad
...
}
56
Copyright 2008 by Pearson Education
Reading files (6.1)
To read a file, pass a File when constructing a Scanner.
Scanner name = new Scanner(new File("file name"));
Example:
File file = new File("mydata.txt");
Scanner input = new Scanner(file);
57
Copyright 2008 by Pearson Education
The throws clause
throws clause: Keywords on a method's header that state
that it may generate an exception.
Syntax:
public static type name(params) throws type {
Example:
public class ReadFile {
public static void main(String[] args)
throws FileNotFoundException {
Like saying, "I hereby announce that this method might throw
an exception, and I accept the consequences if it happens."
58
Copyright 2008 by Pearson Education
Input tokens (6.2)
token: A unit of user input, separated by whitespace.
A Scanner splits a file's contents into tokens.
59
Copyright 2008 by Pearson Education
Files and input cursor
Consider a file numbers.txt that contains this text:
308.2
14.9 7.4 2.8
60
Copyright 2008 by Pearson Education
Consuming tokens
consuming input: Reading input and advancing the cursor.
Calling nextInt etc. moves the cursor past the current token.
61
Copyright 2008 by Pearson Education
Scanner exceptions
InputMismatchException
You read the wrong type of token (e.g. read "hi" as int).
NoSuchElementException
You read past the end of the input.
62
Copyright 2008 by Pearson Education
Output to files (6.4)
PrintStream: An object in the java.io package that lets
you print output to a destination such as a file.
Any methods you have used on System.out
(such as print, println) will work on a PrintStream.
Syntax:
PrintStream name = new PrintStream(new File("file name"));
Example:
PrintStream output = new PrintStream(new File("out.txt"));
output.println("Hello, file!");
output.println("This is a second line of output.");
63
Copyright 2008 by Pearson Education
System.out and PrintStream
The console output object, System.out, is a PrintStream.
64
Copyright 2008 by Pearson Education
Arrays (7.1)
array: object that stores many values of the same type.
element: One value in an array.
index: A 0-based integer to access an element from an array.
inde 0 1 2 3 4 5 6 7 8 9
x
value 12 49 -2 26 5 17 -6 84 72 3
65
Copyright 2008 by Pearson Education
Array declaration
type[] name = new type[length];
Example:
int[] numbers = new int[10];
inde 0 1 2 3 4 5 6 7 8 9
x
valu 0 0 0 0 0 0 0 0 0 0
e
66
Copyright 2008 by Pearson Education
Accessing elements
name[index] // access
name[index] = value; // modify
Example:
numbers[0] = 27;
numbers[3] = -6;
System.out.println(numbers[0]);
if (numbers[3] < 0) {
System.out.println("Element 3 is negative.");
}
inde 0 1 2 3 4 5 6 7 8 9
x
value 27
0 0 0 -6
0 0 0 0 0 0 0
67
Copyright 2008 by Pearson Education
Out-of-bounds
Legal indexes: between 0 and the array's length - 1.
Reading or writing any index outside this range will throw an
ArrayIndexOutOfBoundsException.
Example:
int[] data = new int[10];
System.out.println(data[0]); // okay
System.out.println(data[9]); // okay
System.out.println(data[-1]); // exception
System.out.println(data[10]); // exception
inde 0 1 2 3 4 5 6 7 8 9
x
value 0 0 0 0 0 0 0 0 0 0
68
Copyright 2008 by Pearson Education
The length field
An array's length field stores its number of elements.
name.length
69
Copyright 2008 by Pearson Education
Quick array initialization
type[] name = {value, value, … value};
Example:
int[] numbers = {12, 49, -2, 26, 5, 17, -6};
inde 0 1 2 3 4 5 6
x
valu 12 49 -2 26 5 17 -6
e
Useful when you know what the array's elements will be.
The compiler figures out the size by counting the values.
70
Copyright 2008 by Pearson Education
The Arrays class
Class Arrays in package java.util has useful static
methods for manipulating arrays:
Method name Description
binarySearch(array, value) returns the index of the given value
in a sorted array (< 0 if not found)
equals(array1, array2) returns true if the two arrays
contain the same elements in the
same order
fill(array, value) sets every element in the array to
have the given value
sort(array) arranges the elements in the array
into ascending order
toString(array) returns a string representing the
array, such as "[10, 30, 17]"
71
Copyright 2008 by Pearson Education
Arrays as parameters
Declaration:
public static type methodName(type[] name) {
Example:
public static double average(int[] numbers) {
...
}
Call:
methodName(arrayName);
Example:
int[] scores = {13, 17, 12, 15, 11};
double avg = average(scores);
72
Copyright 2008 by Pearson Education
Arrays as return
• Declaring:
public static type[] methodName(parameters) {
Example:
• Calling:
type[] name = methodName(parameters);
Example:
int x = 5;
int y = x; // x = 5, y = 5 x
y = 17; // x = 5, y = 17
x = 8; // x = 8, y = 17
y
74
Copyright 2008 by Pearson Education
Reference semantics (objects)
reference semantics: Behavior where variables actually
store the address of an object in memory.
When one reference variable is assigned to another, the object
is not copied; both variables refer to the same object.
Modifying the value of one variable will affect others.
a1 inde 0 1 2 3 4 5 6
x
a2 value
valu 7
4 5 2 12 14 14 9
e
75
Copyright 2008 by Pearson Education
Null
null : A reference that does not refer to any object.
Fields of an object that refer to objects are initialized to null.
The elements of an array of objects are initialized to null.
inde 0 1 2 3 4
words x
valu null null null null null
e
inde 0 1 2
windows x
value null null null
76
Copyright 2008 by Pearson Education
Null pointer exception
dereference: To access data or methods of an object with
the dot notation, such as s.length().
It is illegal to dereference null (causes an exception).
null is not any object, so it has no methods or data.
Output:
word is: null
Exception in thread "main"
java.lang.NullPointerException
at Example.main(Example.java:8)
77
Copyright 2008 by Pearson Education
Classes and objects (8.1)
class: A program entity that represents either:
1. A program / module, or
2. A template for a new type of objects.
78
Copyright 2008 by Pearson Education
Fields (8.2)
field: A variable inside an object that is part of its state.
Each object has its own copy of each field.
encapsulation: Declaring fields private to hide their data.
Declaration syntax:
private type name;
Example:
79
Copyright 2008 by Pearson Education
Instance methods
instance method: One that exists inside each object of a
class and defines behavior of that object.
Example:
public void shout() {
System.out.println("HELLO THERE!");
}
80
Copyright 2008 by Pearson Education
A Point class
public class Point {
private int x;
private int y;
// Changes the location of this Point object.
public void draw(Graphics g) {
g.fillOval(x, y, 3, 3);
g.drawString("(" + x + ", " + y + ")", x, y);
}
}
Each Point object contains data fields named x and y.
Each Point object contains a method named draw that draws
that point at its current x/y position.
81
Copyright 2008 by Pearson Education
The implicit parameter
implicit parameter:
The object on which an instance method is called.
During the call p1.draw(g);
the object referred to by p1 is the implicit parameter.
82
Copyright 2008 by Pearson Education
Kinds of methods
Instance methods take advantage of an object's state.
Some methods allow clients to access/modify its state.
83
Copyright 2008 by Pearson Education
Constructors (8.4)
constructor: Initializes the state of new objects.
public type(parameters) {
statements;
}
Example:
public Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}
To call a method:
this.method(parameters);
86
Copyright 2008 by Pearson Education
Static methods
static method: Part of a class, not part of an object.
shared by all objects of that class
good for code related to a class but not to each object's state
Declaration syntax:
87
Copyright 2008 by Pearson Education
Inheritance (9.1)
inheritance: A way to form new classes based on existing
classes, taking on their attributes/behavior.
a way to group related classes
a way to share code between two or more classes
88
Copyright 2008 by Pearson Education
Inheritance syntax (9.1)
public class name extends superclass {
Example:
89
Copyright 2008 by Pearson Education
Overriding methods (9.1)
override: To write a new version of a method in a subclass
that replaces the superclass's version.
No special syntax required to override a superclass method.
Just write a new version of it in the subclass.
90
Copyright 2008 by Pearson Education
super keyword (9.3)
Subclasses can call overridden methods with super
super.method(parameters)
Example:
public class LegalSecretary extends Secretary {
public double getSalary() {
double baseSalary = super.getSalary();
return baseSalary + 5000.0;
}
...
}
91
Copyright 2008 by Pearson Education
Polymorphism
polymorphism: Ability for the same code to be used with
different types of objects and behave differently with each.
Example: System.out.println can print any type of object.
Each one displays in its own way on the console.