0% found this document useful (0 votes)
8 views28 pages

coreAPI 2x2

The document provides an overview of the java.lang package, which includes fundamental classes and utilities essential for Java programming, such as Object, String, and System. It also discusses the java.io package for input/output operations and the concept of wrapper classes for primitive types. Additionally, it covers exception handling, assertions, and cloning objects in Java.

Uploaded by

Athrav Chougule
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views28 pages

coreAPI 2x2

The document provides an overview of the java.lang package, which includes fundamental classes and utilities essential for Java programming, such as Object, String, and System. It also discusses the java.io package for input/output operations and the concept of wrapper classes for primitive types. Additionally, it covers exception handling, assertions, and cloning objects in Java.

Uploaded by

Athrav Chougule
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Advanced Programming with Java The java.

lang package

The java.lang package contains classes, interfaces,


The JavaTM programming platform contains a and exceptions that are fundamental to the Java
set of class libraries. These standard libraries programming language
provide functionality that ranges from file
compression to graphics. Here we will discuss
some of Java’s fundamental classes, useful • Object, Class, System
utility classes, and tools for performing I/O.

• String, StringBuilder
The Standard Libraries

• java.lang • The “wrapper” classes

• java.io • A bunch of exceptions

• java.util

Copyright ©2000-2023 by David M. Whitlock. Permission to make digital or hard


copies of part or all of this work for personal or classroom use is granted without
fee provided that copies are not made or distributed for profit or commercial
advantage and that copies bear this notice and full citation on the first page. To
copy otherwise, to republish, to post on servers, or to redistribute to lists, requires
prior specific permission and/or fee. Request permission to publish from
[email protected]. Last updated January 5, 2023.

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

• charAt: Returns the char at a given offset into a


• equals: Compares an Object to another String

• toString: Returns a String representation of an • compareTo: Compares a String to another


Object (often invoked automagically)

• hashCode: Returns a hash code for an Object • endsWith/startsWith: Determines if one String is
a suffix/prefix of another

• clone: Returns a copy of an Object


• indexOf: Finds an occurrence of a char in a String

• getClass: Returns an instance of an Object’s


“metaclass” • length: Returns the length of a String

• 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);

• delete/deleteCharAt: Removes some number of Is really:


chars from a StringBuilder
double temp;
StringBuilder sb = new StringBuilder();
• insert: Inserts something into a StringBuilder sb.append("Today’s temp is ");
sb.append(temp);
• length: Returns the length of a StringBuilder System.out.println(sb.toString());

So, remember that string concatenation creates a


• subString: Returns a portion of a StringBuilder StringBuilder
as a String

• There is some overhead, so don’t do it inside a tight


• toString: Returns the contents of a StringBuilder loop
as a String
• Sometimes it is better to use a StringBuilder
* StringBuilderprovides a better-performing alternative to the older
StringBuffer class
directly instead of concatentation

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.

• equals: Compares this Boolean to another

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

• forDigit: Returns the char value for a number • doubleValue

• isDigit: Determines if a char is a digit • floatValue

• isLetter: Determines if a char is a letter


• intValue

• isWhitespace: Determines if a char is whitespace


• longValue

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

Static methods: java.lang.Throwable is the base class for all exceptions

• getMessage: Returns a String message describing


• parseInt: Converts a String to an int Throwable object

• 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

• toHexString • JDK 1.4 added a getCause method that returns a


Throwable that caused the other Throwable
(chained exceptions) and a getStackTrace method
• toOctalString that returns a representation of the location at which
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

• MIN VALUE: The smallest int


• java.lang.Errors are truly not expected (e.g.
running out of virtual memory), could happen at any
time, and should not be caught

13 14

Big Bucket o’ java.lang Exceptions Checked versus Unchecked Exceptions

Exceptions java.lang.RuntimeExceptions are often thrown by the


ArithmeticException e.g. divide by zero Java Virtual Machine’s runtime system
ArrayIndexOutOfBoundsException
ClassCastException Trying to cast an object • Called “unchecked” exceptions because they do not
need to be declared in a throws clause, nor do they
to a type that it is not have to be caught
IllegalArgumentException
NegativeArraySizeException • Examples include ClassCastExecption and
NullPointerException Referencing an object NullPointerException
that is null
NumberFormatException Thrown when parsing • Often easy to test for: “Look before you leap”
numbers Other subclasses of java.lang.Exception must be
explicitly thrown and caught
Errors
OutOfMemoryError Garbage collected heap • These are “checked” exceptions
is full
StackOverflowError Too much recursion • Examples include java.io.IOException,
java.sql.SQLException, and
java.awt.AWTException

