Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering

Similar presentations


Presentation on theme: "Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering"— Presentation transcript:

1 Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering umar.kalim@niit.edu.pk http://www.niit.edu.pk/~umarkalim 18/09/2007

2 Fall 2007cs4202 Agenda Review of Java Fundamentals Lecture slides prepared from CS193J Summer 2003 Stanford University

3 Fall 2007cs4203 Introduction to Java (Handout #2) The Java buzzword-bingo! –Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, high performance, multi-threaded, and dynamic language. Right Language, Right Time –Kept all the good features of C/C++ –Dumped a lot of the ugliness –Timing  Internet boom  Moore’s Law –Transistors per integrated circuit –Cost of computing –…

4 Fall 2007cs4204 The Java Virtual Machine The Java Language runs on a “Java Virtual Machine” –Java Virtual machine abstracts away the details of the underlying platform and provides a uniform environment for executing Java “byte-code” The Java compiler (javac) compiles Java code into byte- code –Bytecode is an intermediate form which can run on the JVM –JVM does the translation from byte-code to machine-code in a platform dependent way.

5 Fall 2007cs4205 Language + Libraries Core language –Ints, array, objects, loops and conditionals –Moderately sized language  Can run on small devices Libraries –This is where the power of Java really emerges  String, ArrayList, HashMap, String Tokenizer –Networking, Graphics, XML, Database connectivity, Web Services…. –Re-use at it’s best (so far).

6 Fall 2007cs4206 Simple Similar to C/C++ in syntax But eliminates several complexities of –No operator overloading –No direct pointer manipulation or pointer arithmetic –No multiple inheritance –No malloc() and free() – handles memory automatically –Garbage Collector Lots more things which make Java more attractive.

7 Fall 2007cs4207 Object-Oriented Fundamentally based on OOP –Classes and Objects –Uses a formal OOP type system –Lends an inherent structure/organization for how we write Java programs  Unlike spaghetti code in languages like Perl –Efficient re-use of packages such that the programmer only cares about the interface and not the implementation

8 Fall 2007cs4208 Robust / Secure / Safe Designed with the intention of being secure –No pointer arithmetic or memory management! –The JVM “verifier”  Checks integrity of byte-codes –Dynamic runtime checking for pointer and array access  No buffer overflow bugs! –SecurityManager to check which operations a piece of code is allowed to do –“Sandbox” operation for applets and other untrusted code  Limited set of operations or resources made available  Contrast to ActiveX

9 Fall 2007cs4209 Portable “Write-Once Run-Anywhere” The Java Virtual Machine becomes the common denominator –Bytecodes are common across all platforms –JVM hides the complexity of working on a particular platform  Difficult to implement a JVM  But simpler for the application developer Java does this well

10 Fall 2007cs42010 High-Performance Honestly – thanks to Moore’s Law Java performance IS slower than C  Tradeoff between development time vs. run time  Additional checks in Java which make is secure and robust and network aware etc, all have a small cost. BUT –JIT compilation and HotSpot  Dynamic compilation of bytecode to native code at runtime to improve performance –HotSpot optimizes code on the fly based on dynamic execution patterns  Can sometimes be even faster than compiled C code!

11 Fall 2007cs42011 Multi-Threaded Native support for threading –We will cover this in detail Basic concept –The ability to have multiple flows of control/programs which appear to run at the same time  Processes - application level  Threads – within the application –JVM uses native threads on operating system but provides a consistent abstraction for the developer.

12 Fall 2007cs42012 Dynamic Java is “self-aware” –Java code can look at itself and tell what interfaces it exports (Introspection) –Can dynamically load new classes/code at runtime

13 Fall 2007cs42013 Java Programmer Efficiency Faster Development –More programmer friendly –Less error prone OOP –Easier to manage large development projects Robust memory system –No pointer arithmetic and manual memory management. Garbage collector! Libraries –Re-use of code

14 Fall 2007cs42014 Microsoft vs. Java Java is platform independent –Was considered a threat to Microsoft’s dominance –Sun vs. Microsoft Law Suit Microsoft’s response to Java –C#  Very similar to Java in structure and style  Some improvements over Java (which have now emerged in Java 1.5/1.6)  Some debatable features ~ http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_a nd_Java#C.23 http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_a nd_Java#C.23

15 Fall 2007cs42015 Review of Java Fundamentals (we will not cover the following) Java Environment –Class Libraries, JDK directory structure Program Structure –Data, Variables, Operators, Precedence, Comments, Loops and Logic, Arrays and Strings, Array-String Operations Writing a Java Program –Editing, Compilation and Execution Object Oriented Programming –Objects, Classes, Interfaces, Messages and Methods, OOP Design, Constructors, Encapsulation, Inheritance, Overloading, Polymorphism, Packages, Abstract Classes Exceptions GUI & Multimedia –Creating Windows, Layouts Event Handling

16 Fall 2007cs42016 Review of Java Fundamentals (we will cover the following) Access control and modifiers Collections Streams and Serialization Threads

17 Fall 2007cs42017 Controlling Access to Members of a Class Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control: –At the top level—public, or package-private (no explicit modifier). –At the member level—public, private, protected, or package-private (no explicit modifier).

18 Fall 2007cs42018 ModifierClassPackageSubclassWorld publicYYYY protectedYYYN no modifierYYNN privateYNNN ModifierAlphaBetaAlphasubGamma publicYYYY protectedYYYN no modifierYYNN privateYNNN Visibility Access Levels

19 Fall 2007cs42019 Static Can have static –Instance variables –Methods Static variables and methods –Are associated with the class itself!! –Not associated with the object Therefore Statics can be accessed without instantiating an object!

20 Fall 2007cs42020 Static Variable Like a global variable –But on a class by class basis –Stored in the class Static variable occurs as a single copy in the class –Instance variables occur as multiple copies – one in each instance (object) Example –System.out is a static variable!

21 Fall 2007cs42021 Static Methods Like a “global function” –Again on a class by class basis No Receiver! –Since the static method is associated with the class, there is no object that is associated with it and therefore, no “receiver” –You can think of it as the class being the receiver. Example –System.arrayCopy() is a static method

22 Fall 2007cs42022 Static Fun Class: Student numStudents: 2 Methods: getNumStudents() Object: bart Type: Student Name: Bart Simpson Age: 10 Object: bart Type: Student Name: Bart Simpson Age: 10 Methods: eat(), run() walk() Object: lisa Type: Student Name: Lisa Simpson Age: 5 Methods: eat(), run() walk()

23 Fall 2007cs42023 Static Example public class Student { private int units; // Define a static int counter private static int count = 0; public Student(int init_units) { units = init_units; // Increment the counter count++; } public static int getCount() { // Clients invoke this method as Student.getCount(); // Does not execute against a receiver, so // there is no "units" to refer to here return(count); } // rest of the Student class... }

24 Fall 2007cs42024 Static Gotcha! Cannot refer to a non-static instance variable in a static method –There is no receiver (no object) –So the instance variable doesn’t exist! Example public static int getCount() { units = units + 1;// error }

25 Fall 2007cs42025 Using the final modifier final for members of a class final for classes

26 Fall 2007cs42026 Collections (Handout #7) Built-in support for collections –Similar to STL in C++ Collection type –Sequence/Set –Example ArrayList Map type –Hashtable/dictionary –Example HashMap Collections store pointers to objects! Read –http://java.sun.com/docs/books/tutorial/collectionshttp://java.sun.com/docs/books/tutorial/collections

27 Fall 2007cs42027 Collection Design All classes implement a similar interface –add(), size(), iterator()… –Easy learning curve for using Collections –Possible to swap out the underlying implementation without significant code change Implemented as pointer to Object –Similar to using a void * in C –Require a cast back to the actual type –Example  String element = (String)arraylist.get(i) Java checks all casts at run-time

28 Fall 2007cs42028 Collection Messages Basic messages –constructor()  Creates a collection with no elements –size()  Number of elements in the collection –boolean add()  Add a new pointer/element at the end of the collection  Returns true if the collection is modified. –iterator()  Returns an Iterator Object

29 Fall 2007cs42029 Additional Collection Messages Utilities –Additional useful methods –boolean isEmpty() –boolean contains(Object o)  Iterative search, uses equals() –boolean remove(Object o)  Iterative remove(), uses equals() –Boolean addAll(Collection c)

30 Fall 2007cs42030 Iterators Used to iterate through a collection –Abstracts away the underlying details of the implementation Responds to –hasNext() - Returns true if more elements –next() - Returns the next element –remove() - removes element returned by previous next() call.

31 Fall 2007cs42031 Working with Iterators Not valid to modify a collection directly while an iterator is being used! –Should not call collection.add() or collection.remove() OK to modify the collection using the iterator itself –iterator.remove() Why? –Motivation for concurrency issues later in the course

32 Fall 2007cs42032 ArrayList Most useful collection Replaces the “Vector” class Can grow over time Methods –add() –int size() –Object get(int index)  Index is from 0 to size() -1  Must cast to appropriate type when used. –iterator()  We’ll see an example!

33 Fall 2007cs42033 ArrayList Demo: constructor import java.util.*; /* The ArrayList is replaces the old Vector class. ArrayList implements the Collection interface, and also the more powerful List interface features as well. Main methods:add(), size(), get(i), iterator() See the "Collection" and "List" interfaces. */ public static void demoArrayList() { ArrayList strings = new ArrayList(); …

34 Fall 2007cs42034 ArrayList Demo: adding/size // add things... for (int i= 0; i<10; i++) { // Make a String object out of the int String numString = Integer.toString(i); strings.add(numString);// add pointer to collection } // access the length System.out.println("size:" + strings.size());

35 Fall 2007cs42035 ArrayList Demo: looping // ArrayList supports a for-loop access style... // (the more general Collection does not support this) for (int i=0; i<strings.size(); i++) { String string = (String) strings.get(i); // Note: cast the pointer to its actual class System.out.println(string); }

36 Fall 2007cs42036 ArrayList: iterating // ArrayList also supports the "iterator" style... Iterator it = strings.iterator(); while (it.hasNext()) { String string = (String) it.next(); // get and cast pointer System.out.println(string); } // Calling toString() System.out.println("to string:" + strings.toString());

37 Fall 2007cs42037 ArrayList Demo: removing // Iterate through and remove elements // get a new iterator (at the beginning again) it = strings.iterator(); while (it.hasNext()) { it.next();// get pointer to elem it.remove();// remove the above elem } System.out.println("size:" + strings.size()); }

38 Fall 2007cs42038 ArrayList Demo: output /* Output... size:10 0 1 2 3 4 5 6 7 8 9 to string:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] size:0 */

39 Fall 2007cs42039 Streams - Concept An abstract representation of input or output device, that is a source or destination of data

40 Fall 2007cs42040 Streams - Review Write data to a stream, the stream is called an output stream. Read data from an input stream. In principle, this can be any source of serial data. Reason for using a stream - To make the pro- gram code for read/write operations independent of the device involved

41 Fall 2007cs42041 Stream Review Stream input and output methods generally permit very small amounts of data –single character or byte Extremely inefficient! Hence notion of buffers ~ Buffered Stream Types of Streams –Binary Streams –Character Streams

42 Fall 2007cs42042 Relevant Classes ~ Binary Input 9 sub classes BufferedInputStream, DataInputStream, CheckedInputStream, CipherInputStream, ….

43 Fall 2007cs42043 Relevant Classes ~ Binary Output 7 sub classes BufferedOutputStream, ….

44 Fall 2007cs42044 Relevant Classes ~ Character Input

45 Fall 2007cs42045 Relevant Classes ~ Character Output

46 Fall 2007cs42046 File & Streams File object encapsulates a pathname or reference to what may or may not be a physical file or directory on your hard disk Not the physical file or directory itself!

47 Fall 2007cs42047 Channels

48 Fall 2007cs42048 Buffers and Channels A buffer just holds data in memory. –We load the data that we want to write to a file into a buffer using the buffer’s put() methods. –We use a buffer’s get() methods to retrieve data that has been read from a file –java.nio package We obtain a FileChannel object from a file stream object. –We use a FileChannel object to read and/or write a file using the read() and write() methods for the FileChannelobject –with a buffer or buffers as the source or destination of the data –java.nio.channels package

49 Fall 2007cs42049

50 Fall 2007cs42050

51 Fall 2007cs42051 Serialization The process of storing and retrieving objects in an external file is called serialization. –Serializing an object –Deserializing an object Writing objects and the fields they contain to a stream –this excludes static members  Have values assigned by default

52 Fall 2007cs42052 Relevant Classes

53 Fall 2007cs42053 ObjectOutputStream

54 Fall 2007cs42054 3 Conditions The class must be declared as public The class must implement the Serializable interface If the class has a direct or indirect base class that is not serializable, then –That base class must have a default constructor — that requires no arguments –The derived class must take care of transferring the base class data members to the stream

55 Fall 2007cs42055 writeObject() The call to writeObject() takes care of writing everything to the stream that is necessary to reconstitute the object later in a read operation. –This includes information about the class and all its  superclasses,  the contents and types of the data members of the class –This works even when the data members are themselves class objects  As long as they are objects of Serializable classes  Our writeObject() call will cause the writeObject() method for each object that is a data member to be called

56 Fall 2007cs42056 Implementing Serializable Interface

57 Fall 2007cs42057

58 Fall 2007cs42058 Writing Objects

59 Fall 2007cs42059

60 Fall 2007cs42060 Review ~ Conditions Each superclass that is not serializable must have a public default constructor—a constructor with no parameters. Class must be declared as implementing the Serializable interface Class must take responsibility for serializing and deserializing the fields for the super-classes that are not serializable.

61 Fall 2007cs42061 Transient Data Members Fields that are not serializable, or that you just don’t want to have written to the stream Will be null when read –Unless programmed otherwise

62 Fall 2007cs42062 Reading Objects

63 Fall 2007cs42063 Determining the Class of a Deserialized Object

64 Fall 2007cs42064 Serializing Classes Ourselves Must have the exact signature

65 Fall 2007cs42065 Challenges

66 Fall 2007cs42066 Resetting an Object Stream

67 Fall 2007cs42067 Summary & Questions? That’s all for today!


Download ppt "Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering"

Similar presentations


Ads by Google