Java Review
Java Review
Java Review
This document is copyright (C) Marty Stepp and Stanford Computer Science.
Licensed under Creative Commons Attribution 2.5 License. All rights reserved.
Variables
●
variable: A piece of the computer's memory that is given a
name and type, and can store a value.
●
A variable can be declared/initialized in one statement.
●
Syntax:
type name = value;
x 14
– double myGPA = 3.95;
myGPA 3.95
– int x = (11 % 3) + 12;
Java's primitive types
primitive types: 8 simple types for numbers, text, etc.
Java also has object types, which we'll talk about later
●
Syntax:
(type) expression
Examples:
double result = (double) 19 / 5; // 3.8
int result2 = (int) result; // 3
int x = (int) Math.pow(10, 3); // 1000
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
Precedence
●
precedence: Order in which operators are evaluated.
– Generally operators evaluate left-to-right.
1 - 2 - 3 is (1 - 2) - 3 which is -4
●
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;
Passing parameters
●
Declaration:
public 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);
}
Return
●
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.
-42 Math.abs(42)
42
main
2.71
3
Math.round(2.71)
Java's Math class
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
an angle in radians
Math.cos(value) 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
●
Example:
// Returns the slope of the line between the given points.
public double slope(int x1, int y1, int x2, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
return dy / dx;
}
Strings
string: An object storing a sequence of text characters.
String name = "text";
String name = expression;
●
These methods are called using the dot notation:
String gangsta = "Dr. Dre";
System.out.println(gangsta.length()); // 7
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
●
char values can be concatenated with strings.
char initial = 'P';
System.out.println(initial + " Diddy"); // P
Diddy
char vs. String
"h" is a String
'h' is a char (the two behave differently)
String is an object; it contains methods
String s = "h";
s = s.toUpperCase(); // 'H'
int len = s.length(); // 1
char first = s.charAt(0); // 'H'
What is s + 1 ? What is c + 1 ?
What is s + s ? What is c + c ?
if/else
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.");
}
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.
●
"Truth tables" for each, used with logical values p and q:
p q p && q p || q p !p
true true true true true false
true false false true false true
false true false true
false false false false
Type boolean
●
boolean: A logical type whose values are true and false.
– A test in an if, for, or while is a boolean expression.
– You can create boolean variables, pass boolean parameters, return
boolean values from methods, ...
●
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
do/while loops
● 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:
// prompt until the user gets the right password
String phrase;
do {
System.out.print("Password: ");
phrase = console.next();
} while (!phrase.equals("abracadabra"));
The Random class
●
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
– Example:
Random rand = new Random();
int randomNumber = rand.nextInt(10); // 0-9
break
●
break statement: Immediately exits a loop.
– Can be used to write a loop whose test is in the middle.
– Such loops are often called "forever" loops because their header's
boolean test is often changed to a trivial true.
while (true) {
statement(s);
if (test) {
break;
}
statement(s);
}
index 0 1 2 3 4 5 6 7 8 9
value 12 49 -2 26 5 17 -6 84 72 3
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
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.");
}
index 0 1 2 3 4 5 6 7 8 9
value 27
0 0 0 -6
0 0 0 0 0 0 0
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
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
The length field
●
An array's length field stores its number of elements.
name.length
index 0 1 2 3 4 5 6
value 12 49 -2 26 5 17 -6
Useful when you know what the array's elements will be.
The compiler figures out the size by counting the values.
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
Example:
public double average(int[] numbers) {
...
}
Call:
methodName(arrayName);
Example:
int[] scores = {13, 17, 12, 15, 11};
double avg = average(scores);
Arrays as return
• Declaring:
public type[] methodName(parameters) {
Example:
public int[] countDigits(int n) {
int[] counts = new int[10];
...
return counts;
}
• Calling:
type[] name = methodName(parameters);
Example:
public static void main(String[] args) {
int[] tally = countDigits(229231007);
System.out.println(Arrays.toString(tally));
}
Value semantics (primitives)
●
value semantics: Behavior where values are copied when
assigned to each other or passed as parameters.
– When one primitive variable is assigned to another,
its value is copied.
– Modifying the value of one variable does not affect others.
int x = 5;
x
int y = x; // x = 5, y = 5
y = 17; // x = 5, y = 17
x = 8; // x = 8, y = 17 y
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.
value 4
7 5 2 12 14 14 9
a2
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.
String[] words = new String[5];
Point[] points = new Point[3];
index 0 1 2 3 4
words
value null null null null null
index 0 1 2
points
value null null null
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)
Classes and objects
class: A program entity that represents either:
1. A program / module, or
2. A template for a new type of objects.
●
Declaration syntax:
private type name;
– Example:
public class Student {
private String name; // each object now has
private double gpa; // a name and gpa field
}
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!");
}
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.
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.
– During the call p2.draw(g);
the object referred to by p2 is the implicit parameter.
●
accessor: A method that lets clients examine object state.
– Example: A distanceFromOrigin method that tells how far a
Point is away from (0, 0).
– Accessors often have a non-void return type.
●
mutator: A method that modifies an object's state.
– Example: A translate method that shifts the position of a Point
by a given amount.
Constructors
●
constructor: Initializes the state of new objects.
public type(parameters) {
statements;
}
– Example:
public Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}
●
Syntax for using this:
– To refer to a field:
this.field
– To call a method:
this.method(parameters);
●
Declaration syntax:
public static type name(parameters) {
statements;
}
Inheritance
●
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
●
One class can extend another, absorbing its data/behavior.
– superclass: The parent class that is being extended.
– subclass: The child class that extends the superclass and inherits its
behavior.
●
Subclass gets a copy of every field and method from superclass
Inheritance syntax
public class name extends superclass {
Example:
●
A variable of type T can hold an object of any subclass of T.
Employee ed = new LegalSecretary();
●
When a method is called, it behaves as a LegalSecretary.
System.out.println(ed.getSalary()); // 55000.0
System.out.println(ed.getVacationForm()); // pink
Collections and lists
●
collection: an object that stores data ("elements")
import java.util.*; // to use Java's collections
●
list: a collection of elements with 0-based indexes
– elements can be added to the front, back, or elsewhere
– a list has a size (number of elements that have been added)
– in Java, a list can be represented as an ArrayList object
Idea of a list
●
An ArrayList is like an array that resizes to fit its contents.
●
When a list is created, it is initially empty.
[]
●
You can add items to the list. (By default, adds at end of list)
[hello, ABC, goodbye, okay]
– The list object keeps track of the element values that have been added
to it, their order, indexes, and its total size.
– You can add, remove, get, set, ... any index at any time.
Type parameters (generics)
ArrayList<Type> name = new ArrayList<Type>();
●
When constructing an ArrayList, you must specify the
type of its elements in < >
– This is called a type parameter ; ArrayList is a generic class.
– Allows the ArrayList class to store lists of different types.
●
Example:
// Returns count of plural words in the given list.
public int countPlural(ArrayList<String> list) {
int count = 0;
for (int i = 0; i < list.size(); i++) {
String str = list.get(i);
if (str.endsWith("s")) {
count++;
}
}
return count;
}
Throwing exceptions
throw new ExceptionType();
throw new ExceptionType("message");
●
Generates an exception that will crash the program,
unless it has code to handle ("catch") the exception.
●
Common exception types:
– ArithmeticException, ArrayIndexOutOfBoundsException, FileNotFoundException, IllegalArgumentException,
IllegalStateException, IOException, NoSuchElementException, NullPointerException, RuntimeException,
UnsupportedOperationException
●
Why would anyone ever want a program to crash?
Sets
●
set: A collection of unique values (no duplicates allowed)
that can perform the following operations efficiently:
– add, remove, search (contains)
"the"
"if" "of"
set.contains("to") "to"
"down" "from" true
"by" "she"
set.contains("be") "you" false
"in"
"why" "him"
set
Set implementation
●
in Java, sets are represented by Set type in java.util
• Set is implemented by HashSet and TreeSet classes
●
Provides a clean syntax for looping over the elements of a Set,
List, array, or other collection
Set<Double> grades = new HashSet<Double>();
...
●
basic map operations:
– put(key, value ): Adds a
mapping from a key to
a value.
– remove(key ): Removes
the given key and its
myMap.get("Juliet") returns "Capulet"
mapped value.
Map implementation
●
in Java, maps are represented by Map type in java.util
• Map is implemented by the HashMap and TreeMap classes
– HashMap: implemented using an array called a "hash table";
extremely fast: O(1) ; keys are stored in unpredictable order
– Later, we can supply only the key and get back the related value:
Allows us to ask: What is Suzy's phone number?
get("Suzy")
Map
"206-685-2181"
keySet and values
• keySet method returns a Set of all keys in the map
– can loop over the keys in a foreach loop
– can get each key's associated value by calling get on the map
Map<String, Integer> ages = new TreeMap<String, Integer>();
ages.put("Marty", 19);
ages.put("Geneva", 2); // ages.keySet() returns Set<String>
ages.put("Vicki", 57);
for (String name : ages.keySet()) { // Geneva -> 2
int age = ages.get(name); // Marty -> 19
System.out.println(name + " -> " + age); // Vicki -> 57
}
●
A call of A.compareTo(B) will return:
a value < 0 if A comes "before" B in the ordering,
a value > 0 if A comes "after" B in the ordering,
or 0 if A and B are considered "equal" in the ordering.
Using compareTo
• compareTo can be used as a test in an if statement.
String a = "alice";
String b = "bob";
if (a.compareTo(b) < 0) { // true
...
}
Primitives Objects
if (a < b) { ... if (a.compareTo(b) < 0) { ...
if (a <= b) { ... if (a.compareTo(b) <= 0) { ...
if (a == b) { ... if (a.compareTo(b) == 0) { ...
if (a != b) { ... if (a.compareTo(b) != 0) { ...
if (a >= b) { ... if (a.compareTo(b) >= 0) { ...
if (a > b) { ... if (a.compareTo(b) > 0) { ...
compareTo and collections
●
You can use an array or list of strings with Java's included binary
search method because it calls compareTo internally.
String[] a = {"al", "bob", "cari", "dan", "mike"};
int index = Arrays.binarySearch(a, "dan"); // 3
●
Java's TreeSet/Map use compareTo internally for ordering.
Set<String> set = new TreeSet<String>();
for (String s : a) {
set.add(s);
}
System.out.println(s);
// [al, bob, cari, dan, mike]
Ordering our own types
●
We cannot binary search or make a TreeSet/Map of arbitrary
types, because Java doesn't know how to order the elements.
– The program compiles but crashes when we run it.
●
A class can implement the Comparable interface to define a
natural ordering function for its objects.
●
A call to your compareTo method should return:
a value < 0 if this object comes "before" the other object,
a value > 0 if this object comes "after" the other object,
or0 if this object is considered "equal" to the other.
• If you want multiple orderings, use a Comparator instead (see Ch. 13.1)
Comparable example
public class Point implements Comparable<Point> {
private int x;
private int y;
...
// sort by x and break ties by y
public int compareTo(Point other) {
if (x < other.x) {
return -1;
} else if (x > other.x) {
return 1;
} else if (y < other.y) {
return -1; // same x, smaller y
} else if (y > other.y) {
return 1; // same x, larger y
} else {
return 0; // same x and same y
}
}
}
Collections class
Method name Description
binarySearch(list, value) returns the index of the given value in a
sorted list (< 0 if not found)
copy(listTo, listFrom) copies listFrom's elements to listTo
emptyList(), emptyMap(), returns a read-only collection of the given
emptySet() type that has no elements
fill(list, value) sets every element in the list to have the
given value
max(collection), min(collection) returns largest/smallest element
●
override: To replace a superclass's method by writing a new
version of that method in a subclass.
public class Lawyer extends Employee {
// overrides getSalary in Employee; a raise!
public double getSalary() {
return 55000.00;
}
}
The super keyword
super.method(parameters)
super(parameters);
●
The Object class defines several methods
that become part of every class you write.
For example:
– public String toString()
Returns a text representation of the object,
usually so that it can be printed.
Object methods
method description
protected Object clone() creates a copy of the object
public boolean equals(Object o) returns whether two objects have
the same state
protected void finalize() used for garbage collection
public Class<?> getClass() info about the object's type
public int hashCode() a code suitable for putting this
object into a hash collection
public String toString() text representation of object
public void notify() methods related to concurrency
public void notifyAll() and locking (seen later)
public void wait()
public void wait(...)
– What does this list of methods tell you about Java's design?
Using the Object class
●
You can store any object in a variable of type Object.
Object o1 = new Point(5, -3);
Object o2 = "hello there";
●
You can write methods that accept an Object parameter.
public void checkNotNull(Object o) {
if (o != null) {
throw new IllegalArgumentException();
}
●
You can make arrays or collections of Objects.
Object[] a = new Object[5];
a[0] = "hello";
a[1] = new Random();
List<Object> list = new ArrayList<Object>();
Recall: comparing objects
●
The == operator does not work well with objects.
– It compares references, not objects' state.
– It produces true only when you compare an object to itself.
Point p1 = new Point(5, 3);
Point p2 = new Point(5, 3);
Point p3 = p2;
x 5 y 3
p1
// p1 == p2 is false; ...
// p1 == p3 is false;
// p2 == p3 is true
p2 x 5 y 3
// p1.equals(p2)? ...
// p2.equals(p3)? p3
Default equals method
●
The Object class's equals implementation is very simple:
public class Object {
...
public boolean equals(Object o) {
return this == o;
}
}
●
However:
– When we have used equals with various objects, it didn't behave like
== . Why not? if (str1.equals(str2)) { ...
– The Java API documentation for equals is elaborate. Why?
Implementing equals
public boolean equals(Object name) {
statement(s) that return a boolean value ;
}
●
Casting references is different than casting primitives.
– Really casting an Object reference into a Point reference.
– Doesn't actually change the object that is referred to.
– Tells the compiler to assume that o1 refers to a Point object.
The instanceof keyword
if (variable instanceof type) {
statement(s);
}
expression result
s instanceof Point false
• Asks if a variable refers s instanceof String true
to an object of a given type. p instanceof Point true
p instanceof String false
– Used as a boolean test.
p instanceof Object true
s instanceof Object true
String s = "hello";
null instanceof String false
Point p = new Point();
null instanceof Object false
equals method for Points
// Returns whether o refers to a Point object with
// the same (x, y) coordinates as this Point.
public boolean equals(Object o) {
if (o instanceof Point) {
// o is a Point; cast and compare it
Point other = (Point) o;
return x == other.x && y == other.y;
} else {
// o is not a Point; cannot be equal
return false;
}
}
More about equals
●
Equality is expected to be reflexive, symmetric, and transitive:
a.equals(a) is true for every object a
a.equals(b) ↔ b.equals(a)
(a.equals(b) && b.equals(c)) ↔ a.equals(c)
●
No non-null object is equal to null:
a.equals(null) is false for every object a
●
Two sets are equal if they contain the same elements:
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new TreeSet<String>();
for (String s : "hi how are you".split(" ")) {
set1.add(s); set2.add(s);
}
System.out.println(set1.equals(set2)); // true
The hashCode method
public int hashCode()
Returns an integer hash code for this object, indicating its preferred to
place it in a hash table / hash set.
– Allows us to store non-int values in a hash set/map:
●
How is hashCode implemented?
– Depends on the type of object and its state.
●
Example: a String's hashCode adds the ASCII values of its letters.
– You can write your own hashCode methods in classes you write.
●
All classes come with a default version based on memory address.
Polymorphism
●
polymorphism: Ability for the same code to be used with
different types of objects and behave differently with each.
●
A variable or parameter of type T can refer to any subclass of T.
Employee ed = new Lawyer();
Object otto = new Secretary();