• Your exceptions should subclass Exception

• Checked exceptions make your code more explicit


and easier to understand

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

• The type of the exception determines which catch • assert Expression1


block will be executed
• assert Expression1 : Expression2
try {
openFile();
If Expression1 evaluates to false, then a
} catch (FileNotFoundException ex) { java.lang.AssertionError is thrown
// prompt user for new file name
• Expression2 is the detail message issued with the
} catch (IOException ex) { AssertionError
// Print out error message and exit
} Assertions are used to verify that certain program facts
Note that the catch statements have to be arranged are true
according to the exception class hierarchy
• For instance, after reading all of the bytes from a
try { buffer, assert that the buffer is empty
openFile();
Assertions incur some runtime expense, so they must be
} catch (IOException ex) { explicitly enabled
} catch (FileNotFoundException ex) {
// Unreachable code. Won’t compile. • Assertions are enabled via the -ea switch to java
}
• Code executed by the assertion must have no side
effects (e.g. changing the state of an object)
17 18

Using Assertions vs. Throwing Exceptions Assertions and Program Logic

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;
// ...
}

Using asserts will make your code better!

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;

But obviously, public Object clone() {


Grades grades2 = (Grades) super.clone();
x.clone() != x grades2.grades = this.grades.clone();
return grades2;
By default, the JVM doesn’t know how to make a copy of }
an object }

• By default, the clone method throws a Some notes:


CloneNotSupportedException
• Invoking super.clone() creates a new object
If a class implements the Cloneable interface, invoking
the clone method will automagically return a shallow
copy of the receiving object • Arrays are cloneable (because they are Objects)

• 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

Covariant Returns Covariant Returns

In J2SE 1.5 methods may have covariant returns If you were to decompile the class files you would see

• In Human’s class file the declared return type of clone


• An overriding method may modify the return type of a is still Object
method to be a subclass of the overridden method’s
return type – Binary compatibility with older code

• However, a call to Human.clone() is typed as


From edu/pdx/cs410J/j2se15/CovariantReturns.java returning a Human

static abstract class Animal implements Cloneable {


public abstract Object clone(); Have to be careful with using covariant returns with
} third-party code

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.

• External APIs are for users (interfaces and abstract


classes) • File class that represents a file
package com.college;
• Classes for byte-based I/O (Streams)
public interface Classroom { ... }

public interface University {


public Classroom[] getClassrooms(); • Classes for text-based I/O (Readers/Writers)
}

• Internal APIs contain implementation (classes)


package com.college.internal;

public class ClassroomImpl implements Classroom { ... }

public class UniveristyImpl implements University {


public ClassroomImpl[] getClassrooms() { ... }
}

If the internal classes return internal types, the


implementation code doesn’t have to cast

25 26

java.io.File Other File goodies

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.

• mkdir: Creates the directory that a File represents


• list(FilenameFilter) returns the names of all files
• getParentFile: Returns the directory containing this that are accepted by a FilenameFilter
File as a File
• listFiles(FileFilter) returns all of the Files that
are accepted by a FileFilter

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

Example using Files and filters Why is the FileFilter interesting?

$ cd ~whitlock/public_html/src Instance of DirectoryFilter and JavaFilenameFilter


$ java -cp ~/classes edu.---.FindJavaFiles . do not have any state (fields)
./edu/pdx/cs410J/AbstractAirline.java
./edu/pdx/cs410J/AbstractFlight.java
• An object encapsulates behavior
./edu/pdx/cs410J/AirportNames.java
./edu/pdx/cs410J/ParserException.java
./edu/pdx/cs410J/lang/Animal.java The responsibility of filtering files is partitioned between
./edu/pdx/cs410J/lang/Ant.java the File API and your code:
./edu/pdx/cs410J/lang/Bee.java
./edu/pdx/cs410J/lang/Bird.java
• File knows how to apply the filter, but doesn’t know
./edu/pdx/cs410J/lang/Cow.java
the criteria under which to filter
./edu/pdx/cs410J/lang/DivTwo.java
...
./edu/pdx/cs410J/family/TextDumper.java • You know what you want to filter, but File takes care
./edu/pdx/cs410J/family/Parser.java of doing the grunt work
./edu/pdx/cs410J/family/TextParser.java
./edu/pdx/cs410J/family/AddPerson.java
File delegates some of its work to the filter’s accept
./edu/pdx/cs410J/family/NoteMarriage.java
method

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

