A Java Crash Course

Document Sample
A Java Crash Course Powered By Docstoc

                A Java Crash Course
           Dan Wallach, Princeton University

      s    Applet “Hello, World”
            x graphics
            x widgets
      s    AWT event model
      s    Multithreaded programming
      s    Networking
      s    Utilities and tricks

12/10/97                           Wallach / A Java Crash Course   2


      Starting resources
      s    If you own only one book...
           Java in a Nutshell, David Flanagan (O’Reilly &
               (examples online!)
      s    “Whenever possible, steal code.” [Duff]

12/10/97                            Wallach / A Java Crash Course   3

      Normal Hello World

      public class Hello {
          public static void main(String args[]) {
              System.out.println(“Hello, world.”);

      s    Put in:
      s    Compile with: javac
           ·   Creates Hello.class
      s    Run with: java Hello
12/10/97                            Wallach / A Java Crash Course   4


      Applet Hello, world #1
           import java.applet.*;      // Don’t forget these import statements!
           import java.awt.*;

           public class FirstApplet extends Applet {
               // This method displays the applet.
               // The Graphics class is how you do all drawing in Java.
               public void paint(Graphics g) {
                   g.drawString("Hello, world.", 25, 50);

       s     paint() called by system when refresh is necessary
       s     Graphics class has lines, polygons, text, images,

12/10/97                                  Wallach / A Java Crash Course      5

      Hello, world #2
       import java.applet.*;
       import java.awt.*;

       public class HelloWorld2 extends Applet {
           TextArea textarea;

             // Create a text area to send our output
             public void init() {
                 textarea = new TextArea(20, 60);
                 Dimension prefsize = textarea.preferredSize();
                 this.resize(prefsize.width, prefsize.height);

      s     Make a scrolling text area where you can do terminal-
            like output

12/10/97                                  Wallach / A Java Crash Course      6


      Hello, world #2 (cont.)
               public void start() {
                   ByteArrayOutputStream os = new ByteArrayOutputStream();
                   PrintStream ps = new PrintStream(os);

                   try {
                   } catch (Throwable t) {}


               public void go(PrintStream ps) {
                   // your program goes here
                   ps.println(“Hello, world.”);

      s    text printed after program is done
      s    TextArea widget redraws itself
12/10/97                                  Wallach / A Java Crash Course               7

      Applets in HTML
           ARCHIVE=“” (Netscape 3)

       <param name=“text” value=“Dan & Drew’s Excellent Java Class”>
       <param name=“speed” value=“5”>

       <img src=“nojava.gif” alt=“Oh, you don’t have Java.                Sorry.”>


      s    codebase/archive tags are optional
      s    argument-passing through param tags
12/10/97                                  Wallach / A Java Crash Course               8


      Applet class
      s    java.applet.Applet
           x   you extend this for your applet
      s    java.awt.Panel
      s    java.awt.Container
           x   applet widget can contain other widgets
      s    java.awt.Component
           x   lots of interesting methods here
      s    java.lang.Object

12/10/97                             Wallach / A Java Crash Course   9

      Basic methods on Applet
      s    init()
           x   called once for your applet
      s    start()
           x   called every time you enter the page
      s    stop()
           x   called every time you leave the page
      s    destroy()
           x   called when your page is discarded

12/10/97                             Wallach / A Java Crash Course   10


      Funky methods on Applet
      s    AudioClip getAudioClip(URL url)
      s    Image getImage(URL url)
           x   starts asynchronous image loading
      s    void showDocument(URL url)
           x tells browser to load new document
           x optional second argument for frames
      s    void showStatus(String msg)
           x   writes to browser status line

12/10/97                              Wallach / A Java Crash Course   11

      Applet repainting
      s    paint()
           x   defaults to nothing
      s    update()
           x   clears screen, calls paint()
      s    repaint()
           x passes events to Motif/Win32
           x don’t mess with this

12/10/97                              Wallach / A Java Crash Course   12


      Applet event handling
      s    boolean handleEvent(Event evt)
           x mouse, keyboard, all widget events
           x checks event type, then calls...
      s    mouseUp() / mouseDown() / keyUp() / keyDown()
      s    action(Event evt, Object arg)
           x - specific widget
           x arg - widget-specific result (i.e., new state of a

12/10/97                            Wallach / A Java Crash Course    13

      Applet event handling
      s    Centralized event management
           x add standard buttons, widgets as children of the top-
             level applet
           x custom action() method, checks
      s    Distributed event management
           x subclass buttons, widgets
           x custom action() methods in subclasses

12/10/97                            Wallach / A Java Crash Course    14


      Java and threads
      s      One lock per object plus one per class
      s      synchronized keyword on a method
      s      Mesa-style monitors
              x wait() / notify() / notifyAll()
              x must be called within a synchronized block
      s      System classes already thread-safe
              x   HashTable, OutputStream, AWT, etc.

12/10/97                                   Wallach / A Java Crash Course                         15

      Thread-safe Message Passing
 public class SafeBuffer {                              synchronized public Object get() {
   private Object buffer;                                 while(buffer == null) {
                                                            try {
    public SafeBuffer() {}                                    wait();
                                                            } catch(InterruptedException e) {}
    synchronized public void put(Object o) {              }
      while(buffer != null) {                             Object tmp = buffer;
        try {                                             buffer = null;
        } catch (InterruptedException e) {}                 notifyAll();
      }                                                     return tmp;
      buffer = o;                                       }

             Exercise for reader: barrier sync, bounded-buffer
             queue, etc.
12/10/97                                   Wallach / A Java Crash Course                         16


      Starting Threads
 class client implements Runnable {
   private SafeBuffer b;                   ...

     public client(SafeBuffer b) {         SafeBuffer sb = new SafeBuffer();
       this.b = b;                         new Thread(new client(sb)).start();
                                           sb.put("Hello, world.");
     public void run() {
       String s;                           ...
       s = (String) b.get();

      s    Thread constructor takes any object which implements

12/10/97                              Wallach / A Java Crash Course              17

      s    Applet restrictions
           x Same IP address which loaded applet
           x UDP support is flakey
      s    Using the browser’s cache
           x constructor takes normal string argument
           x InputStream toStream()
           x only current way to get SSL support

12/10/97                              Wallach / A Java Crash Course              18


      s    client:
           x constructor takes DNS name, port
           x getInputStream() / getOutputStream()

      s    server:
           x constructor takes local port number
           x Socket accept()
                3   blocks until success -- use multithreading!

12/10/97                                Wallach / A Java Crash Course   19

      Utilities and tricks
      s    StringBuffer vs. String
           x strings are immutable
           x StringBuffer append() is cheaper
      s    java.util.Hashtable
           x   uses Object.hashCode() and Object.equals()
      s    java.util.StringTokenizer
           x   split string on whitespace / separator chars

12/10/97                                Wallach / A Java Crash Course   20


      Use Javadoc
      s    Literate programming for Java
           x document as you write code
           x generates pretty, cross-linked HTML
                * Creates an absolute URL from the specified protocol,
                * host, port and file.
                * @param protocol the protocol to use
                * @param host the host to connect to
                * @param port the port at that host to connect to
                * @param file the file on that host
                * @exception MalformedURLException If an unknown protocol is
                * found.
               public URL(String protocol, String host, int port, String file)
                    throws MalformedURLException {

12/10/97                                   Wallach / A Java Crash Course         21

      Useful tools
      s    Debugging / Development
           x   Microsoft Visual J++ / Symantec Visual Café
                 3   Debuggers integrated with IE / Netscape
           x Kaffe - free JVM with JIT (
           x Jikes - fast Java compiler from IBM
           x cc-mode for Emacs understands Java
      s    When in doubt…

12/10/97                                   Wallach / A Java Crash Course         22