coreAPI 2x2
coreAPI 2x2
lang package
• String, StringBuilder
The Standard Libraries
• java.util
1 2
java.lang.Object java.lang.String
Object is the root class in Java: Everything is an Object Strings can be constructed from byte arrays, char
arrays, or other Strings
Therefore, all objects have the following methods
• hashCode: Returns a hash code for an Object • endsWith/startsWith: Determines if one String is
a suffix/prefix of another
• finalize: Called when an Object is garbage • replace: Replaces all occurrences of one char with
collected (not a destructor!) another
• notify, notifyAll, and wait are used in • trim: Removes leading and trailing whitespace from
multi-threaded programs a String
3 4
java.lang.StringBuilder The secret life of StringBuilder
Strings are immutable, StringBuilders* can be The + operator is overloaded to concatenate Strings
changed
In reality, javac compiles string concatenation into
operations on a StringBuilder:
• append: Appends something to a StringBuilder
– The StringBuilder itself is returned double temp;
– sb.append("Result: ").append(4); System.out.println("Today’s temp is " + temp);
5 6
java.lang.System java.lang.Math
Contains a number of system-level fields and methods Math provides static methods for performing
mathematical calculations on doubles
Static fields:
• abs, sqrt
• out: A PrintStream for standard output (as in
System.out.println("Hi"))
• Trigonometric functions (cos, tan, asin, et. al.)
• err: A PrintStream for standard error
• ceil, floor
• in: An InputStream for standard in
• exp, pow
Static methods:
• min, max
• currentTimeMillis: Returns the current time in
milliseconds since January 1, 1970
• toDegrees, toRadians
• exit: Shuts down the JVM with a given int exit code
• random: Returns a random double between 0.0 and
1.0
• setOut, setErr, setIn: Reassigns the various
“standard” streams
7 8
The “wrapper” classes java.lang.Boolean
Some things, such as they keys of a hash table, can only Class methods
be Objects.
What if you wanted to key a hash table on an int value? • valueOf: Parses a String and returns its boolean
value (case insensitive)
Java provides “wrapper” classes for all of the primitive
types: Boolean, Byte, Character, Double, Float, Instance methods
Integer, Long, Short, Void
Each wrapper class has a method that returns the value • booleanValue: Returns the boolean value for a
of the primitive class represents: intValue, charValue, Boolean
etc.
9 10
java.lang.Character java.lang.Number
Java supports the 16-bit Unicode standard for The numeric wrapper classes are subclasses of Number
international character sets
Instance methods for converting between numeric types
A number of useful static methods
• digit: Returns the numeric (int) value of a char • byteValue: Returns a Number’s value as a byte
Instance methods
• shortValue
• charValue: Returns the char value of a Character
All of Number’s subclass have similar behavior
• compareTo: Compares one Character to another
11 12
java.lang.Integer The Wide World of Exceptions
• toBinaryString Returns the binary representation • printStackTrace: Prints a stack trace describing
of an int as a String where in the code the Throwable was thrown
Static fields:
Throwable has two subclasses
• MAX VALUE: The largest int • java.lang.Exceptions are the kinds of things a
reasonable program may want to catch
13 14
15 16
Catching Multiple Kinds of Exceptions Assertions
A try block can have multiple catch blocks JDK 1.4 added an assertion facility to the Java language
Assertions should be used to verify the internal logic of a Assertions are most useful to verify program logic
method
private String getDayString(int day) {
An exception (such as IllegalArgumentException) switch (day) {
should be used to verify the inputs to a (public) method case MONDAY:
return "Monday";
• Remember, it is reasonable for a program to catch an case TUESDAY:
Exception, but it shouldn’t catch an Error return "Tuesday";
// ...
Using assertions: default:
assert false : "Unknown day: " + day;
public void setPort(int port) { }
if (port <= 1024) { }
throw new IllegalArgumentException();
}
} if (i % 3 == 0) {
// ...
private int readPort() { } else if (i % 3 == 1) {
int port = ...; // Read from config file // ...
assert port > 1024 : port; } else {
} assert i % 3 == 2;
// ...
}
19 20
Cloning Objects Cloning Objects
Object’s clone method returns a copy of an object In order to get a deep copy, clone should be overridden:
The copy usually has the same state and commonly
public class Grades implements Cloneable {
x.clone().equals(x) private double[] grades;
• JVM allocates a new instance of the class of the • Even though the overriden clone doesn’t declare that
receiver – no constructor is invoked it throws CloneNotSupportedException, it still has
to be caught
• Fields of the clone have the same values as the
receiver object – Superclass (Object) may throw it – can’t change
the contract
• Contents of the fields are not cloned (clone will refer
to the same objects as the original)
21 22
In J2SE 1.5 methods may have covariant returns If you were to decompile the class files you would see
static class Human extends Animal { • If someone else subclassed the JDK 1.4 Human
public Human clone() {
return new Human(); class Professor extends Human {
} public Object clone() {
} return new Professor();
}
static class Student extends Human { }
public Student clone() {
return new Student(); The code wouldn’t compile because Object is not a
} subclass of Human
}
23 24
Covariant returns of internal classes The java.io package
Very often, applications have “external” APIs and The classes and interfaces in the java.io package
“internal” APIs provide a myriad of facilities for performing I/O operations.
25 26
File represents a file and can be created from a String File has four important static fields
specifying its location or a File representing the directory
that a named file resides in.
• separator/separatorChar: The string/character that
separates portions of a file spec (/ on UNIX)
• canWrite: Determines whether or not a File can be
written to
• pathSeparator/pathSeparatorChar: The
• delete: Deletes a File string/character that separates directories in a path
(: on UNIX)
• exists: Determines if a File exists
• getName: Returns the name of a File The java.io package contains two interfaces,
FileFilter and FilenameFilter, which have an accept
method that accepts/rejects a File based on some
• isDirectory: Determine if a File represents a criteria (e.g. its name).
directory
The filters are used as arguments to File’s list and
• length: Returns the size of a File listFiles methods.
27 28
Example using Files and filters Example using Files and filters
package edu.pdx.cs410J.core;
package edu.pdx.cs410J.core; import java.io.*;
import java.io.*; // Must be imported
public class FindJavaFiles {
public class DirectoryFilter implements FileFilter { private static FileFilter dirFilter;
public boolean accept(File file) { private static FilenameFilter javaFilter;
if (file.isDirectory()) {
return true; private static void findJavaFiles(File dir) {
} else { File[] javaFiles = dir.listFiles(javaFilter);
return false; for (int i = 0; i < javaFiles.length; i++)
} System.out.println(javaFiles[i].toString());
} File[] dirs = dir.listFiles(dirFilter);
} for(int i = 0; i < dirs.length; i++)
findJavaFiles(dirs[i]);
}
package edu.pdx.cs410J.core;
public static void main(String[] args) {
import java.io.*;
File file = new File(args[0]);
if (file.isDirectory()) {
public class JavaFilenameFilter
dirFilter = new DirectoryFilter();
implements FilenameFilter {
javaFilter = new JavaFilenameFilter();
public boolean accept(File dir, String fileName) {
findJavaFiles(file);
if (fileName.endsWith(".java")) {
} else {
return true;
System.err.println(file +
} else {
" is not a directory");
return false;
}
}
}
}
}
}
29 30
31 32
Streams: I/O in bytes java.io.OutputStream
The java.io package in JDK 1.0 contained two An OutputStream is an abstract class that writes bytes
hierarchies of classes for performing byte-based stream and has the following methods:
I/O
OutputStream
• write: Writes bytes to the stream
ByteArrayOutputStream ObjectOutputStream
• flush: Sends all pending output to the stream
InputStream
• ByteArrayOutputStream: Writes to a byte array
33 34
$ java -cp ~/classes edu.---.WriteDoubles \ InputStreams read bytes and have the following
doubles.out 1.23 2.34 3.45 methods:
If you were to cat doubles.out you would see garbage • available: Returns the number of bytes that can be
because double.out is a binary file. read without blocking
37 38
$ java -cp ~/classes edu.---.ReadDoubles \ Streams worked well for byte data, but working with text
doubles.out data was awkward. JDK 1.1 introduced writers and
1.23 2.34 3.45 readers:
Note the use of print and flush PrintWriter StringWriter PipedWriter FilterWriter
FileWriter
Reader
FileReader
41 42
java.io.Writer java.io.PrintWriter
Writer is an abstract class and writes characters to A PrintWriter prints formatted text to another Writer or
some destination. It has methods such as an OutputStream
• write: Writes characters or strings Like a PrintStream in that it has print and println
methods, but flushing is not automatic
• close: Closes a Writer
• OutputStreamWriter: Converts chars to bytes and The file is specified by a File object or the file’s name
sends them to an OutputStream
43 44
Example using Writers Example using Writers
// All done
writer.flush();
writer.close();
} catch(IOException ex) {
err.println("** " + ex);
}
}
}
45 46
BufferedReader br =
new BufferedReader(new FileReader(file));
try {
while (br.ready()) {
System.out.println(br.readLine());
}
} finally {
if (br != null) {
br.close();
}
}
}
49 50
In Java 7, a new “try with resources” language feature The java.util package contains a number of useful and
was added: A try statement can declare instances of handy classes
java.lang.AutoCloseable that are automatically closed
when the try block is exited
• StringTokenizer, Vector, Hashtable, Stack
• The java.io.Closeable interface that is
implemented by most I/O classes subclasses
AutoCloseable • The collection classes
try (BufferedReader br =
new BufferedReader(new FileReader(file))) { • System properties
while (br.ready()) {
System.out.println(br.readLine());
}
51 52
java.util.StringTokenizer StringTokenizer example
import java.util.*;
The constructor takes the String to be parsed and a
String whose characters delimit tokens (by default public class ParseString {
whitespace delimits tokens) /**
* The second <code>String</code> from the
• countTokens: Returns the number of tokens * command line contains the parsing delimiters.
remaining */
public static void main(String[] args) {
• nextToken: Returns the next token in the String String string = args[0];
String delimit = args[1];
StringTokenizer st;
• hasMoreTokens: Are there more tokens to be st = new StringTokenizer(string, delimit);
returned?
while (st.hasMoreTokens()) {
String token = st.nextToken();
System.out.println("Token: " + token);
}
}
}
The first Java release contained several classes for First of all, a hierarchy of interfaces in java.util
collecting objects together:
55 56
java.util.List java.util.Iterator
The elements of a List are 0-indexed An Iterator is used to iterate over the Objects in a
collection
• add: Adds an Object at a given index
• hasNext: Determines if there are any more elements
to be iterated over
• get: Returns the Object at a given index
• next: Returns the next element to be examined
• set: Sets the Object at a given index
• remove: Removes the element returned by next from
• listIterator Returns a ListIterator over a List the underlying collection (not always implemented)
java.util.Set java.util.ListIterator
Sets are unordered and each element in a Set is unique ListIterators can iterate in both directions
The equals method is used to determine the equality of
• add: Inserts an Object into the underlying list
two Objects
• hasPrevious: Determines whether or not there is a
java.util.SortedSet previous element in the list
A Set whose elements are ordered • previous: Returns the previous element in the
underlying list
Has methods like first and last
• nextIndex/previousIndex: Returns the index of the
element that would be returned by next/previous
57 58
• put: Creates a mapping from one Object to another AbstractSet SortedSet AbstractList List
in a Map
– Invokes the key’s hashCode method
HashSet TreeSet AbstractSequentialList ArrayList Vector
59 60
Concrete implementations of collections Example using collections
$ java -cp ~/classes edu.---.Collections Collections take Objects, but ints, doubles,booleans,
One etc. are not Objects
Two
Three Use the wrapper classes to create Objects that
represent the primitives:
One
Three
Four package edu.pdx.cs410J.core;
Two import java.util.*;
System.out.println(c);
}
}
63 64
Autoboxing of primitive types Strongly typing collections
J2SE 1.5 provides automatic conversion of primitives to Originally, collections could only contain Objects
wrapper objects in a procedure called “autoboxing”
“Generic types” introduced in Java 5 allow you to specify
the type of objects that a collection may contain
• Autoboxing is applied to variable and field
assignments, the arguments to method calls, and
casting • List<String> is pronounced “a list of strings”
65 66
Generics add some complexity to the type Generics added some complexity to the
system language
Even though a String is an Object, an Being forced to include all of the generic types in a
ArrayList<String> is not a List<Object> variable declaration made for hard-to-read code:
Because the compiler cannot determine that lo may List<Map<String, String>> data = new ArrayList<>();
actually only contain Strings, the language disallows the
assignment.
67 68
Iterating over collections Iterating over collections
What happens when a collection is modified while it is Most Iterators are fail-fast
being iterated over?
• If the underlying collection is modified (e.g. it size
package edu.pdx.cs410J.core; changes), then subsequent calls to next will result in
import java.util.*; a ConcurrentModificationException
69 70
Iterators and the enhanced for loop Example working with Maps
The enhanced for loop syntax can be used with package edu.pdx.cs410J.core;
Collections* as well as arrays
import edu.pdx.cs410J.lang.*;
Collection coll = ... import java.util.*;
for (Object o : coll) {
System.out.println(o); public class Farm {
} /** Prints the contents of a Map. */
private static void print(Map<String, Animal> map)
for (String key : map.keySet()) {
See edu.pdx.cs410J.j2se15.EnhancedForLoop Animal value = map.get(key);
String s = key + " -> " + value;
This syntax is compact, but you cannot reference the System.out.println(s);
Iterator object }
}
• Can’t remove an element from the Collection while public static void main(String[] args) {
you’re iterating over it Map<String, Animal> farm = new HashMap<>();
farm.put("Old MacDonald",
new Human("Old MacDonald"));
farm.put("Bossie", new Cow("Bossie"));
farm.put("Clyde", new Sheep("Clyde"));
farm.put("Louise", new Duck("Louise"));
print(farm);
} }
* Actually, any object that implements the java.lang.Iterable inter-
face
71 72
Working with our Map example Comparing Objects
Note that the order in which the elements were added to • Comparable’s compareTo method compares the
the HashMap has nothing to do with the order in which the receiver (x) object to another object (y)
Iterator visits them
– if x < y, a negative int should be returned
Note also: – if x == y, zero should be returned*
– if x > y, a positive int should be returned
• Maps use the key object’s hashCode method to
determine the bucket in which to search
• Comparable has a generic type that specifies the
class of object it can compare itself to
• Each element in the bucket’s collision chain is
compared to the key object using its equals method – Often you compare an object to another object of
its same type
So, if instances of your own classes are to be used as
keys in a Map Unless instructed otherwise, classes and methods that
sort objects (such as SortedSets) will respect their
• You should override equals and hashCode natural ordering
• Note that two objects that are equal must have the
same hash code * Should have the same semantics as the equals method
73 74
Instances of Cereal are naturally sorted alphabetically by public static void main(String[] args) {
their name SortedSet<Cereal> set = new TreeSet<Cereal>();
set.add(new Cereal("Total", 3.56));
package edu.pdx.cs410J.core; set.add(new Cereal("Raisin Bran", 2.65));
import java.util.*; set.add(new Cereal("Sugar Crisps", 2.38));
The java.util.Comparator interface is used to sort Compares boxes of Cereal based on their price
objects by criteria other than their natural ordering
package edu.pdx.cs410J.core;
• A Comparator specifies a total ordering over a set of import java.util.*;
objects
public class CerealComparator
implements Comparator<Cereal> {
• A Comparator’s compare method compares two public int compare(Cereal o1, Cereal o2) {
objects and returns an int with the same meaning double price1 = o1.getPrice();
as Comparable’s compareTo method double price2 = o2.getPrice();
77 78
public static void main(String[] args) { The java.util.Collections class* contains helpful
Set<Cereal> set = static methods for working with collections
new TreeSet<Cereal>(new CerealComparator());
set.add(new Cereal("Cap’n Crunch", 2.59)); • max(Collection) returns the largest element in a
set.add(new Cereal("Trix", 3.29)); collection (uses natural ordering)
set.add(new Cereal("Count Chocula", 2.59));
set.add(new Cereal("Froot Loops", 2.45));
• nCopies(int, Object) returns a List contains n
// Print out the cereals copies of a given object
for (Cereal c : set) {
System.out.println(c); • singleton(Object) returns an immutable Set that
} contains only the given object
}
} • sort(List, Comparator) sorts a list using the given
comparator
$ java -cp ~/classes edu.---.CerealComparator
Froot Loops $2.45 • unmodifiableMap(Map) returns a Map that cannot be
Cap’n Crunch $2.59 modified that has the same contents as the input Map
Trix $3.29
– Attempts to modify the Map throw an
UnsupportedOperationException
Why wasn’t Count Chocula printed out?
The java.util.Arrays class contains static methods J2SE 1.5 provides an enum facility* that is like a class, but
for working with arrays has a set of pre-defined instances (“constants”)
• asList(Object[]) returns a List that is backed by • The enum is similar to a class in that it has its own
a given array namespace (can be referenced via an import
– Changes to the list will “write through” to the static)
backing array
• Unlike static final fields, the values of references
• binarySearch(int[], int) returns the array index are not compiled into the class
at which the given int occurs
– Can change enum values without having to
recompile all of your code
• equals(int[], int[]) returns whether or not two
arrays have the same contents
• Have useful toString, equals, and hashCode
methods (can be used with Collections)
• fill(int[], int) populates each element of an
array with the given value
• enums can implement interfaces, are Serializable
• sort(int[]) sorts an array in-place and Comparable, and can be used in a switch
statement
Each of these methods is overloaded to operate on the
different kinds of arrays (double[], Object[], etc.) • Compile-time type safety (constants are no longer
just ints)
enums are compiled into Java inner classes You can also attach additional behavior to enumerated
types:
• All enums extend the java.lang.Enum class that
provides methods like equals, hashCode, and package edu.pdx.cs410J.j2se15;
ordinal
public class NumericOperators {
• The only non-final method of Enum is toString – private abstract enum Operation {
the rest is taken care of for you PLUS {
double eval(double x, double y) {
The compiler adds two interesting static methods to the return x + y;
enum class: }
char getSymbol() { return ’+’; }
};
• values returns an array of each enumeration
instance MINUS {
double eval(double x, double y) {
for (Coin coin : Coin.values()) { return x - y;
System.out.println(coin); }
} char getSymbol() { return ’-’; }
};
• valueOf return the enumerated instance with the
given name // Method declarations follow enumerations
abstract double eval(double x, double y);
Coin dime = Coin.valueOf("DIME"); abstract char getSymbol();
}
85 86
public static void main(String[] args) { Properties instances map Strings to Strings and are
Operation[] ops = { Operation.PLUS, usually used to store configuration information about the
Operation.MINUS, Operation.TIMES, JVM or an application.
Operation.DIVIDE };
for (Operation op : ops) {
System.out.println("5 " + op.getSymbol() + • setProperty: Set a named property to a given value
" 2 = " + op.eval(5, 2));
}
• getProperty: Returns the value of a property with a
}
given name
}
$ java -cp ~/classes edu.---.NumericOperators • list: Prints the contents of the Properties to a
5 + 2 = 7.0 PrintStream
5 - 2 = 3.0
5 * 2 = 10.0
5 / 2 = 2.5 • load: Loads properties from some source (e.g. a file)
87 88
The JVM system properties Example using system properties
89 90
$ java -Dedu.pdx.cs410J.Debug=true -cp ~/classes \ The Date class represents a date and a time as the
edu.pdx.cs410J.core.SystemProperties number of milliseconds since midnight on January 1,
-- listing properties -- 1970.
java.vm.version=1.5.0-b64
java.vm.vendor=Sun Microsystems Inc.
• after Determines if a Date occurs after another
path.separator=:
java.vm.name=Java HotSpot(TM) Client VM
user.dir=/u/whitlock/public_html/src • before
java.runtime.version=1.5.0-b64
os.arch=sparc
• getTime Returns the aforementioned number of
java.io.tmpdir=/var/tmp/
milliseconds
line.separator=
91 92
java.util.Calendar An example using Date and Calendar
A Calendar is used to get information (e.g. the day of the package edu.pdx.cs410J.core;
week) about a Date.
import java.util.*;
Calendar has a number of static int fields
public class Today {
public static void main(String[] args) {
• Info about days: DAY OF MONTH, DAY OF YEAR, YEAR Date today = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(today);
• Info about time: HOUR, MINUTE, SECOND
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);
Calendar instance methods: int weekOfMonth =
cal.get(Calendar.WEEK_OF_MONTH);
• setTime: Sets the Date for a Calendar
StringBuilder sb = new StringBuilder();
sb.append("Today is " + today + "\n");
• add: Adds to one of a date’s fields (e.g. MONTH) sb.append("It’s been " + today.getTime() +
"ms since the epoch.");
sb.append("\nIt is the " + dayOfWeek +
• get: Returns the value of a date’s field "th day of the week \nand the " +
dayOfYear + "th day of the year. ");
sb.append("\nWe are in the " + weekOfMonth +
All of Calendar’s constructors are protected. How do we "th week of the month.");
get a Calendar to work with?
System.out.println(sb.toString());
Calendar’s static getInstance method returns a }
Calendar instance. }
93 94
Different Calendars can treat time differently Like Calendar, you use static methods to get an
instance of DateFormat
// Continued...
97 98
Again we’ve seen how the presentation of a date J2SE 1.5 introduced language syntax for specifying a
(DateFormat) is separated from the date itself (Date). variable number of arguments (“varargs”) to a method
(think printf in C)
This mechanism allows us to display dates in a variety of
ways. • Prior to this feature, methods had to be overloaded to
take one, two, three, etc. arguments, or you had to
The java.util.Locale class represents a certain pass in an array
language/country combination.
• Now there is a special keyword ... that indicates
There is a DateFormat for each Locale that parses and that there are multiple arguments
formats dates according to the local convention.
• The vararg is treated like an array in the method body
For instance, in the FRANCE locale, a date is printed as:
– Varargs have a length and are zero-indexed
samedi 30 septembre 2000 17 h 01 GMT-07:00
• A method can only have one variable-length
argument list
– Only the last argument to a method can have
variable length
101 102
An example of a variable-length argument list: One of the deficiencies of Java’s text formatting
capabilities was that you had to invoke print (or
package edu.pdx.cs410J.j2se15; StringBuilder.append) multiple times, or you had to
create an Object array to pass to a
public class VarArgs { java.text.MesageFormat’s format method
private static void printSum(String header, Variable-length argument lists allow the Java API to
int... ints) { provide C-style printf and scanf behavior
int sum = 0;
for (int i : ints) {
• A printf method has been added to
sum += i;
java.io.PrintStream
}
System.out.print(header);
System.out.println(sum); • Most of the formatting work is done by the
} java.util.Formatter class
103 104
Format string syntax Format string syntax
The general form of the format string is: This table summarizes the various conversion characters
105 106
The t conversion character can be followed by one of the The t conversion character can be followed by one of the
following (like POSIX strftime): following (like POSIX strftime):
109 110