• close: Closes the stream and releases any


PipedOutputStream FilterOutputStream FileOutputStream resources associated with it

ByteArrayOutputStream ObjectOutputStream
• flush: Sends all pending output to the stream

DataOutputStream PrintStream BufferedOutputStream


Some OutputStreams

InputStream
• ByteArrayOutputStream: Writes to a byte array

ByteArrayInputStream FilterInputStream StringBufferInputStream

• PipedOutputStream: Used with a


ObjectInputStream FileInputStream PipedInputStream SequenceInputStream
PipedInputStream to send data between threads

DataInputStream LineNumberInputStream PushBackInputStream BufferedInputStream


• ObjectOutputStream: Writes Objects to a stream

33 34

java.io.FileOutputStream An example using OutputStreams

A FileOutputStream write bytes to a file package edu.pdx.cs410J.core;


import java.io.*;
Constructed from a File or a file’s name, may throw a
FileNotFoundException public class WriteDoubles {
static PrintStream err = System.err;

java.io.FilterOutputStream public static void main(String[] args) {


FileOutputStream fos = null;
try {
A FilterOutputStream is built around another fos = new FileOutputStream(args[0]);
OutputStream and performs some processing on its } catch(FileNotFoundException ex) {
bytes err.println("** No such file: " + args[0]);
System.exit(1);
• BufferedOutputStream: Buffers the data to be }
written DataOutputStream dos = new DataOutputStream(fos);
for(int i = 1; i < args.length; i++) {
• DataOutputStream: Writes Java’s primitive types in a try {
machine-independent format double d = Double.parseDouble(args[i]);
dos.writeDouble(d);
} catch(NumberFormatException ex) {
• PrintStream: Writes data in a human-readable err.println("** Not a double: " + args[i]);
format, doesn’t throw exceptions } catch(IOException ex) {
– System.out and System.err are PrintStreams err.println("** " + ex);
System.exit(1);
– Has print and println methods for all types }
}
– The hasError method determines if an error has }
occurred }
35 36
An example using OutputStreams java.io.InputStream

$ 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

• close: Closes the stream


Behavior Delegation
• read: Reads bytes into a byte array. Returns the
write(double) number of bytes read, -1 if done.
DataOutputStream
• skip: Skips over some number of bytes in the
write(byte[])
stream
FileOutputStream
Some InputStreams:
writeToFile(byte[])

File • ByteArrayInputStream: InputStream behavior over


a byte array
Object Composition (the “object onion”) • PipedInputStream: Used with a
PipedOutputStream to send data between threads
DataOutputStream
• SequenceInputStream: Read from multiple
FileOutputStream
InputStreams in a given order
File

37 38

java.io.FileInputStream An example using InputStreams

FileInputStream is used for reading bytes from a file package edu.pdx.cs410J.core;


import java.io.*;
public class ReadDoubles {
Constructed from a File or a file’s name, may throw a static PrintStream out = System.out;
FileNotFoundException static PrintStream err = System.err;
public static void main(String args[]) {
FileInputStream fis = null;
java.io.FilterInputStream try {
fis = new FileInputStream(args[0]);
A FilterInputStream is built around another } catch(FileNotFoundException ex) {
InputStream and processes the bytes that are read err.println("** No such file: " + args[0]);
}
DataInputStream dis = new DataInputStream(fis);
• BufferedInputStream: Buffer the input read from while (true) {
another InputStream try {
double d = dis.readDouble();
out.print(d + " ");
out.flush();
• DataInputStream: Used to read Java’s primitive
} catch(EOFException ex) {
types
break; // All done reading
} catch(IOException ex) {
err.println("** " + ex);
• PushbackInputStream: Allows you to push bytes System.exit(1);
back into the stream }
}
out.println("");
}
}
39 40
An example using InputStreams Handling text I/O: Writers and Readers

$ 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:

There’s no nice way of telling when a DataInputStream Writer


is done – have to catch an EOFException – yuch!

