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
Zaawansowane programowanie obiektowe Lecture 1 Szymon Grabowski [email protected] http://szgrabowski.kis.p.lodz.pl/zpo/ Thx to Wojciech Bieniecki for sharing stuff and friendly advices Łódź, 2009 Recommended literature / resources Bruce Eckel, Thinking in Java, Prentice Hall, NJ, 1998. http://java.sun.com/ Cay S. Horstmann, Gary Cornell, Core Java 2 : Volume I – Fundamentals; Volume II – Advanced Features, Prentice Hall, 2007 (8th Edition). http://www.horstmann.com/corejava/corejava8.zip In Polish: Java. Podstawy. Wyd. VIII, 2008 (Helion), Java. Techniki zaawansowane. Wydanie VIII, 2009 (Helion). Krzysztof Barteczko, Java. Wykłady i ćwiczenia, Mikom, 2000 (in Polish). Krzysztof Barteczko, Java od podstaw do techologii, tom 1 i 2, Mikom, 2004 (in Polish). KIS Java Pages , in Polish: http://wbieniec.kis.p.lodz.pl/studenci/pliki/2008-pwsg/ (?) http://jacenty.kis.p.lodz.pl/systemy_multimedialne.html 2 A little bit of history Developed by Sun in 1995. Based on C++. Versions: 1.0.x, 1.1.x etc. up to 1.6 now (Dec. 2006). (Don't get confused: everything from v1.2+ is Java 2.) Java 2 in three editions: standard (SE), enterprise (EE) and micro (ME). For example, J2ME is for PDA’s (e.g. cell phones) – lighter. 3 Design goals Portability (running on a Java Virtual Machine). High-level (objects, threads, exceptions, interfaces, packages, native zip handling...). Rich standard library (GUI, DB support, regexp, algorithms and data structures). Basically, there are three kinds of Java applications: • applets (interpreted and run by a web browser, on the client side); • servlets (on the server side); • stand-alone apps. 4 What makes Java safe Garbage collector. (No delete for objects, arrays... Objects no longer used will be deallocated automatically.) Exceptions everywhere. (In C++ they were optional. Here they are mandatory.) Applets – sandbox model. (Some operations not allowed, unless perhaps the applet’s digital signature is approved.) References, no pointers. Strong typing. No implicit conversions (except some safe cases, see later), no int boolean conversion. 5 What makes Java slow See previous slide... But also, and this is the most important speed penalty factor, the thing that Java is interpreted by a JVM. 6 Create & run Java code [ http://ww2.cs.fsu.edu/~pfenning ] Five stages: 1. Edit – creating .java file 2. Compile – creating .class files (one .class file per built class). This is B-code (cmd-line: javac MyClass.java) 3. Load – loading bytecodes into memory 4. Verify – confirm bytecode validity and that it is secure 5. Execute – program execution (cmd-line: java MyClass – don’t type the extension) 7 Environment It’s easier to use cmd-line tools with the environment variable PATH containing the dirs of java.exe and javac.exe files. Java interpreter uses CLASSPATH variable to look for .class files. I.e., it searches the subdirs with roots on the CLASSPATH. It can be just “.”, i.e. the current directory. 8 Type less or type more? // first program; surprisingly verbose syntax public class HiThere { public static void main(String[] args) // yep, THAT weird :-( { System.out.println("Welcome to Java"); } // end of method main } // end of class HiThere In Java, each function (method) belongs to a class! 9 Comments: like in C++ // single line comment /* will span until the closing part is found */ But you may see /** ...something... */ as well. Explanation later (tip: this is for javadoc). 10 Functions and classes in Java Functions are called methods. No “standalone” functions (as opposed to C++). Every function must belong to some class. Every program must have a class (at least one). Named like the program file (prev. example: file must be called HiThere.java). At least one method main in a program. 11 Identifiers Java is case-sensitive. Class names, variable names etc. cannot start with a digit or have spaces. Letters, _, digits (not as the 1st char), $ are OK in names. Common convention: MyClass, HiThere, but: int myHumbleVariable; int byte; /* ILLEGAL (byte is a reserved word (keyword)) */ Exercise. Which of the following are not valid identifiers? userName last name user_name user1.age $dots _comment_ 2ndName comment2 12 Printing on screen System.out.print("Hello "); or System.out.println("everybody"); Got the hang of it? Special chars (like in C etc.) \n, \t, \r (carriage return), \\, \" Since SDK 5.0 there is printf (C-like syntax). Sometimes it’s hard to live without printf. 13 Formatted output [ http://mcsp.wartburg.edu/zelle/python/ccsc-html/mgp00005.html ] No longer needed since J2SE 5.0 ! Use System.out.printf ("%10.2f", x); 14 Math ops – like in C (mostly) +, -, *, /, % And also: +=, /=, ++ (prefix and postfix variation) etc. etc. Relations: ==, !=, <= etc. (returns true or false) int a = 10; // assignment Ternary op (like in C), example: System.out.println(height>=185 ? "Tall" : height>=170 ? "Medium" : "Short"); 15 Java-specific math operators && and || are like in C; they use short-circuit (aka lazy) evaluation, e.g. boolean cond = false; int x = 4; if (cond && x > 5) ... // cond – false the whole expression is false // i.e. (x>5) will not be evaluated But & and | for booleans mean almost the same, except for full evaluation. Beware: in C/C++ the operators & and | are AND/OR on the bitwise level! In Java, bitwise &, | and ^ (xor) still exist though. E.g. int n = 10 & 6 | 5; // n==7 16 Java-specific math operators, cont’d Other bitwise ops: ~ (negation), << (shift left), >> (shift right), <<=, >>=, >>>, >>>= (no equivalence in C/C++) >>> is unsigned shift right: regardless of the sign, zeroes are inserted at the higher-order bits. But the signed right shift >> uses sign extension: if the value is positive, 0s are inserted at the higher-order bits; if the value is negative, 1s are inserted at the higher-order bits. Example: int a = -11; System.out.println(a >> 1); // -6 System.out.println(a >>> 1); // 2147483642 17 Shortcut assignment int total = 5; int current = 4; total *= current + 3; // what is the result? Java evaluates right before left of =. That is, total will become 5*7 = 35. 18 8 primitive data types char (single characters in Unicode, 2 bytes!, from '\u0000' to '\uffff') boolean (true or false; 1 byte) integer types (all signed): No unsigned byte (8 bits) types in Java! short (16 bits) int (32 bits) long (64 bits) floating point types: float (32 bits) double (64 bits) 19 Built-in data types, examples float x=3.5F, y=-5.92F, z; int n1 = 54; boolean trustworthy = false; char c = '\u1f00'; long theKeyToUniverse = 42353265264254219L; final double PI = 3.14; // keyword final means a constant! Printing variables: int x = 3; System.out.println("x is now " + x + ", isn't it?"); 20 Arrays (1) Indexes from 0. Same element type in a whole array. Stored in consecutive memory cells (hence O(1) access). Creating an array: int[] tab; // declare the array tab = new int[100]; // create the array OR you can do it in one step… int tab[] = new int[100]; int c[]; or int[] c; // ?? // both alternatives valid Create and initiate: No pointers in Java! int[] n = {10, 20, 30, 40, 50}; 21 Arrays (2) Arrays are objects! But of what class..? This is implicit (“hidden” to a programmer). E.g. the name of a 1-dim array of int’s is [I, the name of a 2-dim array of int’s is [[I, the name of a 1-dim array of double’s is [D etc. Notes: You cannot declare an array of a given size, e.g. int[5] tab; // compile-error! You cannot resize an array. 22 Arrays (3) ArrayName.length returns how many elements are in the array. So, n[n.length-1] = -10; will set the last cell of n to -10. Sum array elements idiom: int total = 0; // or maybe long needed? for (int i=0; i < n.length; i++) total += n[i]; What if reaching out of array bounds? E.g. int[] tab = { 1, 3, 5 }; System.out.println(tab[8]); // ?? 23 Arrays (4) Coping with array copying int[] a; int[] b = {5, 6, 7, 8, 9}; a = b; // WRONG ! Copied a reference, not the 5 elements of b Correct: a = new int[b.length]; for(int i=0; i < b.length; i++) a[i] = b[i]; There is a copy method in java.lang.System. Syntax: arraycopy(sourceArray, src_pos, destArray, dest_pos, length); Example: System.arraycopy(b, 0, a, 0, b.length); Exceptions possible: NullPointerException (if sourceArray or destArray null), IndexOutOfBoundsException (e.g. src_pos negative), or ArrayStoreException 24 (element type mismatch). Arrays (5) arraycopy demo [ http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html ] Output: caffein 25 Arrays (6) Methods can return an array. Example (from [Barteczko’04, vol. 1, p. 191]) int[] dblVal(int[] tab) { int[] output_arr = new int[tab.length]; for(int i=0; i<output_arr.length; i++) output_arr[i] = tab[i] * 2; return output_arr; } 26 Arrays (7) [ http://ww2.cs.fsu.edu/~pfenning ] Multi-dim arrays int[][] tab = new int[8][3]; // 8 rows, 3 columns int[][] c = { {5, 8, 3}, {1, 2, 9}, {7, 4, 2} }; // What is c[1][2] ? // What is c.length ? 27 Arrays (8) public static void main(String[] arg) { int[] w = { 2, 3, 4 }; int n = 3; int[][] m3 = new int[n][]; // row sizes - dynamic for(int i = 0; i < m3.length; i++){ m3[i] = new int[w[i]]; for (int j = 0; j < m3[i].length; j++) m3[i][j] = i + j; } for (int i = 0; i < m3.length; i++) { System.out.println("i-th row size: " + m3[i].length); String out = " "; for(int j = 0; j < m3[i].length; j++) out += " " + m3[i][j]; System.out.println(out); } } 28 Variable length argument lists (added in SDK 5.0) Up to v1.4, this was a feature from C/C++ missing in Java. Same notation used (ellipsis). Argument list: type ... identifier. The type can be anything, even an array. Each method can only have a single type as a variable argument and it must come last in the parameter list. 29 Varargs, example (based on [W. Clay Richardson et al., Professional Java, JDK 5 Edition, Wrox, 2005]) 30 Previous example, can we have int sum(int[]) signature and still use e.g. sum(5, 10, -30)? Answer: no, the compiler reports an error. You can use sum(new int[] {5, 10, -30}) instead. Actually, the ellipsis is just syntactic sugar for having the compiler create and initialize an array of same-typed values and pass that array’s reference to a method. When the ellipsis can be used? E.g., for computing the average of a list (of e.g. floats), concatenating a list of strings into a single string, finding the max/min values in lists of floats. http://today.java.net/pub/a/today/2004/04/19/varargs.html 31 Varargs, example with arrays (based on [W. Clay Richardson et al., Professional Java, JDK 5 Edition, Wrox, 2005]) 32 Other constructs from C/C++ Loops: for(exp1; exp2; exp3) while (expr) instr; do (inst) while (expr); Selection: switch (expr) { case var1: inst1; case var2: instr2; .... default: instr_def; } 33 Switch specifics The variable used in a switch statement can only be an integer value of up to 32 bits. I.e.: byte, short, int, or char. The value for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. You cannot list more than one value after a single case. 34 Not quite C/C++ constructs break and continue made more flexible. int i = 0, j = 0; A reasonable outerloop: // label compromise between while (i < 100) stiff break / continue { i++; in C/C++ while (true) and most flexible but { messy goto j++; (in many languages). if (i + j > 10) break outerloop; // escapes to (*) } } // (*) 35 Data conversion What is b: double b = 1 / 3; // ? Just like in C/C++: integer division, result: 0. To obtain 0.3333333... use 1.0 / 3.0. And now, what is c? int c = 1.0 / 3.0; Compile error. Java wants to make sure you know you’d lose fractional information. Solution: int c = (int)(1.0 / 3.0); 36 Type conversions (arithmetic) int i; int2int short sh; sh = 5; // OK; 5 is int but is constant and // is small enough (no information loss) i = sh; // expanding, ok sh = (short)i; // OK – with the explicit cast double d = 5.12; float2int i = d; // WRONG! Conversion must be explicit // but: i = (int)d; // OK. The fraction is cut off 37 Integer arithmetic Java performs integer arithmetic at the int level, so e.g. b+c, where b and c are of type short, returns an int. The sum must therefore be cast to a short before an assignment to a, because a is a short: short a, b, c; c = 21; b = 9; a = (short) (b + c); // without casting – a compile error Similar example: byte a=4, b=-1; short c = (short)(a+b); 38 What’s wrong with that? float width = 5.5; // compile error Compiler message: possible loss of precision found: double required: float So, you should’ve written float width = (float)5.5; // explicit cast or (more naturally) float width = 5.5F; // or ...5.5f 39 Methods (functions) Very much like in C/C++. Returned type declaration (possibly void), name, parameters... return keyword. Passing variables in Java always by value – a copy is made. No change of the variable in the called method affects its value when back in the caller. Aren’t some variables passed by reference though?? No. The reference’s (memory location’s) copy is passed to the second method. This works for objects (incl. arrays). 40 References Declaring an object is in fact only declaring a reference to it (no memory allocation for the object itself). This is different than with simple types (e.g. int)! Button b; // declaring a reference to a Button object b = new Button(); // now we create the object (Kind of) a special case: String objects. String s = "George Bush"; // !! What about String s = new String("George Bush"); // ?? It’s correct too, but it’s beating around the bush. 41 Little trap? String s1 = "abc"; String s2 = "ab"; s2 += "c"; boolean result = (s1==s2); // true? False. Different objects (i.e., their references point to different memory locations). Content irrelevant. How to compare content then? if (s1.equals(s2)) ... or if (s1.equalsIgnoreCase(s2)) ... String s1 = "abc"; String s2; s2 = s1; // copy? No, just another reference. Write s2 = new String(s1); if a copy needed. 42 Concatenating strings and numbers String s1 = "Johnny has drunk "; int count1 = 2, count2 = 1; String s2 = " beers."; String s3 = s1 + count1 + s2; String s4 = s1 + (count1 + count2) + s2; String s5 = s1 + count1 + count2 + s2; String s6 = count1 + count2 + s2; What do s3, s4, s5, s6 store? Remember: evaluation from left to right. 43 More on strings Lots of functionality in String class. See: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html A few examples: String c = "Abcde ".substring(2,4); if (c.startsWith("b")) System.err.println("What the hell?!"); c += " "; String d = c.trim(); // leading and trailing whitespace removed float f = 5.001f; String s = d.valueOf(f); // s.equals("5.001")==true now // valueOf is a static method from class String c = c.toUpperCase(); // what if we write just: c.toUpperCase(); ? 44 System.out.println(c.length()); More on strings String s = "Abcde ".substring(2,8); /* Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8 */ Maybe you meant String s = "Abcde ".substring(2, Math.min(8, "Abcde ".length())); String s = "abracadabra"; system.out.print(s.lastIndexOf("ab")); // 7 system.out.print(s.lastIndexOf("abb")); // -1, not found 45 Scanner class [ http://java.sun.com/javase/6/docs/api/java/util/Scanner.html ] Breaks its input into tokens using a delimiter pattern (by default: whitespace). Provides convenient nextXxxx() methods for type conversion. Example: Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) long aLong = sc.nextLong(); 46 Scanner example, data from the standard input [ http://www.cs.fit.edu/~mmahoney/cis5100/examples/ch02/ex02_06/Product.java ] 47 Scanner, various inputs are possible [ http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html ] 48 Command-line arguments Very similar to C/C++. But of course the arguments are not arrays of characters (char[]), but Strings. public class Demo01 { public static void main(String[] args) { System.out.println("no of arguments specified: " + args.length); System.out.println("Here go the args:"); for(int i=0; i<args.length; i++) System.out.println(args[i]); } } 49 Math class http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html sin, cos, tan, atan, asin, ... exp, log (base e), ceil, floor, sqrt, ... min, max (lesser or greater of a pair), pow(a, b), random() (from [0,1)) static double toDegrees(double angrad), static double toRadians(double angdeg) rint(double a) – returns the double value that is closest in value to arg. a and is equal to a mathematical integer. Rounding to an even, in case of a “tie”. Constants: PI, E 50 javadoc (1) Writing documentation to large software projects: both very tedious and very important. javadoc is a simple tool to fascilitate it. Just comment each (public) function in the classes and run javadoc – the whole documentation will be generated (as a set of html pages). Sun Microsystem’s on-line documentation for the standard Java API was produced using javadoc. The documentation for each item must be placed in a comment that precedes the item. (This is how javadoc knows which item the comment is for.) 51 javadoc (2) Javadoc documentation in /** ... */. Special notation allowed: @return, @param. /** * Return the real number represented by the string s, * or return Double. NaN if s does not represent a legal * real number. * * @param s String to interpret as real number. From http://www.faqs.org/ * @return the real number represented by s. docs/javap/ */ advanced.html public static double stringToReal(String s) { try { return Double.parseDouble(s); } catch (NumberFormatException e) { return Double.NaN; } } 52 Java vs. C++, main differences (summary) Removed in Java: • preprocessor (#define, #include etc.) • operator overloading • (explicit) pointers • typedef • standalone functions; global variables • multiple inheritance • non-virtual methods. Added in Java: • interfaces • garbage collector • array bound checking, strong typing • concurrency support. 53 Classes Class is an object type. Basic syntax similar to C++. class WackyWindow { ... // data & methods WackyWindow(int x, int y) // constructor { ... } } // no ; as opposed to C++ In Java, method bodies are inside the class. 54 Constructor (example based on [Barteczko’00]) class Pair { int a, b; Pair(int x, int y) { a=x; b=y; } void add(Pair p) { a+=p.a; b+=p.b; } } class Pair { int a, b; Pair(int x) // single param. { a=x; b=x; } } 55 Default (=no-arg) constructor class X { int i, j; void setState(int a, int b) { i = a; j = b; } void showState() { ... } } ... X x = new X(); // OK (default constructor launched) But if we had class X { ... X(int a, int b) { ... } // "standard" constructor } then X x = new X(); // compile error 56 Keyword this (only in methods) Pair add(Pair p) { a = a + p.a; b = b + p.b; return this; } ... p.add(p1); p.add(p2); p.add(p3); But you can also type p.add(p1).add(p2).add(p3); // ! Why? this – reference to the current object 57 this in a constructor class Date { int year, month, day; public Date(int d, int m, int y) // one constructor { day = d; month = m; year = y; } public Date(int y) { this(1, 1, y); } // another public Date( ) // yet another constructor { this(2008); } } Based on an example from http://www.cs.fiu.edu/~weiss/cop3338_f00/lectures/Objects/objects.pdf 58 this specifics 59 Static data, static methods static int n; // the field n belongs not to an individual object // but to the class // all class objects “see” the same value of n Static method – belongs to the class. It can access only static fields of the class. this not accessible. A static method cannot access non-static fields. Why? Since perhaps no object yet exists when we launch this method. (But a non-static method can invoke a static method, or access a static field.) 60 Static field and method, example class Pair { static int count = 0; Pair(int x, int y) { count++; a = x; b = y; } static void showCount() { System.out.println("No. of created pairs: "+count); } ... } Pair p1 = null, p2 = null; . . . . . . if (Pair.count == 0) Pair p1 = new Pair(1,1); else while (Pair.count < 10) { p2 = new Pair(2,2); p1.add(p2); } System.out.println(p1.count); Pair.showCount(); p1.showCount(); p2.showCount(); 61 We already used API static methods System.out.println(Math.sqrt(2)); /* OK, although no Math object created */ Can we also do it like that? Math m = new Math(); System.out.println(m.sqrt(2)); No. The Math constructor is private. 62 Hiding identifiers Class fields can be hidden: class A { int a; void method(){ int a = 0; a = a + 10; this.a++; } ... // local var. // local var. // field of the object You can’t do it in blocks: int a; { int a; } // COMPILE ERROR This is wrong too: int i = 0; for (int i = 0; i < 10; i++) { ... } 63 Method overloading • int Fun(int x) • int Fun(float y) • int Fun(int a, float b) All they can appear in one class. But not • int Fun(int x) and • boolean Fun(int y) 64 There is a time to live and a time to die Local variables and references “live” since their declaration until leaving the block they were declared in. Objects – since new operation until being removed by the garbage collector. class A { String s; void f1() { String dog = new String("Dog"); s = dog; } void f2(){ System.out.println(s + "exists."); } } 65 More on cleanup Two ways: finalization and garbage collection. From Eckel’s TIJ, 3rd ed., chapter 4: Java provides a method called finalize( ) that you can define for your class. Here’s how it’s supposed to work. When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the object’s memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection. But what for can we need finalize()? 66 Trap for C++ programmers GC or finalize() method are NOT equivalent to destroying an object (with the class destructor) in C++ ! The reason is, in C++ objects always get destroyed (and the programmer controls this moment) while in Java – not. (Perhaps an object will be destroyed, i.e. its storage will be garbage-collected (when? We don’t know), or perhaps not... – to save time.) 1. Your objects might not get garbage collected. 2. Garbage collection is not destruction. [ B.Eckel, Thinking in Java, 3rd ed., chapter 4 ] 67 So, what do we need finalize() for?? We may allocate space using native methods, i.e. calling non-Java code from Java. Example: allocate memory with C’s malloc(). Until free() called, storage will not be released. Of course, free() is a C and C++ function, so we need to call it in a native method inside our finalize(). But I won’t use that ugly C or C++ in my Java code! So, I will never need finalize(), right? Not quite true... 68 finalize(), interesting use [ B.Eckel, Thinking in Java ] Verification of the termination condition of an object. When we’re no longer interested in an object, it should be in a state whereby its memory can be safely released. E.g. the object is an open file, that file should be explicitly closed before the object is garbage collected. The value of finalize() is that it can be used to eventually discover this condition, even if it isn’t always called. If one of the finalizations happens to reveal the bug, then you discover the problem. 69 finalize(), interesting use, cont’d Code example (1/2) [ B.Eckel, Thinking in Java ] 70 finalize(), interesting use, cont’d Code example (2/2) [ B.Eckel, Thinking in Java ] 71 First GUI app import java.awt.*; class Hello { public static void main(String[] args) { Frame fr = new Frame("Window title"); Label lab = new Label("Hullo!"); Font font = new Font("TimesRoman", Font.ITALIC, 32); lab.setFont(font); lab.setBackground(Color.blue); lab.setForeground(Color.yellow); fr.add(lab); fr.pack(); fr.setVisible(true); } } 72