Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Princeton University COS 333: Advanced Programming Techniques A Subset of Java Program Structure public class Hello { public static void main(String[] args) // Print "hello, world" to stdout. { System.out.println("hello, world"); } } ----------------------------------------------------------------------------------public class Square { public static void main(String[] args) { System.out.println(sqr(5)); } private static int sqr(int i) { return i * i; } } ----------------------------------------------------------------------------------Methods within a class can be defined in any order. Typically must import classes/interfaces from other packages: import package.subpackage.classorinterface; Building and Running javac Class.java java Class Terminal I/O Reading from stdin: import java.util.Scanner; Scanner scanner = new Scanner(System.in); int i = scanner.nextInt(); double d = scanner.nextDouble(); Writing to stdout: System.out.print(i); System.out.println(d); Page 1 of 8 Writing to stderr: System.err.print(i); System.err.println(d); Reserved Words abstract, assert, boolean, break, byte, case, catch, char, class, const*, continue, default, do, double, else, enum, extends, final, finally, float, for, goto*, if, implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while * unused Primitive Data Types boolean char byte short int long float double 1 2 1 2 4 8 4 8 bit bytes byte bytes bytes bytes bytes bytes true, false '\u0000', 'uFFFF', 'a', '\n', '\t', '\0' (byte)-128, (byte)127 (short)-32768, (short)32767 -2147483648, 2147483647 -9223372036854775808L, 9223372036854775807L 123.456F 123.456 A datum of a primitive type is not an object. Variables must be declared before used. Operators method(params) a[i] obj.field, obj.method() class.field, class.method() i++, ++i, i-–, --i +x, -x ~i, !b new Class() (type) x*y, x/y, i%j x+y, x-y i<<j, i>>j, i>>>j x<y, x>y, x<=y, x>=y obj instanceof Class x==y, x!=y i&j i^j i|j b1&&b2 b1||b2 b?x:y x=y x+=y, x-=y, x*=y, x/=y, i%=j i&=j, i^=j, i|=j i<<=j, i>>=j, i>>>=j (1) method call (parameters passed by value) (1) array element selector (1) object member selector (1) class member selector (2) increment, decrement (2) unary plus, unary minus (2) bitwise NOT, logical NOT (3) object creation (3) typecast (4) multiplication, division, remainder (5) addition, subtraction (6) left-shift, right-shift, right-shift zero fill (7) obvious (7) instanceof (8) equality, inequality (9) bitwise AND (10) bitwise EXCLUSIVE OR (11) bitwise OR (12) logical AND (13) logical OR (14) conditional expression (15) assignment (15) assignment (15) assignment (15) assignment Page 2 of 8 Statements Expression statement: expr; Declaration statement: modifiers datatype var [= expr][, var [= expr]]...; Common modifiers: const, static Compound statement: { statement; statement; ...} Selection statements: if (booleanExpr) statement else statement; switch (intExpr) { case (intvalue1): statement; ...; break; case (intvalue2): statement; ...; break; ... default: statement; ...; } Iteration statements: while (booleanExpr) statement; do statement while (booleanExpr); for (initExpr; booleanExpr; incrExpr) statement; for (type var : IterableOrArrayObject) statement; break; continue; Return statement: return; return expr; Classes, Objects, and Object References import java.util.HashMap; public class MyClass { private int i; public MyClass(int i) { this.i = i; } public int get() { return i; } public void set(int i) { this.i = i; } public String toString() { return "" + i; } public boolean equals(Object other) { if (! (other instanceof MyClass)) return false; return i == ((MyClass)other).i; Page 3 of 8 // "foreach" statement } public int hashCode() { return i; } public static void main(String[] args) { MyClass myObj1 = new MyClass(5); myObj1.set(10); System.out.println(myObj1.get()); System.out.println(myObj1); MyClass myObj2 = new MyClass(10); if (myObj1.equals(myObj2)) System.out.println("equal"); if (! myObj1.equals(myObj2)) System.out.println("not equal"); HashMap hashMap = new HashMap(); hashMap.put(myObj1, myObj2); } // weak // calls myObj1.toString() // calls myObj1.hashCode() } Data Structures Arrays int[] a1; a1 = new int[5]; int[] a2 = new int[] {18, 19, 20, 21, 22}; String[] a3 = new String[3]; int i = a1.length; int j = a2[1]; // 19 Strings String s1; s1 = "COS"; s1 = "COS" + " 333"; s1 += " is fun"; int i = s1.length(); String s2 = "" + 5; String s3 = "" + obj; // Conversion from primitive type to String // Conversion from any class to String; // calls toString() Container interfaces (all are in package java.util) Iterable: an object over which one can iterate Collections: the root interface List: an ordered collection Set: a collection that contains no duplicates SortedSet: a map that orders its keys Map: an object that maps keys to values SortedMap: a map that orders its keys Iterator ListIterator Container classes (all except java.lang.Object are in package java.util) Object AbstractCollection (implements Collection) AbstractList (implements List) ArrayList: a List implemented as an Array Page 4 of 8 AbstractSequentialList LinkedList: a List implemented as a linked list AbstractSet (implements Set) HashSet: a Set implemented as a hash table TreeSet (implements SortedSet): a Set implemented as a r/b tree AbstractMap (implements Map) HashMap: a Map implemented as a hash table TreeMap (implements SortedMap): a map implemented as a r/b tree Arrays: utility methods related to arrays Collections: utility methods related to Collection objects Comparator Some Collection methods i = coll.size(); bool = coll.contains(obj); bool = coll.isEmpty(); bool = coll.add(obj); bool = coll.remove(obj); bool = coll.clear(); a[] = coll.toArray(); iter = coll.iterator(); // optional // optional // optional Some Iterator methods bool = iter.hasNext(); obj = iter.next(); Some List methods obj = list.get(index); index = list.indexOf(obj); oldObj = list.set(index, obj); bool = list.add(index, obj); bool = list.remove(index); // optional // optional // optional Some SortedSet methods (can specify Comparator object in constructor) obj = sortedSet.first(); obj = sortedSet.last(); Some Map methods i = map.size(); bool = map.containsKey(obj); bool = map.containsValue(obj); obj = map.get(key); oldValue = map.put(key, value); // optional oldValue = map.remove(key); // optional map.clear(); bool = map.isEmpty(); set = map.keySet(); coll = map.values(); Some SortedMap methods (can specify Comparator object in constructor) obj = sortedMap.firstKey(); obj = sortedMap.lastKey(); Some Arrays methods sort(a); sort(a, comparator); i = binarySearch(a, obj); Page 5 of 8 i = binarySearch(a, obj, comparator); Some Collections methods i = binarySearch(list, obj); i = binarySearch(list, obj, comparator); sort(list); sort(list, comparator); A Comparator method i = comparator.compare(obj1, obj2); Files All except java.lang.Object are in package java.util. Object InputStream (System.in is an object of this class) ByteArrayInputStream (source) FileInputStream (source) FilterInputStream (decorator) BufferedInputStream (decorator) DataInputStream (decorator) PushbackInputStream (decorator) ObjectInputStream (decorator) PipedInputStream (special) SequenceInputStream (decorator twice) OutputStream ByteArrayOutputStream (source) FileOutputStream (sink) FilterOutputStream (decorator) BufferedOutputStream (decorator) DataOutputStream (decorator) PrintStream (decorator) (System.out is an object of this class) ObjectOutputStream (decorator) PipedOutputStream (special) Reader BufferedReader (decorator) LineNumberReader (decorator) CharArrayReader (source) FilterReader (decorator) PushbackReader (decorator) InputStreamReader (bridge) FileReader (decorator) PipedReader (special) StringReader (source) Writer BufferedWriter (decorator) CharArrayWriter (source) FilterWriter (decorator) OutputStreamWriter (bridge) FileWriter (decorator) PipedWriter (special) PrintWriter (bridge, decorator) StringWriter (source) File FileDescriptor Page 6 of 8 RandomAccessFile ObjectStreamClass StreamTokenizer Reader and Writer classes are for characters InputStream and OutputStream classes are for bytes For efficient reading of characters from stdin: InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); br.readLine(); For efficient reading of characters from a file: FileInputStream fis = new FileInputStream("filename"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); br.readLine(); For efficient writing of characters to stdout: OutputStreamWriter osw = new OutputStreamWriter(System.out); BufferedWriter bw = new BufferedWriter(osw); PrintWriter pw = new PrintWriter(bw); pw.println(whatever); pw.close(); For efficient writing of characters to a file: FileOutputStream fos = new FileOutputStream("filename"); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); PrintWriter pw = new PrintWriter(bw); pw.println(whatever); pw.close(); Command-Line Arguments The args parameter of main() is an array of Strings args[0] is not the name of the program; it's the first command-line argument public class Class { public static void main(String[] args) { if (args.length != 2) { System.err.println("Usage: java Class arg1 arg2\n"); System.exit(1); } ... } } Debugging To use the jdb debugger: javac -g Class.java jdb Class Debugger commands: help Page 7 of 8 stop in pkg.pkg.Class.method stop in pkg.pkg.Class.method(paramtype, paramtype, …) stop at pkg.pkg.Class:line clear pkg.pkg.Class.method clear pkg.pkg.Class.method(paramtype, paramtype, …) clear pkg.pkg.Class:line run run pkg.pkg.Class run pkg.pkg.Class args list next step cont print expr where quit Type !! to repeat the last command. Etc. We'll cover other features of Java throughout the course as necessary. Copyright © 2011 by Robert M. Dondero, Jr. Page 8 of 8