Note the use of print and flush PrintWriter StringWriter PipedWriter FilterWriter

BufferedWriter OutputStreamWriter CharArrayWriter

FileWriter

Reader

StringReader PipedReader FilterReader

BufferedReader InputStreamReader CharArrayReader

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

• flush: Sends all pending text to the destination


java.io.StringWriter

Some Writers StringWriter is a Writer that writes to a String

• BufferedWriter: Buffers text before writing it to the


destination • getBuffer: Returns the StringBuilder written to

• CharArrayWriter: Writes text to a char array


• toString: Returns the String being written to
• FilterWriter: Abstract class for writing filtered text
streams
java.io.FileWriter
• PipedWriter: Used with a PipedReader to send text
between threads A FileWriter writes text to a file

• 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

package edu.pdx.cs410J.core; $ java -cp ~/classes edu.---.WriteToFile \


import java.io.*; text.out This is some text
$ cat text.out
public class WriteToFile { This
private static PrintWriter err; is
some
public static void main(String[] args) { text
// Wrap a PrintWriter around System.err
err = new PrintWriter(System.err, true);
Note how we “wrapped” a PrintWriter around a
try { PrintStream
Writer writer = new FileWriter(args[0]);
This abstraction helps simplify programming by hiding
// Write command line arguments to the file what’s really going on
for(int i = 1; i < args.length; i++) {
writer.write(args[i]);
You don’t know what you’re writing to and, more
writer.write(’\n’);
importantly, you don’t care!
}

// All done
writer.flush();
writer.close();

} catch(IOException ex) {
err.println("** " + ex);
}
}
}
45 46

java.io.Reader Example using Readers

Reader is an abstract class for reading character data package edu.pdx.cs410J.core;


from a source import java.io.*;

• read: Reads chars public class ReadFromConsole {


public static void main(String[] args) {
• ready: Determines if a Reader has more text to read InputStreamReader isr =
new InputStreamReader(System.in);
• close: Closes a Reader BufferedReader br = new BufferedReader(isr);
StringWriter text = new StringWriter();
• skip: Skips some number of characters
while (true) {
Some Readers
try {
• CharArrayReader: Reads from a char array // Read a line from the console
String line = br.readLine();
• FilteredReader: Abstract class for reading filtered
character streams if (line.equals("-1")) {
break;
• PipedReader: Used with a PipedWriter to send text } else {
between threads text.write(line + " ");
}
• StringReader: Reads from a String } catch(IOException ex) {
System.err.println("** " + ex);
• InputStreamReader: Reads from an InputStream System.exit(1);
}
• BufferedReader: Buffers the text it reads }
– Has a readLine method System.out.println(text);
}
}
47 48
Example using Readers Closing Streams

$ java -cp ~/classes edu.---.ReadFromConsole To free up system resources, streams (and


Does readers/writers) should be closed by invoking their close
this method, often in a finally block
program
work? • It’s easy to forget to call close
-1
Does this program work? • And close may throw an IOException
public void printTextFile(File file)
throws IOException {

BufferedReader br =
new BufferedReader(new FileReader(file));
try {
while (br.ready()) {
System.out.println(br.readLine());
}

} catch (IOException ex) {


System.err.println(ex);
throw ex;

} finally {
if (br != null) {
br.close();
}
}
}
49 50

Automatically Closing Streams The utility classes

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

public void printTextFile(File file)


throws IOException { • Date, Calendar, Locale

try (BufferedReader br =
new BufferedReader(new FileReader(file))) { • System properties
while (br.ready()) {
System.out.println(br.readLine());
}

} catch (IOException ex) {


System.err.println(ex);
}
}

Now you don’t need to remember to close the reader

51 52
java.util.StringTokenizer StringTokenizer example

A StringTokenizer is used to parse a String* package edu.pdx.cs410J.core;

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);
}
}
}

$ java -cp ~/classes edu.---.ParseString \


This,is,a:sentence. ,:
Token: This
Token: is
* JDK 1.4 added a regular expression package to Java Token: a
(java.util.regex) that provides Perl-like regex Token: sentence.
53 54

The Original Collection Classes Collection Classes

The first Java release contained several classes for First of all, a hierarchy of interfaces in java.util
collecting objects together:

Collection Iterator Map


• Vector: A growable, ordered collection of objects

