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
Advanced Programming Rabie A. Ramadan [email protected] http://www.rabieramadan.org/classes/2014/Ad vPro/ Lecture 1 Welcome Back 2 Class Organization Attendance is very important Assignments Projects Quizzes 3 Textbooks 4 Topics to be Covered Object Serialization Advanced I/O - New I/O Reflection Advanced JDBC Networking with Sockets Remote Method Invocation Keys, Signatures, and Certificates Java Authentication and Authorization Service (JAAS) Parsing XML with Java - JAXP Java Design Patterns Effective Java topics 5 Class Format Some presentations by myself Presentations by you Report discussion biweekly Labs 6 Grading Midterm grades will be added towards the project Labs Assignments 7 Agenda Introduction and Course Motivation Project Assignment 1 – Get your hands dirty 8 Introduction and Course Motivation Computer Programming is the art of making a computer do what you want it to do. 9 Terminology API – Application Programming Interface • Classes, Interfaces, Constructors, Members, and Serialized Forms By Which a Programmer Accesses a Class, Interface, or Package User Client • A Programmer Who Writes a Program That Uses an API • A Class Whose Implementation Uses an API Key Principles For Using Any Language Focus on Clarity and Simplicity Don’t Surprise Users of an API • Hide Complexity Underneath, Not In, The API Reuse Rather Than Copy Minimize Dependencies Between Modules • Some Early Habits Need to Be Broken Detect Errors As Soon As Possible • Compile-Time Detection Beats Run-Time Failure • Run-Time Exceptions Beat Undefined Behavior Performance Bloch Does not Focus on Performance • Instead, Strive to Write Programs that are: • Clear, Correct, Robust, Flexible, Maintainable Start With Sound Software Engineering Excessive Performance Focus Has Real Costs • Get Performance Later Where You Need It • Think About Why a Language Like C++ is so Complex Who are You ? • • Just a coder Most of us are coders not programmers Programmer / Developer Writes an efficient code 13 Project Project 14 Assignment 1 Available on the website 15 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented: • Structured in terms of classes, which group data with operations on that data • Can construct new classes by extending existing ones Java designed as • A core language plus • A rich collection of commonly available packages Java can be embedded in Web pages 16 Java Processing and Execution Begin with Java source code in text files: Model.java A Java source code compiler produces Java byte code • Outputs one file per class: Model.class • May be standalone or part of an IDE A Java Virtual Machine loads and executes class files • May compile them to native code (e.g., x86) internally Appendix A: Introduction to Java 17 Compiling and Executing a Java Program Appendix A: Introduction to Java 18 Java: Write Once, Run Anywhere Consequence of Java’s history: platformindependence Click on link to Applet Mac user running Safari Web page stored on Unix server Virtual machine translates byte code to native Mac code and the Applet is run Byte code is downloaded Windows user running Internet Explorer Byte code (part of web page) Java: Write Once, Run Anywhere Consequence of Java’s history: platform-independent Mac user running Safari Web page stored on Unix server Click on link to Applet Byte code is downloaded Windows user running Internet Explorer Virtual machine translates byte code to native Windows code and the Applet is run Java: Write Once, Run Anywhere (2) But Java can also create standard (nonweb based) programs Dungeon Master (Java version) Kung Fu Panda 2: THQ http://homepage.mac.com/aberfield/dmj/ Examples of mobile Java games: http://www.mobilegamesarena.net Java: Write Once, Run Anywhere (3) Java has been used by large and reputable companies to create serious stand-alone applications. Example: • Eclipse1: started as a programming environment created by IBM for developing Java programs. The program Eclipse was itself written in Java. 1 For more information: http://www.eclipse.org/downloads/ Compiled Programs With Different Operating Systems Windows compiler Executable (Windows) Computer program Mac OS compiler Executable (Mac) UNIX compiler Executable (UNIX) A High Level View Of Translating/Executing Java Programs Stage 1: Compilation Filename.java Java program Java compiler (javac) Filename.class Java bytecode (generic binary) A High Level View Of Translating/Executing Java Programs (2) Stage 2: Interpreting and executing the byte code Filename.class Java bytecode (generic binary) Java interpreter (java) Machine language instruction (UNIX) Machine language instruction (Windows) Machine language instruction (Apple) Classes and Objects The class is the unit of programming A Java program is a collection of classes • Each class definition (usually) in its own .java file • The file name must match the class name A class describes objects (instances) • Describes their common characteristics: is a blueprint • Thus all the instances have these same characteristics These characteristics are: • Data fields for each object • Methods (operations) that do work on the objects Appendix A: Introduction to Java 26 Grouping Classes: The Java API API = Application Programming Interface Java = small core + extensive collection of packages A package consists of some related Java classes: • Swing: a GUI (graphical user interface) package • AWT: Application Window Toolkit (more GUI) • util: utility data structures The import statement tells the compiler to make available classes and methods of another package A main method indicates where to begin executing a class (if it is designed to be run as a program) 27 A Little Example of import and main import javax.swing.*; // all classes from javax.swing public class HelloWorld { // starts a class public static void main (String[] args) { // starts a main method // in: array of String; out: none (void) } } public = can be seen from any package static = not “part of” an object 28 Processing and Running HelloWorld javac HelloWorld.java java HelloWorld • Produces HelloWorld.class (byte code) • Starts the JVM and runs the main method 29 References and Primitive Data Types Java distinguishes two kinds of entities Primitive-type data is stored in primitivetype variables Reference variables store the address of an object • Primitive types • Objects 30 Primitive Data Types Represent numbers, characters, boolean values Integers: byte, short, int, and long Real numbers: float and double Characters: char 31 Primitive Data Types Data type Range of values byte -128 .. 127 (8 bits) short -32,768 .. 32,767 (16 bits) int -2,147,483,648 .. 2,147,483,647 (32 bits) long -9,223,372,036,854,775,808 .. ... (64 bits) float +/-10-38 to +/-10+38 and 0, about 6 digits precision double +/-10-308 to +/-10+308 and 0, about 15 digits precision char Unicode characters (generally 16 bits per char) boolean True or false 32 Operators 1. 2. 3. 4. 5. 6. 7. 8. 9. subscript [ ], call ( ), member access . pre/post-increment ++ --, boolean complement !, bitwise complement ~, unary + -, type cast (type), object creation new * / % binary + - (+ also concatenates strings) signed shift << >>, unsigned shift >>> comparison < <= > >=, class test instanceof equality comparison == != bitwise and & bitwise or | 33 Operators (sequential) and && 12. logical (sequential) or || 13. conditional cond ? true-expr : false-expr 14. assignment =, compound assignment += -= *= /= <<= >>= >>>= &= |= 11. logical 34 Type Compatibility and Conversion Widening conversion: • In operations on mixed-type operands, the numeric type of the smaller range is converted to the numeric type of the larger range • In an assignment, a numeric type of smaller range can be assigned to a numeric type of larger range byte to short to int to long int kind to float to double 35 Declaring and Setting Variables int square; square = n * n; double cube = n * (double)square; • Can generally declare local variables where • they are initialized All variables get a safe initial value anyway (zero/null) 36 Java Control Statements A group of statements executed in order is written •{ stmt1; stmt2; ...; stmtN; } The statements execute in the order 1, 2, ..., N 37 Java Control Statements (continued) Appendix A: Introduction to Java 38 Java Control Statements (continued) 39 Methods A Java method defines a group of statements as performing a particular operation static indicates a static or class method A method that is not static is an instance method All method arguments are call-by-value • Primitive type: value is passed to the method • Method may modify local copy but will not affect caller’s value • Object reference: address of object is passed • Change to reference variable does not affect caller • But operations can affect the object, visible to caller 40 The String Class The String class defines a data type that is used to store a sequence of characters You cannot modify a String object • If you attempt to do so, Java will create a new object that contains the modified character sequence Appendix A: Introduction to Java 41 Comparing Objects You can’t use the relational or equality operators to compare the values stored in strings (or other objects) (You will compare the pointers, not the objects!) 42 The StringBuffer Class Stores character sequences Unlike a String object, you can change the contents of a StringBuffer object Appendix A: Introduction to Java 43 StringTokenizer Class We often need to process individual pieces, or tokens, of a String 44 Arrays In Java, an array is also an object The elements are indexes and are referenced using the form arrayvar[subscript] 45 Array Example float grades[] = new float[numStudents]; ... grades[student] = something; ... float total = 0.0; for (int i = 0; i < grades.length; ++i) { total += grades[i]; } System.out.printf(“Average = %6.2f%n”, total / numStudents); 46 Array Example Variations // possibly more efficient for (int i = grades.length; --i >= 0; ) { total += grades[i]; } // uses Java 5.0 “for each” looping for (float grade : grades) { total += grade; } 47 Input/Output using Streams An InputStream is a sequence of characters representing program input data An OutputStream is a sequence of characters representing program output The console keyboard stream is System.in The console window is associated with System.out 48 Opening and Using Files: Reading Input import java.io.*; public static void main (String[] args) { // open an input stream (**exceptions!) BufferedReader rdr = new BufferedReader( new FileReader(args[0])); // read a line of input String line = rdr.readLine(); // see if at end of file if (line == null) { ... } 49 Item 1: Consider Static Factory Methods Instead of Constructors Factory methods: • Have names, unlike constructors, which can clarify code. • Do not need to create a new object upon each invocation • objects can be cached and reused, if necessary. Can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller. Item 1: Consider Static Factory Methods Instead of Constructors Constructor Calls vs Static Factory Method Item 1: Advantages Unlike constructors, static factory methods • Can have meaningful names • Need not create new instances • Can return any subtype of return type • Reduces client dependency on specific class • Can reduce verbosity of creating parameterized type instances Advantage 2: Not Required To Create New Object Instance-controlled classes can be useful • Can avoid creating unnecessary duplicate objects • Boolean.valueOf(boolean) is an example • Can guarantee a “singleton” or “noninstatiable” object • Can allow for very fast “equals” test Advantage 3: Can Return Subtype of Return Type Consider the java.util.Collections class • 32 Convenience implementations of Collection interfaces • All are static factory methods • Interface return type vs. actual classes Static factory methods can hide multiple implementations •java.util.EnumSet has two implementations • Future release could easily change this • Clients neither know nor care about actual type • Reduce client dependencies! Advantage 4: Reduce Verbosity of Parameterized Type Instances // Parameterized type instances Map<String, List<String>> m = new HashMap<String, List<String>>(); vs. // Static factory alternative public static <K, V> HashMap<K, V> newInstance() { return new HashMap<K, V>(); } // Now, client code looks like this // Compiler does type inference! Map<String, List<String>> m = HashMap.newInstance(); Item 1: Disadvantages of Static Factory Methods Naming conventions necessary •valueOf – effectively a type converter (also just of) •getInstance – return instance described by parameters •newInstance – like getInstance, but guarantees distinct object •getType – like getInstance, but converts type •newType – like newInstance, but converts type Item 3: Enforce Singleton Property A Singleton is a class that’s instantiated exactly once • Note: singletons are hard to mock in unit testing Two approaches before Enums: Enum singleton is now preferred • Public static member (a constant, of course) • Public static factory method • Lots of subtle advantages: security, serialization, etc. Item 3: Code Example // Option 1: public final field public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() {...} } // Option 2: static factory method public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() {...} public static Elvis getInstance() { return INSTANCE; } } // Option 3: Enum type – now the preferred approach public enum Elvis { INSTANCE; ... } Item 4: Enforce Noninstantiability With a Private Constructor Some classes just group static methods and/or fields Trying to enforce noninstantiability by making class abstract doesn’t work • Makes no sense to instantiate such a class • Subclassing is possible • Clients are led to believe subclassing makes sense However, a private constructor does the job Item 4: Code Example // Noninstantiable utility class public class UtilityClass { // Suppress default constructor for noninstantiability private UtilityClass() { throw new AssertionError(); } ... // Remainder of class omitted } // // // // Note that no subclassing is possible (constructor chaining...) Note that client can’t call constructor Note that if constructor is mistakenly called inside class, there is an immediate assertion violation. Item 5: Avoid Creating Unnecessary Objects On the one hand, performance is a secondary concern behind correctness On the other, gratuitous object creation is just bad programming // String s = new String(“stringette”); // Don’t do this! vs. // String s = “stringette”; // Let JVM optimize for you // Also see earlier Boolean.valueOf() static factory example Item 5: Code Example public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted // DON’T DO THIS public boolean isBabyBoomer() { // Unnecessary allocation of expensive object Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomStart = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomEnd = gmtCal.getTime(); return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0; } } Item 5: Code Example Fixed public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted private static final Date BOOM_START; private static final Date BOOM_END; static { // Note static block Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); BOOM_START = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); BOOM_END = gmtCal.getTime(); } public boolean isBabyBoomer() { return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0; } } Item 5: Autoboxing Overhead // Hideously slow program! Can you spot the object creation? public static void main(String[] args) { Long sum = 0L; for (long i =0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); } // Lessons: 1) prefer primitives to Boxed primitives // 2) watch for unintentional autoboxing // why are you using classes where there is no need for them? Item 6: Eliminate Obsolete Object References Sometimes, you manage your own memory (leak) • Example: Stack.java public Object pop () { if (size == 0) throw new IllegalStateException("Stack.pop"); Object result = elements[--size]; elements[size] = null; // Eliminate obsolete reference return result; } Also a problem with caches and registration of listeners and callbacks • Suggestion: Use weak pointers, such as WeakHashMap Item 7: Avoid Finalizers finalize() is a method in the Object class • What the garbage collector may call when cleaning up an unused object Finalizers: unpredictable, dangerous, unnecessary! There is no guarantee a finalizer will ever be called Finalizers have severe performance penalties Instead, provide explicit termination methods • They are NOT the analog of C++ destructors • Sometimes requires “finalizer chaining” Item 7: Code Example // try-finally block guarantees execution of termination method // termination method ensures resources are released // Example resources: database connections, threads, windows Foo foo = new Foo(); try { // Do what must be done with foo } finally { foo.terminate(); // Explicit termination method in Foo } Item 7: Finalizer chaining // Manual finalizer chaining // Only do this if you *have* to use the finalizer @Override protected void finalize() throws Throwable { try { .. . // Finalize subclass state } finally super.finalize(); // Note order of finalizer chaining } }