Download Programming Language Technologies and Paradigm - Basic Java | CMSC 433 and more Study notes Programming Languages in PDF only on Docsity!
CMSC 433,Michael Hicks, U. Maryland
CMSC433, Fall 2002
Programming Language
Technology and Paradigms
Basic Java
Michael Hicks
Sep 12, 2002
CMCS 433, Fall 2002 - Michael Hicks 59
Exceptions
• On an error condition, we throw an
exception
• At some point up the call chain, the
exception is caught and the error is handled
• Separates normal from error-handling code
• A form of non-local control-flow
– Like goto, but structured
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 60
Throwing an Exception
• Create a new object of the class Exception, and
throw it
if (i > 0 && i < a.length ) {
return (a[I])
else throw new ArrayIndexOutOfBounds();
• Exceptions thrown are part of return type
– when overriding a method in a superclass
– can’t throw anything that would surprise a superclass
object
CMCS 433, Fall 2002 - Michael Hicks 61
Method throws declarations
• A method declares the exceptions it might throw
– public void openNext() throws
UnknownHostException,
EmptyStackException
• Must declare any exception the method might
throw
– unless it is caught in the method
– includes exceptions thrown by called methods
– certain built-in exceptions excluded
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 64
Example Application
public class BufferedReader {
public String readLine () throws IOException { … } …
public class Echo {
public static void main(String args[]) {
BufferedReader in = …
try {
while((s = in.readLine()) != null)
System.out.println(s);
} catch(IOException e) {
System.out.println(e.stackTrace());
CMCS 433, Fall 2002 - Michael Hicks 65
Creating New Exceptions
• User-defined exception is just a class that is
a subclass of Exception
class MyOwnException extends Exception {}
class MyClass {
void oops() throws MyOwnException {
if (some_error_occurred) {
throw new MyOwnException();
CMSC 433,Michael Hicks, U. Maryland
Java Libraries
CMCS 433, Fall 2002 - Michael Hicks 67
You should familiarize yourself
• Packages
– java.lang
– java.util
– java.net
– java.io
• Read the documentation on line
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 70
I/O Classes
• OutputStream – byte stream going out
• Writer – character stream going out
• InputStream – byte stream coming in
• Reader – character stream coming in
CMCS 433, Fall 2002 - Michael Hicks 71
OutputStream - bytes
• Example classes
– ByteArrayOutputStream – goes to byte []
– FileOutputStream – goes to file
• Wrappers – wrapped around OutputStream
– BufferedOutputStream
– ObjectOutputStream – serialization of object
graph
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 72
Writer - characters
• OutputStreamWriter
– wraps around OutputStream to get a Writer
– takes characters, converts to bytes
– can specify encoding used to convert
• Other wrappers
– PrintWriter – supports print, println
– BufferedWriter
• Other Writers
– CharArrayWriter
– StringWriter
CMCS 433, Fall 2002 - Michael Hicks 73
InputStream - bytes
• Example classes
– ByteArrayInputStream
– FileInputStream
• Wrappers – wrapped around InputStream
– BufferedInputStream
– PushedBackInputStream
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 76
Input (JDK 1.1 and higher)
• Wrap System.in in an InputStreamReader
– converts from bytes to characters
• Wrap the result in a BufferedReader
– makes input operations efficient
– supports readline() interface
• readline() returns a string
– returns null if at EOF
CMCS 433, Fall 2002 - Michael Hicks 77
Example Echo Application
import java.io.*;
public class Echo {
public static void main(String [] args) {
String s;
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
int i = 1;
try {
while((s = in.readLine()) != null)
System.out.println((i++) + “: “ + s); }
catch(IOException e) {
System.out.println(e); }
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 78
Java Networking
• class Socket
– Client-side connections to servers
• class ServerSocket
– Server-side “listen” socket
– Awaits and responds to connection requests
CMCS 433, Fall 2002 - Michael Hicks 79
Example Client/Server
ServerSocket s = new ServerSocket(5001);
Socket conn = s.accept();
InputStream in = conn.getInputStream();
OutputStream out = conn.getOutputStream();
Socket conn = new Socket (5001);
InputStream in = conn.getInputStream();
OutputStream out = conn.getOutputStream();
Client code
Server code
server client
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 82
Example Client/Server
ServerSocket s = new ServerSocket(5001);
Socket conn = s.accept();
InputStream in = conn.getInputStream();
OutputStream out = conn.getOutputStream();
Socket conn = new Socket (5001);
InputStream in = conn.getInputStream();
OutputStream out = conn.getOutputStream();
Client code
Server code
server client
Note: The server is still
listening other
connection requests
CMCS 433, Fall 2002 - Michael Hicks 83
Example Client/Server
ServerSocket s = new ServerSocket(5001);
Socket conn = s.accept();
InputStream in = conn.getInputStream();
OutputStream out = conn.getOutputStream();
Socket conn = new Socket (5001);
InputStream in = conn.getInputStream();
OutputStream out = conn.getOutputStream();
Client code
Server code
server client
in
out
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 84
Example Client/Server
ServerSocket s = new ServerSocket(5001);
Socket conn = s.accept();
InputStream in = conn.getInputStream();
OutputStream out = conn.getOutputStream();
Socket conn = new Socket (5001);
InputStream in = conn.getInputStream();
OutputStream out = conn.getOutputStream();
Client code
Server code
server client
in
out
in
out
CMCS 433, Fall 2002 - Michael Hicks 85
Possible Failures
• Server-side
– ServerSocket port already in use
– Client dies on accept
• Client-side
– Server dead
– No one listening on port
• In all cases IOException thrown
– Must use appropriate throw/try/catch constructs
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 88
Other libraries
• java.lang.Math
– abstract final class – only static members
– includes constants e and π
– includes static methods for trig, exponentiation,
min, max, …
• java.text
– text formatting tools
• class MessageFormat provides printf/scanf
functionality
– lots of facilities for internationalization
CMCS 433, Fall 2002 - Michael Hicks 89
Java Container Classes
• A unified architecture for representing and
manipulating collections of objects
• Container classes contain three things:
– Interfaces: abstract data types representing collections
of objects
– Implementations: concrete implementations of the
collection interfaces
– Algorithms: methods that perform computations on
objects that implement collection interfaces
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 90
Container class hierarchy
CMCS 433, Fall 2002 - Michael Hicks 91
Collection Classes
• Collections contain groups of objects (elements)
• Collection interface is not implemented in Java.
Subinterfaces implemented
– Set: unordered, can’t contain duplicate elements
- Hashset – unordered, no duplicates
- TreeSet - ordered, no duplicates
– List: ordered, can contain duplicate elements
- LinkedList – unordered, dynamic size, add/delete quick
- ArrayList – unordered, dynamic size, random access
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 94
compareTo Interface
• public int compareTo(Object o)
• The natural comparison method (i.e., default)
- Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than o
- sgn(x.compareTo(y)) == -sgn(y.compareTo(x))
- implies that x.compareTo(y) must throw an exception iff
y.compareTo(x) throws an exception.
- (x.compareTo(y)>0 && y.compareTo(z)>0) => x.compareTo(z)>0.
- x.compareTo(y)==0 => sgn(x.compareTo(z)) == sgn(y.compareTo(z))
- Recommended that (x.compareTo(y)==0) == (x.equals(y))
CMCS 433, Fall 2002 - Michael Hicks 95
Comparator Interface
• When natural order isn’t acceptable
• public int compare(Object o1, Object o2)
- Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second
- sgn(compare(x, y)) == -sgn(compare(y, x))
- (This implies that compare(x,y) must throw an exception if and only
if compare(y, x) throws an exception.)
- ((compare(x, y)>0) && (compare(y, z)>0)) => compare(x, z)>0.
- compare(x, y)==0 => sgn(compare(x,z))==sgn(compare(y, z))
- recommended (compare(x, y)==0) == (x.equals(y))
• public boolean equals(Object obj)
- Indicates whether some other object is "equal to" this Comparator.
CMSC 433,Michael Hicks, U. Maryland
CMCS 433, Fall 2002 - Michael Hicks 96
Example
import java.util.; import java.awt.; class MyPoint extends java.awt.Point implements Comparable { MyPoint(int x, int y) {super(x,y);} public int compareTo(Object o) { MyPoint p = (MyPoint)o; double d1 = Math.sqrt(xx + yy); double d2 = Math.sqrt(p.xp.x + p.yp.y); if (d1 < d2) {return -1;} else if (d2 < d1) {return 1;} return 0; } }
class Sort3 { public static void main(String[] args) { Random rnd = new Random(); MyPoint[] points = new MyPoint[10]; for (int i=0; i<points.length; i++) { points[i] = new MyPoint (rnd.nextInt(100),rnd.nextInt(100)); System.out.println(points[i]); } System.out.println("-----------"); Arrays.sort(points); //Print the points for (int i=0; i<points.length; i++){ System.out.println(points[i]); } } }
CMCS 433, Fall 2002 - Michael Hicks 97
Example
import java.util.*;
import java.awt.*;
class MyPoint extends
java.awt.Point implements
Comparable {
MyPoint(int x, int y) {
super(x, y);
public int
compareTo(Object o) {
MyPoint p = (MyPoint)o;
return x - p.x;
class Sort2 { public static void main(String[] args) { Random rnd = new Random(); MyPoint[] points = new MyPoint[10]; for (int i=0; i<points.length; i++) { points[i] = new MyPoint (rnd.nextInt(100), rnd.nextInt(100)); System.out.println(points[i]); } System.out.println("-----------"); Arrays.sort(points); //Print the points for (int i=0; i<points.length; i++){ System.out.println(points[i]); } } }