• Stack: A Vector with push/pop List Set ListIterator SortedMap

• Hashtable: Maps objects to objects SortedSet

java.util.Collection groups objects together


While these classes were very useful, they tended to be
bulky and slow. • add: Adds an Object to a Collection
• contains: Determines if a Collection contains an
Object
• isEmpty: Determines if a Collection is empty
• iterator: Returns an Iterator over a Collection
• remove: Removes an Object from a Collection
• size: Returns the number of elements in a
Collection

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

java.util.Map Abstract collection classes

A Map maps key objects to value objects Set AbstractCollection Collection

• 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

• get: Returns the value Object associated with a LinkedList Stack


given key Object

To ease the implementation of collection classes, several


• containsKey: Determines if an Object is a key in the abstract base classes are provided:
mapping
• java.util.AbstractCollection
• containsValue: Determines if an Object is a value
in the mapping • java.util.AbstractList: Backed by a random
access data structure (e.g. array)

• keySet: Returns the keys in a Map as a Set • java.util.AbstractSequentialList: Backed by a


sequential access data structure (e.g. linked list)
• values: Returns the values in a Map as a Collection
• java.util.AbstractMap

• entrySet: Returns the mappings in a Map as a Set • java.util.AbstractSet

59 60
Concrete implementations of collections Example using collections

In the java.util package: Lists package edu.pdx.cs410J.core;


import java.util.*; // Must be imported!
• ArrayList: List backed by an array
public class Collections {
• LinkedList: List back by a linked list, provides
stack-like behavior /** Prints the contents of a Collection */
private static void print(Collection c) {
• Vector: Implements the List interface Iterator iter = c.iterator();
while (iter.hasNext()) {
Object o = iter.next();
Maps
System.out.println(o);
}
• HashMap: Constant-time get and put }
• TreeMap: Sorted keys gives log(n) get and put public static void main(String[] args) {
Collection c = new ArrayList();
• IdentityHashMap: Key comparison based on identity c.add("One");
(==) instead of equals method c.add("Two");
c.add("Three");
• LinkedHashMap: Keeps track of insertion order of print(c);
mappings System.out.println("");
Sets Set set = new HashSet(c);
set.add("Four");
• HashSet: Set backed by a hash table set.add("Two");
print(set);
• TreeSet: SortedSet backed by a red-black tree }
}
61 62

Working with our example Storing primitives in collection

$ 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.*;

public class WrapperObjects {


Note order of ArrayList and that a HashSet contains public static void main(String[] args) {
unique values Collection c = new ArrayList();
c.add(new Integer(4));
Abstraction is key: “Program to the interface” c.add(new Double(5.3));
c.add(new Boolean(false));

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”

package edu.pdx.cs410J.j2se15; • List<Long> longs = new ArrayList<Long>();


import java.util.*;
• Attempting to a non-Long to longs will caused a
public class Autoboxing { compilation error:
public static void main(String[] args) {
// Note that Integer.valueOf returns an Integer – longs.add("This will not compile")
int i = Integer.valueOf("123");

List list = new ArrayList();


list.add(i);
int j = (Integer) list.get(0);
}
}

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:

Otherwise, you could do this: List<Map<String, String>> data =


new ArrayList<Map<String, String>>();
List<String> ls = new ArrayList<String>();
List<Object> lo = ls; Java 7 introduced the generics “diamond” that infers the
lo.add(new Integer(42)); // Bad! generic types on the left side of the assignment:

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

public class ModifyWhileIterating { • To safely modify an underlying collection, use


public static void main(String[] args) { Iterator’s remove method
List<String> list = new ArrayList<String>();
list.add("one"); list.add("two"); Fail-fast iterators have the benefit of immediately
detecting when they are out-of-date
Iterator<String> iter = list.iterator();
while (iter.hasNext()) { • Iterator fails quickly instead of allowing potential
String s = iter.next(); non-deterministic (or simply incorrect) behavior
if (s.equals("one")) {
list.add(0, "start"); However, you should not rely on a
} ConcurrentModificationException always being
} thrown:
}
} • Replacing an item in a List (using put) may not
cause the iterator to fail
$ java -cp ~/classes edu.---.ModifyWhileIterating
Exception in thread "main" • Fail-fast behavior should only be used to detect bugs
java.util.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

$ java -cp ~/classes edu.---.Farm Objects that implement the java.lang.Comparable


Clyde -> Clyde says Baa interface are said to have a natural ordering
Bossie -> Bossie says Moo
Old MacDonald -> Old MacDonald says Hello • Instances of String, Integer, Double, etc. are all
Louise -> Louise says Quack Comparable

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

An example of Natural Ordering An example of Natural Ordering

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));

