The JAVA API UMBC CMSC 331 Java A
The JAVA API UMBC CMSC 331 Java
A Tour of the Java API • An API User’s Guide, in HTML, is bundled with Java • Much of the “learning curve” is in the API • Let’s look at some packages UMBC CMSC 331 Java 2
The Java API • java. applet – Applet class • java. awt – Windows, buttons, mouse, etc. • java. awt. image – image processing • java. awt. peer – GUI toolkit • java. io – System. out. print • java. lang – length method for arrays; exceptions • java. net – sockets • java. util – System. get. Property See http: //docs. oracle. com/javase/8/docs/api/ for the current APIs UMBC CMSC 331 Java 3
The package java. lang • The class Object – The root class in Java – Example methods: clone(), equals(), to. String() – Subclasses may override these methods • The class Class – Example methods: get. Name(), get. Super. Class() UMBC CMSC 331 Java 4
Observing an object’s class void print. Class. Name (Object obj) { System. out. println("The class of " + obj + " is " + obj. get. Class(). get. Name()); } UMBC CMSC 331 Java 5
Strings in Java • Strings are nt a primitive data type, but represented as objects. • Many methods defined in class java. lang: – Several constructors – Lots of methods: concat(), equals(), index. Of(), length() – strings are concatenated with + • Strings are constants (immutable) – You can concatenate two strings to produce a new, longer string, using the + operator, but you cannot add, delete, insert into, or delete from any particular string. UMBC CMSC 331 Java 6
String. Buffers in Java • Several methods defined in class java. lang: – Constructors can specify length or initial value – append(), insertf(), length(), to. String() UMBC CMSC 331 Java 7
Java. lang. system • Printstreams – System. out. err(“Error message”); • Inputstreams – System. in. read(input. Character) – System. in. read(input. Buffer, 0, max. Chars) UMBC CMSC 331 Java 8
The Cloneable Interface • A class implements the cloneable interface by overriding the Object method clone() • For example, we could add a clone() method to the FIFO class, if we wanted to be able to make copies of queues. UMBC CMSC 331 Java 9
The class java. util • Interface to host OS • Some basic functions and data structures – Bit. Set, Dictionary (the superclass of Hashtable), Stack, Vector – Random number generation UMBC CMSC 331 Java 10
System Properties • System properties are like UNIX environment variables, but platform independent • The API class java. util has methods for accessing the system properties UMBC CMSC 331 Java 11
// determine environment variables import java. util. *; class env. Snoop { public static void main ( String args[] ) { Properties p; String s; p = System. get. Properties(); p. list(System. out); s = System. get. Property("user. name"); System. out. println("user. name="+s); s = System. get. Property("user. home"); System. out. println("user. home="+s); } }
Java GUI • The awt class allows you to create – frames – buttons – menus and menubars – checkboxes – text areas – scrolling lists UMBC CMSC 331 Java 13
Java. net • Defines several useful objects: – URLs – Internet Addresses – Sockets – Datagrams • packets • sockets UMBC CMSC 331 Java 14
Manipulating URLs • A Web server can provide lots of information about a file being sent back in response to an HTTP request. • A URL can be read – into a string, using the get. Content() – or opened as a Data. Input. Stream, and read using read. Line() UMBC CMSC 331 Java 15
import java. net. *; import java. io. *; import java. util. *; public class Get. URLInfo { // Create a URL from the specified address, open a connection // to it, and then display information about the URL. public static void main(String[] args) throws Malformed. URLException, IOException { URL url = new URL(args[0]); URLConnection connection = url. open. Connection(); printinfo(connection); }
public static void printinfo(URLConnection u) throws IOException { // Display the URL address, and information about it. System. out. println(u. get. URL(). to. External. Form() + ": "); System. out. println(" Content Type: " + u. get. Content. Type()); System. out. println(" Content Length: " + u. get. Content. Length()) System. out. println(" Last Modified: " + new Date(u. get. Last. Modified())); System. out. println(" Expiration: " + u. get. Expiration()); System. out. println(" Content Encoding: " + u. get. Content. Encoding()); // Read and print out the first five lines of the URL. System. out. println("First five lines: "); Data. Input. Stream in = new Data. Input. Stream(u. get. Input. Stream()); for(int i = 0; i < 5; i++) { String line = in. read. Line(); if (line == null) break; System. out. println(" " + line); } } }
UDP Examples • UDP - Unreliable datagram packet • Examples from Flanagan – Send a UDP packet – Receive a UDP packet UMBC CMSC 331 Java 18
// // This example is from the book _Java in a Nutshell_ by David Flanagan. Written by David Flanagan. Copyright (c) 1996 O'Reilly & Associates. You may study, use, modify, and distribute this example for any purpose. This example is provided WITHOUT WARRANTY either expressed or implied. import java. io. *; import java. net. *; // This class sends the specified text as a datagram to // port 6010 of the specified host. public class UDPSend { static final int port = 6010; public static void main(String args[]) throws Exception { if (args. length != 2) { System. out. println( "Usage: java UDPSend <hostname> <message>"); System. exit(0); }
// Get the internet address of the specified host Inet. Address address = Inet. Address. get. By. Name(args[0]); // Convert the message to an array of bytes int msglen = args[1]. length(); byte[] message = new byte[msglen]; args[1]. get. Bytes(0, msglen, message, 0); // Initilize the packet with data and address Datagram. Packet packet = new Datagram. Packet(message, msglen, address, port); // Create a socket, and send the packet through it. Datagram. Socket socket = new Datagram. Socket(); socket. send(packet); } }
import java. io. *; import java. net. *; // This program waits to receive datagrams sent to port 6010. // When it receives one, it displays the sending host and port, // and prints the contents of the datagram as a string. public class UDPReceive { static final int port = 6010; public static void main(String args[]) throws Exception { byte[] buffer = new byte[1024]; String s; // Create a packet with an empty buffer to receive data Datagram. Packet packet = new Datagram. Packet(buffer, buffer. length); // Create a socket to listen on the port. Datagram. Socket socket = new Datagram. Socket(port);
for(; ; ) { // Wait to receive a datagram socket. receive(packet); // Convert the contents to a string s = new String(buffer, 0, 0, packet. get. Length()); // And display them System. out. println("UDPReceive: received from " + packet. get. Address(). get. Host. Name() + ": " + packet. get. Port() + ": " + s); } // close for } // close main } // close class UDPReceive
Using Threads • Thread objects are the basis for multi-threaded programming. • Multi-threaded programming allows a single program to conduct concurrently running threads that perform different tasks. • Defined in java. lang. Thread UMBC CMSC 331 Java 23
The Runnable Interface • A class that implements this interface can provide the “body” of a thread • The run() method needs to be specified UMBC CMSC 331 Java 24
Using a Single Thread • The simple. Thread class implements the Runnable interface – Implements run() method for Runnable interface – Implements init(), start() and stop(), extending Applet class – Can’t just extend Thread class, since Thread. stop() is final and can’t be overriden (why? ) UMBC CMSC 331 Java 25
// Simple Thread Example, based on "Neon Sign" public class One. Thread extends java. applet. Applet implements Runnable { Thread kicker; public void init() { kicker = null; } public void start() { if(kicker == null) { // If no thread is started yet kicker=new Thread(this); // then create one kicker. start(); // and start it } } public void stop() { kicker. stop(); kicker = null; }
public void run() { long sleep. Time; System. out. println("Hello!"); sleep. Time = 5000; while(true) { // Loop forever // The sleep method below might be interrupted // and cause an exception, so catch it. try { // Wait for some period of time Thread. sleep( sleep. Time ); sleep. Time = (sleep. Time == 3000 ? 4000 : 3000 ); } catch (Exception e){ return; } System. out. println("Hello again after "+sleep. Time+ " milliseconds"); } } }
Neon Sign Example • Start a thread • Load two GIF images • Repeat forever – Display first image – Sleep a random period of time – Display the other image UMBC CMSC 331 Java 28
// Blinking Neon Light by Mattias Flodin import java. awt. *; public class Blink. Item extends java. applet. Applet implements Runnable { Image im. Pic[]; // Array that holds the two images int i. Pic. Index=0; // Keeps track of which image is displayed Thread kicker; public void init() { // *Always* resize, in case the HTML author forgot to // include WIDTH and HEIGHT tags resize(512, 243); } public void Paint(Graphics g) { update(g); } // Using the update method will get rid of some flickering public void update(Graphics g) { // Display an error message if something // unexpected has happened to the images if(im. Pic[i. Pic. Index]==null) g. draw. String("Error when loading picture", 0, 172); // Draw the current image g. draw. Image(im. Pic[i. Pic. Index], 0, 0, this); }
public void start() { if(kicker == null) { // If no thread is started yet kicker=new Thread(this); // then create one kicker. start(); // and start it } } public void stop() { kicker=null; } public void run() { im. Pic=new Image[2]; // Dimension the image array // Load the two images in our 'animation' im. Pic[0]=get. Image(get. Code. Base(), "images/Homepage 1. gif"); im. Pic[1]=get. Image(get. Code. Base(), "images/Homepage 2. gif"); for(; ; ) { // Loop forever repaint(); // Redraw the window i. Pic. Index==0 ? 1 : 0; // Switch image // The sleep method below might be interrupted // and cause an Interrupted. Exception, so we'll // have to catch it. try { // Wait for a random amount of time Thread. sleep( (int) (Math. random()*500)); } catch (Interrupted. Exception e){} }
Multiple Threads • An applet that creates a pool of simple threads • Each thread has an ID number, and may handle different tasks • Note separation of applet and thread classes UMBC CMSC 331 Java 31
Multiple Threaded Example public class Thread. Example extends java. applet. Applet { public void init() { simple. Thread[] thread. Pool = new simple. Thread[2]; thread. Pool[0] = new simple. Thread(1); thread. Pool[1] = new simple. Thread(2); } } UMBC CMSC 331 Java 32
public class simple. Thread implements Runnable { Thread this. Thread; int this. Thread. ID; public simple. Thread (int i) { this. Thread. ID = i; this. start(); } public void start() { if(this. Thread == null) { // If thread isn’t started this. Thread = new Thread(this); // create one this. Thread. start(); // and start it } } public void stop() { this. Thread. stop(); this. Thread = null; }
public void run() { long sleep. Time; System. out. println("Hello from simple. Thread "+ this. Thread. ID); while(true) { // The sleep method below might be interrupted // and cause an exception, so catch it. try { // Wait for a random amount of time sleep. Time = (long) ( Math. random()*4 ); Thread. sleep( sleep. Time*1000 ); } catch (Exception e) { return; } System. out. println("Hello again from simple. Thread "+ this. Thread. ID+" after "+sleep. Time+" seconds"); } } }
Other Ideas • Patterns as an addition to the String. Buffer class (ala Perl) • One could easily write a better browser – intelligent pre-fetching of URLs – other ideas? UMBC CMSC 331 Java 35
Where to get more information • There are now many decent Java books • Many other web resources UMBC CMSC 331 Java 36
- Slides: 36