Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Notes on A Crash Course in Java | CMSC 433, Study notes of Programming Languages

Material Type: Notes; Professor: Pugh; Class: PROG LANG TECH & PDGMS; Subject: Computer Science; University: University of Maryland; Term: Spring 2001;

Typology: Study notes

Pre 2010

Uploaded on 07/30/2009

koofers-user-xqt
koofers-user-xqt 🇺🇸

10 documents

1 / 105

Toggle sidebar

Related documents


Partial preview of the text

Download Notes on A Crash Course in Java | CMSC 433 and more Study notes Programming Languages in PDF only on Docsity! Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] http://www.cs.umd.edu/~pugh/java/crashCourse What Makes Java Different Day 1, Session 1 What makes Java Dif ferent • Java is specified 2 • KISS principle applied • Semantics are architecture insensitive • Safe/Secure • A modern programming language • Fewer bugs? • Libraries Galore! • Speed • The Hype 1 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Java is specified • Pascal/C/C++ isn’t • 1000*1000 • (-5)/10 • int a[10]; for(int i=0;i<=10;i++) a[i] = 0; • delete p; q = new foo(); x = p->key; p->key = 0; • *(int *)(random()) = 0 3 • The Java specification (is intended) to completely specify the behavior of all programs • Not just “correct” programs • Caveat - multi-threading, random numbers, ... • specified but has multiple valid implementations • All run-time errors must be caught • Can make promises about what might happen KISS principle applied • Many useful features were removed from C++ • Makes language easier to learn and implement • operator overloading • user-definable coercions • templates • multiple inheritance • multiple supertypes still allowed • structs/unions • unsigned integers • stand-alone functions 4 • Not essential 2 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Privileges bestowed to signed code • You can set policies about which signatures give what privileges 9 • In Active-X, all or nothing • In Java • version 1.1 - applet sandbox or full power • version 1.2 - finer control A modern programming language • Includes many features that PL researchers have been advocating for years (but never caught on in mass-market) • strong type system • multi-threading and synchronization • garbage collection • exceptions • class Class • class Object 10 • Not an embarrassment to academic CS • Adapts ideas from: C++, Smalltalk, Lisp, Modula-3, Objective-C 5 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Fewer bugs? • Many bugs are memory management bugs 11 • Pointers also cause problems • No guarantee that shipping Java programs won’t hit Exceptions/Errors • But the bugs won’t propagate far Libraries Galore! • Java has a huge collection of libraries • Utilities (collection classes, Zip files, Internationalization) • Graphics/Media (2D/3D, Sound, Video) • Graphical User Interfaces • Networking (sockets, URL’s, RMI, CORBA) • Threads • Databases • Cryptography/Security 12 • Increasing in each version (1.0 → 1.1 → 1.2) • No other programming environments • with libraries this complete • cross-platform • Huge improvement in programmer productivity 6 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] 13 Speed • Initial JVM’s are slow, but situation has improved • JVM’s that do Just-in-time compilation • Native code compilers • need to allow for dynamically loaded code • Byte code optimizers, shrinkers and obsfucators • Sun’s Hotspot JVM • How bad is it really? How bad is it really? • Prime number sieve - primes less than 100,000 • Sun Solaris JDK 1.1.6 70 seconds • Sun Solaris JDK 1.2beta3/JIT 27 seconds • Sun Solaris gcc -O4 21 seconds 14 • Developers use a different coding style for Java • Lots of little methods/objects, run-time type dependent stuff • This is a good thing; better programmer productivity? • But makes it hard to generate efficient code 7 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Mostly C/C++ syntax: statements • Empty statement, expression statement 19 • blocks { ... } • if, switch, while, do-while, for • break, continue, return • any statement can be labeled • break and continue can specify a label • continue must specify a loop label • throw and try-catch-finally • synchronized • No goto Mostly C/C++ syntax: expressions • Standard math operators: +, -, *, /, % 20 • Bit operations: &, |, ^, ~, <<,>>, >>> • Update operators: =, +=, -=, *=, /=, %=, ... • Relational operations: <, <=, ==,>=,>, != • Boolean operations: &&, ||, ! • Conditional expressions: b ? e1 : e2 • Select methods/variables/class/subpackage: . • Class operators: new, instanceof, (Class) • No pointer operations: *, &, -> 10 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Hello World example public class HelloWorldApplication { public static void main(String [] args) { if (args.length == 1) System.out.println("Hello " + args[0]); else System.out.println("Hello World"); } } 21 Naming conventions • Classes/Interfaces start with a capital letter 22 • packages/methods/variables start with a lowercase letter • ForMultipleWords, capitalizeTheFirstLetterOfEachWord • Underscores_discouraged • CONSTANTS are in all uppercase 11 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Values • Object reference: null or a reference to an object 23 • boolean (Not a number or pointer/reference) • char (UNICODE; 16 bits, almost a unsigned int) • byte (8 bits signed) • short (16 bits signed) • int (32 bits signed) • long (64 bits signed) • float (32 bits IEEE 754) • double (64 bits IEEE 754) • Objects and References Objects and References • All objects are allocated on the heap 24 • No object can contain another object • All class variables/fields are references to an object • A reference is almost like a C/C++ pointer, except • Can only point to start of heap allocated object • No pointer arithmetic • Use . rather than -> to access fields/methods • String Example 12 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Arrays • Are a special kind of object (with lots of syntactic sugar) 29 • Can declare arrays of any type • Arrays have one instance variable: length • they also have contents indexed with a subscript of 0 ... length-1 • Can be initialized using {val0, val1, ..., valn} notation • Initializing huge arrays this way is inefficient • Array declarations Array declarations 30 • A little surprising for C/C++ programmers • int[] A and int A[] have identical semantics • declares A to be a variable that contains a reference to an array of int’s • int[] A[], B; • A is a ref to an array of ref’s array of int’s • B is a ref to an array of int’s • None of these allocate an array • A = new int [10] allocates an array of 10 int’s and makes A be a reference to it • Array example 15 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] int[] array1 = {1,3,5}; int[][] a = new int[10][3]; // a.length == 10 // a[7].length == 3 a[5][2] = 42; a[9] = array1; // a[9][2] == 5 // Use of array initializers int[][] twoD = {{1,2,3},{4,5},{6}}; Object [] args = {"one", "two", a }; main(new String [] {"a", "b", "c"}); 31 Array example String • A class for representing non-mutable strings public static void printArray(Object [] a) { for(int i=0; i < a.length; i++) System.out.println("a[" + i + "] = " + a[i]); } 32 • “string constants” in program are converted into a String • + does string concatenation • In some contexts, objects are automatically converted to String type • More about strings later... 16 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Object/memory allocation • The only way/time an object gets allocated is: • by executing new • One object per invocation of new • by having a array constant (e.g., {5, -5, 42}) • having a string constant (e.g., "Hello World!") • Declaring a reference variable doesn’t allocate an object • Allocating an array doesn’t automatically allocate the contents of the array • multi-array creation int [][] a = new int[10][10]; • Equivalent to (but faster than): int [][]a = new int[10][]; for(int i = 0; i < 10; i++) a[i] = new int[10]; 33 • No explicit deallocate is required/allowed Garbage Collection • Java uses garbage collection to find objects that cannot be referenced • (e.g., do not have any pointers to them) 34 • Garbage collection not a major bottleneck • Faster Garbage Collectors coming • On existing commercial systems, GC runs on only a single processor 17 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Classes • Each object is an instance of a class • An array is an object 39 • Each class is represented by a class object • (of type Class) • Each class extends one superclass • (Object if not specified) • except class Object, which has no superclass More about Classes • Each class has an associated set of methods and fields/variables • Variables hold primitive values or object references 40 • Use ‘.’ to access object fields • variables and methods • e.g., x.y(a.b) • Most methods are invoked using C++ virtual method semantics • except static, private and final methods 20 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Class Modifiers • public - class is visible outside package 41 • final - No other class can extend this class • abstract - no instances of this class can be created • instances of extensions of it can class Complex - a toy example public class Complex { double r,i; Complex (double r, double i) { this.r = r; this.i = i; } Complex plus(Complex that) { return new Complex( r + that.r, i + that.i); } public String toString() { return “(“ + r + “,” + i + “)”; } public static void main(String [] args) Complex a = new Complex (5.5,9.2); Complex b = new Complex (2.3,-5.1); Complex c; c = a.plus(b); System.out.println(“a = “ + a); System.out.println(“b = “ + b); System.out.println(“c = “ + c); } } a = (5.5,9.2) b = (2.3,-5.1) c = (7.8,4.1) 42 21 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Details • You can overload method names • The method invoked is determined by both the name of the method • and the types of the parameters • resolved at compile time, based on compile-time types 43 • You can override methods: define method that is also defined by a superclass • arguments and result types must be identical • resolved at run-time, based on object method is invoked on • this refers to the object method is invoked on • super refers to same object as this • but used to access method/variables for superclass Methods • Methods are operations supported by an object/class 44 • Can be declared in both classes and interfaces • Can only be implemented in classes • All methods must have a return type • except constructors • void can be used only as a return type • references to arrays or objects can be returned • Method declaration syntax: modifiers returnType methodName ( params ) { [methodBody] } 22 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Overriding • Methods with same name and argument types in a child class override the method in the parent class class Parent { int cost; void add (int x) { cost += x; } } class Child extends Parent { void add (int x) { if (x > 0) cost += x; } } 49 • You can override/hide variables • Both variables will exist • You don’t want to do this Overloading • Methods with the same name, but different parameters, either count or type are overloaded: class Parent { int cost; void add (int x) { cost += x; } } class Child extends Parent { void add (String s) throws NumberFormatException { cost += Integer.parseInt(s); } } 50 25 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Dynamic method dispatch • If you have a ref a of type A to an object that is actually of type B (a subclass of A) • instance methods invoked on a will get the methods for class B (i.e., C++ virtual functions) • class methods invoked on a will get the methods for class A • invoking class methods on objects discouraged 51 • Simple Dynamic Dispatch example • Detailed Example Simple Dynamic Dispatch example 52 class A { String f() {return "A.f() "; } static String g() {return "A.g() "; } } public class B extends A { String f() {return "B.f() "; } static String g() { return "B.g() "; } public static void main(String args[]) { A a = new B(); B b = new B(); System.out.println(a.f() + a.g() + b.f() + b.g()); } } java B generates: B.f() A.g() B.f() B.g() 26 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Detailed Example • Shows • polymorphism for both method receiver and arguments • static vs instance methods • overriding instance variables • Source • Invocation and results • What to notice 53 54 class A { String f(A x) { return "A.f(A) "; } String f(B x) { return "A.f(B) "; } static String g(A x) { return "A.g(A) "; } static String g(B x) { return "A.g(B) "; } String h = "A.h"; String getH() { return "A.getH():" + h; } } class B extends A { String f(A x) { return "B.f(A)/" + super.f(x); } String f(B x) { return "B.f(B)/" + super.f(x); } static String g(A x) { return "B.g(A) "; } static String g(B x) { return "B.g(B) "; } String h = "B.h"; String getH() { return "B.getH():" + h + "/" + super.h; } } Source 27 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Interfaces • An interface is just an object type; no associated code or instance variables • describes methods supported by interface 59 • A class can “implement” (be a subtype of) any number of Interfaces • May have final static variables • Way to define a set of constants Interface example public interface Comparable { public int compareTo(Object o) } public class Util { public static void sort(Comparable []) {...} } public class Choices implements Comparable { public int compareTo(Object o) { return ...; } } ... Choices [] options = ...; Util.sort(options); ... 60 30 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] No multiple inheritance • A class type can be a subtype of many other types (implements) 61 • Can only inherit method implementations from one superclass (extends) • Not a significant omission (in my opinion) • multiple inheritance is rarely or never necessary or well-used • “The Case against Multiple Inheritance in C++”, T.A. Cargil, The Evolution of C++ • Substantially complicates implementation Garbage Collection • Objects that are no longer accessible can be garbage collected 62 • method void finalize() is called when an object is unreachable • best to avoid using finalize • Garbage collection is not a major bottleneck • malloc/free can be expensive as well 31 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Class Objects • For each class, there is an object of type Class 63 • Describes the class as a whole • used extensively in Reflection package • Class.forName("MyClass") • returns the class object for MyClass • will load MyClass if needed • Class.forName("MyClass").newInstance() • will create a new instance of MyClass • MyClass.class will also give the Class object for MyClass Types • A type describes a set of values that can be: • Held in a variable • Returned by an expression 64 • Types include: • Primitive types: boolean, char, short, int, ... • Reference types: • Class types • Array types • Interface types 32 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Object Obligations 69 public boolean equals(Object that) { ... } // default is return this == that public String toString() { ... } // returns print representation public int hashCode() { ... } // key for object // important that a.equals(b) // implies a.hashCode() == b.hashCode() public void finalize() { ... } // called before Object is garbage collected // default is {} public Object clone() { ... } // default is shallow bit-copy if implements Cloneable // throw CloneNotSupportedException otherwise • These operations have default implementations • which may not be the one you want 70 Poor man's polymorphism • Every object is an Object • An Object[] can hold references to any objects • If we have a data structure Set that holds a set of Object • Can use it for a set of String • or a set of images • or a set of anything • Java’s container classes are all containers of Object • When you get a value out, have to downcast it Hashtable h; h.put("Key","Value"); String v = (String) h.get("Key"); 35 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] http://www.cs.umd.edu/~pugh/java/crashCourse Applications, Applets and Graphics Day 1, session 4 Applications, Applets and Graphics • applications methods 72 • applet methods • embedding applets in HTML • making applets available over the web • minimal Graphics 36 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Applications • External interface is a public class 73 • with public static void main(String []args) • args[0] is first argument (unlike C/C++) • System.out and System.err are PrintStream’s • Should be PrintWriter’s, but would break 1.0 code • System.out.print(...) prints a string • System.out.println(...) prints a string and adds a newline • System.in is an InputStream • Not quite as easy to use Reading text input in (JDK 1.1) applications 74 • Wrap System.in in a InputStreamReader • converts from bytes to characters • Wrap it in a BufferedReader • makes it efficient (buffered) • supports readLine() • readLine() returns a String • returns null if at EOF 37 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Example Applet HTML code <applet code=DisplayTextApplet width=300 height=50> <param name=message value="Crash Course"> <param name=fontName value=Dialog> <param name=fontSize value=24> </applet> 79 Try it 80 • Hello world applet is at • http://www.cs.umd.edu/~pugh/crashCourse/HelloWorldApplet.html 40 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Making applets available over the web • Put class files in a directory on web server 81 • Put applet/embed code in HTML file • Point codebase to that directory • Specify class file containing applet class Graphics: A device-independent interface to graphics setColor(Color c) drawLine(int x1, int y1, int x2, int y2) drawRect(int x, int y, int width, int height) draw3DRect(int x, int y, int width, int height, boolean raised) drawOval(int x, int y, int width, int height) fillRect(int x, int y, int width, int height) fillOval(int x, int y, int width, int height) setFont(Font f) drawString(String s, int x, int y) 82 41 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] java.awt.Font • Cross-platform fonts: • SansSerif, Serif, Monospaced, Dialog, DialogInput 83 • Font styles: • Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC+Font.BOLD • Font sizes: any point size allowed • Constructor: Font(String name, int style, int size) • Also: Font.decode(String description) java.awt.FontMetrics • Must get from a Graphics or Container object • FontMetrics fm = g.getFontMetrics(f) 84 • int stringWidth(String str) • int getAscent() • int getDescent() • DisplayTextApplet -- Source 42 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] 89 Why do applets have a destroy() method? • Couldn’t I just use finalize() instead? • Good question! • Serve same purpose • Answer: • Yes • But destroy() will be called sooner • need to depend on GC for finalize() Some bigger applets • Clock • Example: http://www.cs.umd.edu/~pugh/java/crashCourse/Clock.html • Source: http://www.cs.umd.edu/~pugh/java/crashCourse/Clock.java 90 • Graph Layout • Example: http://www.cs.umd.edu/~pugh/java/crashCourse/Graph.html • Source: http://www.cs.umd.edu/~pugh/java/crashCourse/Graph.java • Tic-Tac-Toe • Example: http://www.cs.umd.edu/~pugh/java/crashCourse/TicTacToe.html • Source: http://www.cs.umd.edu/~pugh/java/crashCourse/TicTacToe.java 45 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] http://www.cs.umd.edu/~pugh/java/crashCourse Java programming environments Day 1, session 5 Java programming environments • Situation constantly changing 92 • Sun’s JDK freely available for most platforms • GUI-creation tools that generate Java are here • Useful • Improving 46 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Classes are grouped into packages • For example, java.awt.image • avoids problems such as multiple LinkedList classes 93 • No semantics to having a common prefix • e.g., between java.awt and java.awt.image • but use them logically • Package names are an implicit or explicit part of a class name • e.g., java.awt.image.ColorModel Imports make a package name implicit • If you import a class or package, you can use just the last name • allow use of ColorModel rather than java.awt.image.ColorModel import java.awt.image.ColorModel; • For each class C in java.awt.image, allow use of C rather than java.awt.image.C import java.awt.image.*; 94 • implicit at the beginning of every java file import java.lang.*; • import never required, just allows shorter names 47 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] jar - Java archive tool • First letter of first argument is action: create/list/extract 99 • other letters are options: • f - get jar file name from next argument • m - when creating jar file, read manifest from file given as argument • v - verbose • Examples • jar cvf test.jar *.class data • jar tvf test.jar • jar xf test.jar • jar xf test.jar Test.class appletviewer - Applet tester • appletviewer files 100 • One window per applet • Other HTML ignored • Can also supply URL’s 50 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] javadoc - java documentation tool • javadoc packagename • e.g., javadoc edu.umd.cs.pugh 101 • Looks for packagename on classpath • Builds HTML documentation for package • Special comments in java source files put into HTML What goes where • Each public class C must be in a file C.java 102 • If a class C is part of a package P • package P; must be the first statement in C.java • which must be in a directory P • Treats . in package name as sub-directories • Reverse of domain name is reserved package name • edu.umd.cs is reserved for the Univ. Maryland CS department • Classpath gives list of places to look for class files • both directories and jar/zip files • As of 1.1, you shouldn't set classpath to tell it where to find system files • You only need to set it for your own files • If there are part of a package • If they aren’t in the current directory 51 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] JAR files 103 • Downloading 50 class files and 10 images over http is very expensive • JAR files are compressed archives • extension of zip format • Can hold class files, images, other files • Java knows how to load JAR files over the net • Java knows how to extract files from a JAR • JAR files can be signed java.lang • Wrapper classes 104 • class String • class StringBuffer 52 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Java Surprises • You don’t ever need to use import 109 • Declaring a variable of class Foo doesn’t allocate an object of class Foo • All variables are references to heap allocated objects • packages, classes, methods, fields and labels are separate name spaces • you can label any statement and break out of it • Hard to unload/update a class • You need to give the full package and class name to java interpreter • but give the file name to the compiler More surprises • Internationalization makes things harder • Many things take more steps than they would in an English/US only system 110 • Threads may or may not be preemptive • You can pass an String[] to a method that wants an Object[] • When you store into an array a type check is made • You will write methods you never call • e.g., method paint(Graphics g) of an Applet • And call methods you never wrote • e.g., method repaint() of an Applet 55 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Still More Surprises • Override update to eliminate animation flashing 111 • Beware of RuntimeExceptions • Watch out for broken sound • Exceptions in a thread just kill thread • Watch for misspelling or using wrong types when overriding This slide intentionally left blank 112 56 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] http://www.cs.umd.edu/~pugh/java/crashCourse Exceptions and Inner classes Day 2, session 1 Exceptions and Inner Classes • Exceptions • declaring exceptions • catching and throwing exceptions • Using finally 114 • Inner classes • introduced in Java 1.1 • allows classes to be defined inside other classes • inner classes have access to variables of outer class • designed for creating helper objects • Listeners, Adaptors, ... • Fairly important for Java 1.1 GUI event model 57 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Creating New Exceptions • A user defined exception is just a class that is a subclass of Exception class MyVeryOwnException extends Exception { } class MyClass{ void oops() throws MyVeryOwnException { if (some_error_occurred){ throw new MyVeryOwnException(); } } } 119 Throwing an Exception/Error • Just create a new object of the appropriate Exception/Error type 120 • and throw it • Unless a subtype of Error or RuntimeException • must declare that the method throws the exception • Exceptions thrown are part of the return-type • when overriding a method in a superclass • can’t throw anything that would surprise a superclass 60 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Exception/Error Handling • Exceptions eventually get caught 121 • First catch with supertype of the exception catches it • Don’t catch errors/throwable • finally is always executed try { if (i == 0) return; myMethod(a[i]); } catch (ArrayIndexOutOfBounds e){ System.out.println("a[] out of bounds"); } catch (MyVeryOwnException e){ System.out.println("Caught my error"); } catch (Exception e){ System.out.println ("Caught" + e.toString()); throw e; } finally { /* stuff to do regardless of whether an */ /* exception was thrown or return taken */ } java.lang.Throwable • Many objects of class Throwable have a message • specified when constructed • String getMessage() // returns msg 122 • String toString() • void printStackTrace() • void printStackTrace(PrintWriter s) 61 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Inner Classes • Allow a class to be defined within a class or method 123 • new class has access to all variables in scope • classes can be anonymous • 4 Kinds of Inner Classes • Lots of important details 4 Kinds of Inner Classes • nested classes/interfaces 124 • Standard inner classes • method classes and anonymous classes 62 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] method classes and anonymous classes • Can refer to all methods/variables of outerclass 129 • Can refer to final local variables • Can’t have any static methods/variables • Method classes defined like a method variable • Anonymous classes defined in new expression new BaseClassOrInterface() { extensions } • Method class Example • Anonymous class Example 130 public class FixedStack { Object array []; int top = 0; public java.util.Enumerator enumerateOldestK(final int k) { class MyEnum implements java.util.Enumerator { int pos = 0; public boolean hasMoreElements() { return pos < k && pos < top; } public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException("FixedStack"); return array[pos++]; } } return new MyEnum(); } } Method class Example 65 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] 131 public class FixedStack { Object array []; int top = 0; public java.util.Enumerator enumerateOldestK(final int k) { return new java.util.Enumerator() { int pos = 0; public boolean hasMoreElements() { return pos < k && pos < top; public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException("FixedStack"); return array[pos++]; } } } Anonymous class Example 132 Lots of important details • If class B is defined inside of class A • A synchronized method of B locks B.this, not A.this • You may want to lock A.this for synchronization • Can have many B’s for each A • Can’t define constructor for anonymous inner class • Inner classes are a compile-time transformation • separate class file generated for each inner class • $’s in names 66 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] http://www.cs.umd.edu/~pugh/java/crashCourse Multithreading and Synchronization Day 2, session 2 Multithreading and Synchronization • What is a thread? • Deprecated Methods on Threads 134 • Writing Multithreading code can be difficult • Working with Threads • Synchronization • A common multithreading bug • Some guidelines to simple/safe multithreaded programming 67 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Simple thread methods • void start() 139 • boolean isAlive() • void setDaemon(boolean on) • If only daemon threads are running, VM terminates • void setPriority(int newPriority) • Thread schedule might respect priority • void join() throws InterruptedException • Waits for a thread to die/finish Simple static thread methods • Apply to thread invoking the method void yield() void sleep(long millisecs) throws InterruptedException Thread currentThread() 140 70 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] interface Runnable • extending Thread means can’t extend anything else 141 • Instead implement Runnable • Declares that an object has a void run() method • Create a new Thread • giving it an object of type Runnable • Constructors: Thread(Runnable target) Thread(Runnable target, String name) Thread Example 142 public class ThreadDemo implements Runnable { public void run() { for (int i = 5; i> 0; i--) { System.out.println(i); try { Thread.sleep(1000); } catch (InterruptedException e) { }; } System.out.println("exiting " + Thread.currentThread() ); } public static void main(String args[]) { Thread t = new Thread(new ThreadDemo(), "Demo Thread"); System.out.println("main thread: " + Thread.currentThread()); System.out.println("Thread created: " + t); t.start(); try { Thread.sleep(3000); } catch (InterruptedException e){ }; System.out.println("exiting " + Thread.currentThread() ); } } 71 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] InterruptedException • A number of thread methods throw this exception • Really means: wakeUpCall 143 • interrupt() sends a wakeUpCall to a thread • won’t disturb the thread if it is working • however, if the thread attempts to sleep • it will get immediately woken up • will also wake up the thread if it is already asleep • thrown by sleep(), join(), wait() Be careful • Under some implementations • a thread stuck in a loop will never yield by itself 144 • Preemptive scheduling would guarantee it • not supported on all platforms • Put yield() into loops • I/O has highest priority, so should be able to get time 72 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Synchronized methods • A method can be synchronized • add synchronized before return type 149 • Obtains a lock on object referenced by this before starting method • releases lock when method completes • A static synchronized method • locks the class object Synchronized statement • synchronized (obj) { block } 150 • Obtains a lock on obj before executing block • Releases lock once block completes • Provides finer grain of control • Allows you to lock arguments to a method 75 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Example with Synchronization 151 class SyncTest extends Thread { String msg; public SyncTest(String s) { msg = s; start(); } public void run() { synchronized (SyncTest.class) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e) {}; System.out.println("]"); } } public static void main(String args[]) { new SyncTest("Hello"); new SyncTest("Synchronized"); new SyncTest("World"); } } Using wait and notify • a.wait() • Gives up lock(s) on a • adds thread to wait set for a • suspends thread 152 • a.wait(int m) • limits suspension to m milliseconds • a.notify() resumes one thread from a’s wait list • and removes it from wait set • no control over which thread • a.notifyAll() resumes all threads on a’s wait list • resumed tasks must reacquire lock before continuing • wait doesn’t give up locks on any other objects 76 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] ProducerConsumer example 153 synchronized Object consume() { while(!ready) wait(); ready=false; notifyAll(); return obj; } synchronized void produce(Object o) { while(ready) wait(); obj = o; ready=true; notifyAll(); } } public class ProducerConsumer { private boolean ready = false; private Object obj; public ProducerConsumer() { } public ProducerConsumer(Object o) { obj = o; ready = true; } A change 154 synchronized void produce(Object o) { while(ready) { wait(); if (ready) notify(); } obj = o; ready=true; notify(); } Bad design - no guarantee about who will get woken up synchronized Object consume() { while(!ready) { wait(); if (!ready) notify(); } ready=false; notify(); return obj; } 77 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] 159 Example of common multithreading bug while (true) { try { sleep(100); } catch (InterruptedException e) {}; if (runFlag) c2.t.setText(Integer.toString(count++)); } • From Bruce Eckel’s “Thinking in Java” • mostly an excellent book • Problems with this example • No way for thread to gracefully die • runFlag might be cached (never see changes by other threads) • c2.t might be cached (write never seen by other threads) Some guidelines to simple/safe multithreaded programming • Synchronize/lock access to shared data 160 • Don’t hold a lock on more than one object at a time • could cause deadlock • Hold a lock for as little a time as possible • reduces blocking • While holding a lock, don’t call a method you don’t understand • e.g., a method provided by another client • Have to go beyond this for sophisticated situations • But need to understand threading/synchronization well • Recommended book for going further: • Concurrent Programming in Java by Doug Lea 80 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] http://www.cs.umd.edu/~pugh/java/crashCourse Abstract Windowing Toolkit Day 2, session 4 Abstract W indowing T oolkit • The AWT is very complex (as is any GUI library) 162 • The event model was changed substantially for version 1.1 • Big improvement • Inter-operable, but not within the same window • To keep things manageable, I’ll only discuss 1.1 model • Only reason to use 1.0 model is to be compatible with older browsers 81 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Widgets/Components • Container - Panel or Window 163 • Button • Checkbox • Choice • Label • List • Scrollbar • TextField • TextArea Automatic Layout Managers • Determine position and size of components 164 • Depends on minimum, preferred and maximum size of components • Allows resizing of windows • Controls where extra space goes • Allows for the fact that on different platforms and in different languages • Components might have different sizes • Without a layout manager, must position each component • Can write your own layout manager • Several layout managers provided 82 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Example 1.1 Event handling - part 3 Choice c; add ( c = new Choice()); c.addItem("Red"); c.addItem("Green"); c.addItem("Blue"); c.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { check(e); } }); TextField tf; add(tf = new TextField(8)); tf.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { text(e); } }); tf.addTextListener( new TextListener() { public void textValueChanged(TextEvent e) { text(e); } }); pack(); show(); }}} 169 Removing animation flicker • Default update() method for applets • Erase to background color • call paint() to draw new image on clean background • Can cause flicker 170 • Eliminate flicker • Erase offscreen image • paint onto a offscreen image • copy offscreen image onto screen • class FlickerFree • Anyone who extends FlickerFreeApplet is flicker free 85 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] class FlickerFree 171 public class FlickerFreeApplet extends Applet { private Image offscreenImage; private Graphics offscreenGraphics; private Dimension offscreenDimension; 172 FlickerFreeApplet’s update public final void update(Graphics g) { Dimension d = size(); // warning! In 1.0, Dimension.equals is broken if (offscreenImage == null || !d.equals(offscreenDimension)) { offscreenDimension = d; offscreenImage = createImage(offscreenDimension.width, offscreenDimension.height); offscreenGraphics = offscreenImage.getGraphics(); }; offscreenGraphics.setColor(getBackground()); offscreenGraphics.fillRect(0,0, offscreenDimension.width,offscreenDimension.height); offscreenGraphics.setColor(getForeground()); offscreenGraphics.setFont(getFont()); paint(offscreenGraphics); g.drawImage(offscreenImage,0,0,this); } 86 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] http://www.cs.umd.edu/~pugh/java/crashCourse I/O, Networking and Utility libraries Day 2, session 5 I/O, Networking and Utility libraries • I/O classes 174 • URL’s and Web connections • Sockets • java.util • Other libraries • Loading Resources 87 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Reader - character stream coming in • InputStreamReader • Wrap around an InputStream to get a Reader • takes bytes, converts to characters • Can specify encoding used to convert bytes to characters 179 • CharArrayReader • StringReader • Filters • BufferedReader - efficient, supports readLine() • LineNumberReader - reports Line Numbers • PushbackReader • Convenience Readers • wraps an InputStreamReader around an InputStream • FileReader • PipedReader URL’s and Web connections • Example: URLGet • URL’s • URLConnection 180 90 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] 181 import java.net.*; import java.io.*; public class URLGet { public static void main(String [] args) throws Exception { if (args.length != 1) { System.out.println("Please supply one URL as an argument"); System.exit(1); } URL u = new URL(args[0]); BufferedReader in = new BufferedReader( new InputStreamReader(u.openConnection().getInputStream())); String s; while((s = in.readLine()) != null) System.out.println(s); } } Example: URLGet URL ’ s URL u = new URL("http://www.cs.umd.edu:8080/index.html"); // then URLConnection conn = u.openConnection(); // or InputStream in = u.openStream(); // or Object o = u.getContents(); // depends on finding ContentHandler // parses content // e.g., JPEG file turned into image 182 91 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] URLConnection int len = conn.getContentLength(); // Number of bytes in content long date = conn.getDate(); // Time of last modification // Milliseconds since Epoc // Convert to Date() for other forms String type = conn.getContentType(); // Get Mime type of content Object o = conn.getContent(); // finds ContentHandler to parse Contents 183 Sockets • Sockets are Internet’s way of sending/receiving messages 184 • everything is done via a socket • Supports • TCP sockets • guaranteed, stream based communication • UDP sockets • unguaranteed, packet based communications • also supports Multicast UDP sockets • TCP Client Socket Example • TCP Server Socket Example 92 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Dictionaries • Dictionary • An abstract class • Represents a key to value mapping 189 • HashTable • An implementation of Dictionary • Properties • Uses HashTable • Keys and Values are Strings • Allows scoping • Can be saved to a file Enumerations and Bitsets • Enumeration • Just an Interface • Used in a number of places to return an enumeration public boolean hasMoreElements() public Object nextElement() 190 • BitSet • Provides representation of a set as a bitvector • Grows as needed 95 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Miscellaneous • Date • Not a great design • 1.1 adds java.util.Calendar and java.text.DateFormat • many Date methods depreciated • Complicated due to internationalization • and bad design? 191 • Random • StringTokenizer StringTokenizer tokens = new StringTokenizer(msg," "); while (tokens.hasMoreTokens()) System.out.println(tokens.nextToken()); • java.util.zip package • Provides ability to read/write zip archives Java 1.2 Collection Classes 192 • interface Collection • interface List • class Vector • class Stack • class ArrayList • class LinkedList - a doubly linked list • interface Set • class HashSet • interface SortedSet • class TreeSet • interface Map - Dictionary like structures • class HashMap; replaces HashTable • interface SortedMap • class TreeMap 96 Crash course in Java, by William Pugh http://www.cs.umd.edu/~pugh/java/crashCourse © 1998 by William Pugh, [email protected] Other libraries • class java.lang.Math • abstract final class - has only static members • Includes constants E and PI • Includes static methods for trig, exponentiation, min, max, ... 193 • java.text Package • New to Java 1.1 • Text formatting tools • java.text.MessageFormat provides printf/scanf functionality • Lots of facilities for internationalization 194 Loading Resources • Can load resources from same place as class • images • Text files • Serialized Objects • local file or http connection • directory or jar file • easiest way to get data out of a jar file • Code snippets 97