public class Cereal implements Comparable<Cereal> { for (Cereal c : set) {


private String name; System.out.println(c);
private double price; }
}
// <snip> }

public int compareTo(Cereal c2) { Running the example...


return this.getName().compareTo(c2.getName());
} $ java -cp ~/PSU/src/classes edu.---.Cereal
Raisin Bran $2.65
public boolean equals(Object o) { Sugar Crisps $2.38
if (o instanceof Cereal) { Total $3.56
Cereal other = (Cereal) o;
return this.getName().equals(other.getName());
} Natural ordering allows the author of the class to specify
return false; how instances of that class are compared
}

public int hashCode() {


return this.getName().hashCode();
}
75 76
Custom Sorted Collections An example Comparator

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();

if (price1 > price2) {


• A Comparator may or may not choose to respect the return 1;
equals method of the objects that it is comparing } else if (price1 < price2) {
return -1;
} else {
• Comparator has a generic type that specifies the return 0;
type of object that is compared }
}

Comparators can be used to create TreeSets and // Continued..


TreeMaps

77 78

An example Comparator Helpful collection functions

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?

* This class cannot be instantiated.


79 80
Helpful collection functions Type-safe enumerations

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)

* Based on Item 21 from Joshua Bloch’s Effective Java book


81 82

An example of a type-safe enumeration Type-safe enumerations

package edu.pdx.cs410J.j2se15; public static void main(String[] args) {


import java.util.*; SortedSet<Day> set = new TreeSet<Day>();
set.add(Day.WEDNESDAY);
public class EnumeratedTypes { set.add(Day.MONDAY);
private enum Day { SUNDAY, MONDAY, TUESDAY, set.add(Day.FRIDAY);
WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
System.out.print("Sorted days: ");
private static String enEspanol(Day day) { for (Day day : set) {
switch (day) { System.out.print(day + " ");
case SUNDAY: }
return "Domingo";
case MONDAY: System.out.print("\nEn espanol: ");
return "Lunes"; for (Day day : set) {
case TUESDAY: System.out.print(enEspanol(day) + " ");
return "Martes"; }
case WEDNESDAY: System.out.println("");
return "Miercoles"; }
case THURSDAY:
return "Jueves"; $ java -cp ~/classes edu.---.EnumeratedTypes
case FRIDAY: Sorted days: MONDAY WEDNESDAY FRIDAY
return "Viernes"; En espanol: Lunes Miercoles Viernes
case SATURDAY:
return "Sabado";
default:
String s = "Unknown day: " + day;
throw new IllegalArgumentException(s);
}
}
83 84
Type-safe enumerations implementation Type-safe enumeration with added behavior

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

Type-safe enumeration with added behavior java.util.Properties

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)

• store: Stores properties in a format suitable for use


with load

Properties implements the Map interface

• Note that put will not complain if you add a


non-String property

87 88
The JVM system properties Example using system properties

The JVM maintains a Properties object that contains package edu.pdx.cs410J.core;


various JVM settings known as system properties
import java.util.*;
System properties may be set with the -D option to java
public class SystemProperties {
/**
Accessing the JVM’s system properties: * Print out the system properties and check
* to see if the "edu.pdx.cs410J.Debug"
• System.getProperties: Returns the system’s * property has been set on the command line.
Properties instance */
public static void main(String[] args) {
• System.getProperty: Returns the value of a given // Print out some properties
named system property Properties props = System.getProperties();
props.list(System.out);
Wrapper classes have static “get” methods that decode
system properties as a given primitive type // Is the "edu.pdx.cs410J.Debug" property set?
String name = "edu.pdx.cs410J.Debug";
• Integer.getInteger, Boolean.getBoolean boolean debug = Boolean.getBoolean(name);
System.out.print("\nAre we debugging? ");
System.out.println((debug ? "Yes." : "No."));
}
}

89 90

Example using system properties java.util.Date

$ 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=

os.name=SunOS A Date instantiated with the zero-argument constructor


java.class.version=49.0 represents the current date/time.
os.version=5.9
user.home=/u/whitlock Support for internationalization and multiple day/time
edu.pdx.cs410J.Debug=true <-- formats complicates Java’s day/time facility.
java.specification.version=1.5
user.name=whitlock
• java.util.Calendar
java.class.path=/u/whitlock/jars/examples.jar
java.home=/pkgs/jdk1.5/jre
user.language=en • java.text.DateFormat
file.separator=/
See edu.pdx.cs410J.core.AroundTheWorld
Are we debugging? Yes.

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

Working with our Date and Calendar java.text.DateFormat


example
The DateFormat class is used to format Dates into
Strings (format) and convert Strings into Dates
$ java -cp ~/classes edu.---.Today
(parse).
Today is Thu Jul 28 15:31:11 PDT 2005
It’s been 1122589871595ms since the epoch.
It is the 5th day of the week • DateFormat.SHORT: 6/17/94 9:37 PM
and the 209th day of the year.
We are in the 5th week of the month. • DateFormat.MEDIUM: Jun 17, 1994 9:37:45 PM

• DateFormat.LONG: June 17, 1994 9:37:45 PM PDT


The fact that the representation of a date (Date) is
separate from how it is accessed (via a Calendar) makes • DateFormat.FULL: Friday, June 17, 1994 9:37:45 PM
Java’s time facility more modular. PDT

Different Calendars can treat time differently Like Calendar, you use static methods to get an
instance of DateFormat

• Gregorian calendar • getTimeInstance: Returns a DateFormat for


formatting/parsing a time (9:37 PM)

• Hebrew calendar • getDateInstance: Returns a DateFormat for


formatting/parsing a date (6/17/94)

• Chinese calendar • getDateTimeInstance: Returns a DateFormat for


formatting/parsing both a date and time (6/17/94 9:37
PM)

• setLenient: Sets how strict parsing should be


95 96
Working with DateFormat Working with DateFormat

package edu.pdx.cs410J.core; f = DateFormat.SHORT;


df = DateFormat.getDateTimeInstance(f, f);
import java.text.*; System.out.println("SHORT: " + df.format(date));
import java.util.*;
f = DateFormat.MEDIUM;
public class FormattedDate { df = DateFormat.getDateTimeInstance(f, f);
public static void main(String[] args) { System.out.println("MEDIUM: " + df.format(date));
// Glue args together into one String
StringBuilder sb = new StringBuilder(); f = DateFormat.LONG;
for(int i = 0; i < args.length; i++) { df = DateFormat.getDateTimeInstance(f, f);
sb.append(args[i] + " "); System.out.println("LONG: " + df.format(date));
}
f = DateFormat.FULL;
Date date = null; df = DateFormat.getDateTimeInstance(f, f);
int f = DateFormat.MEDIUM; System.out.println("FULL: " + df.format(date));
}
DateFormat df = }
DateFormat.getDateTimeInstance(f, f);

try { $ java -cp ~/classes edu.---.FormattedDate \


date = df.parse(sb.toString().trim()); Jun 17, 1994 9:37:45 PM
SHORT: 6/17/94 9:37 PM
} catch(ParseException ex) { MEDIUM: Jun 17, 1994 9:37:45 PM
System.err.println("** Bad date: " + sb); LONG: June 17, 1994 9:37:45 PM PDT
System.exit(1); FULL: Friday, June 17, 1994 9:37:45 PM PDT
}

// Continued...
97 98

A more flexible format: SimpleDateFormat Using SimpleDateFormat

java.text.SimpleDateFormat lets you specify a String package edu.pdx.cs410J.core;


that specifies the format of the date to parse/format
import java.text.*;
import java.util.*;
Symbol Meaning Presentation
G era Text public class SimpleDate {
y year Number public static void main(String[] args) {
M month in year Text & Number DateFormat df = new SimpleDateFormat(args[0]);
d day in month Number Date now = new Date();
h hour in am/pm (1-12) Number System.out.println(df.format(now));
H hour in day (0-23) Number }
}
m minute in hour Number
s second in minute Number
S millisecond Number Alphabetical characters must be escaped:
E day in week Text
D day in year Number $ java edu.---.SimpleDate "E M d, y G ’at’ h:mm a z"
F day of week in month Number Sun 4 29, 01 AD at 3:59 PM PDT
w week in year Number
W week in month Number The more times a symbol occurs in the format string, the
a am/pm marker Text more verbose the format:
k hour in day (1-24) Number
K hour in am/pm (0-11) Number $ java edu.---.SimpleDate \
z time zone Text "EEEE MMM d, yyyy G ’at’ h:mm a zzzz"
Sunday Apr 29, 2001 AD at 3:59 PM Pacific Daylight Ti
’ escape for text Delimiter
’’ single quote Literal
99 100
Many kinds of DateFormats Variable-length argument lists

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

• The argument to Arrays.asList has variable


arguments

List l = Arrays.asList("One", "Two", "Three");

101 102

Variable-length argument lists J2SE 1.5 text formatting

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

public static void main(String[] args) {


• Formatter supports formatting the primitive types
printSum("1+2+3 = ", 1, 2, 3);
(int, etc.), Strings, Calendars, etc.
printSum("1+2+3+4+5 = ", 1, 2, 3, 4, 5);
printSum("2+4+6+8 = ", 2, 4, 6, 8);
} • A new method String.format() offers the
} functionality of sprintf (formatting to a String)

• The format is a superset of what is offered in C, but


attempts to convert incompatible types (a Calendar
to an int) will result in an exception being thrown

103 104
Format string syntax Format string syntax

The general form of the format string is: This table summarizes the various conversion characters

b “boolean” true or false


%[argument$][flags][width][.precision]conversion h “hashcode (arg.hashCode() in hexadecimal)
s “string” toString is invoked
• The argument is the index of the argument in the c “character”
varargs list d “decimal integer”
o “octal”
• flags are characters that modify the output format x “hexadecimal”
e “floating point” (in scientific notation)
• width is the minimum number of characters that f “floating point”
should be written for the argument g “floating point” (scientific for large exponents)
a “floating point” (significant and exponent)
• precision usually restricts the number of characters t “time” (data and time)
that should be written (dates and times do not have a % literal percent
precision) n “newline” (platform-specific line separator)

• conversion is a character that indicates how the


argument should be formatted

105 106

Formatting times Formatting dates

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):

B “full month” (e.g. January)


H “Hour of day” (00 - 23)
b “short month” (e.g. Jan)
I “12-hour hour” (01 - 12)
A “full day of week” (e.g. Sunday)
k “24-hour hour” (0 - 23)
a “short day of week” (e.g. Sun)
l “12-hour hour” (1 - 12)
Y “four-digit year”
M “minute” (00 - 59)
y “two-digit year”
S “second” (00 - 60)
j “day of year”
L “millisecond” (000 - 999)
m “two-digit month”
N “nanosecond” (000000000 - 999999999)
d “two-digit day of month”
p am/pm
e “day of month” (one or two digits)
T AM/PM
z RFC 822 time zone offset (e.g. -0800)
The following flags can be applied to format strings:
Z String time zone (PDT)
s Seconds since epoch
- “left justified”
E Milliseconds since epoch
^ “upper case”
# “alternate form”
+ numerics will always have a sign
positive numerics have leading space
0 numerics are zero-padded
, numerics have grouping separators
( negative numerics are enclosed in parentheses
107 108
An example of using formatting Summary

package edu.pdx.cs410J.j2se15; Java’s standard class libraries provide a vast array of


functionality
import java.io.PrintStream;
import java.util.Calendar;
• Basic language features: String, StringBuilder,
public class Formatting { Class, “wrapper” classes, Math
public static void main(String[] args) {
PrintStream out = System.out;
out.printf("%s%n", "Hello World"); • Facilities for performing byte-based or
character-based I/O: File, OutputStream,
Calendar today = Calendar.getInstance(); PrintStream, FileWriter, BufferedReader
out.printf("Today’s date is: %tm/%td/%tY%n",
today, today, today);
out.printf("The current time is: %tl:%tM %tp%n", • Handy utilities: Date, Calendar, BitSet,
today, today, today); StringTokenizer
out.printf("%f/%.2f = %f%n", 2.0, 3.0, (2.0/3.0));

for (int i = 0; i < 3; i++) { • Collection classes: Vector, List, Iterator,


out.printf("%5s%5s%5s%n", i, i+1, i+2); HashMap, Comparator
}

out.printf("%-10s%s%n", "left", "right");


}
}

109 110

You might also like