Download Fundamentals

Document related concepts
no text concepts found
Transcript
Advanced Java Programming
Umar Kalim
Dept. of Communication Systems Engineering
[email protected]
http://www.niit.edu.pk/~umarkalim
18/09/2007
Fall 2007
cs420
1
Agenda
Review of Java Fundamentals
Lecture slides prepared from CS193J Summer
2003 Stanford University
Fall 2007
cs420
2
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
– …
Fall 2007
cs420
3
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 bytecode
– 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.
Fall 2007
cs420
4
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).
Fall 2007
cs420
5
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.
Fall 2007
cs420
6
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
Fall 2007
cs420
7
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
Fall 2007
cs420
8
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
Fall 2007
cs420
9
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!
Fall 2007
cs420
10
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.
Fall 2007
cs420
11
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
Fall 2007
cs420
12
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
Fall 2007
cs420
13
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
Fall 2007
cs420
14
Review of Java Fundamentals
(we will not cover the following)
 Java Environment
– Class Libraries, JDK directory
structure
 Object Oriented
Programming
– Objects, Classes, Interfaces,
Messages and Methods, OOP
Design, Constructors,
Encapsulation, Inheritance,
Overloading, Polymorphism,
Packages, Abstract Classes
 Program Structure
– Data, Variables, Operators,
Precedence, Comments, Loops
and Logic, Arrays and Strings,
Array-String Operations
 Writing a Java Program
– Editing, Compilation and
Execution
Fall 2007
 Exceptions
 GUI & Multimedia
– Creating Windows, Layouts
Event Handling
cs420
15
Review of Java Fundamentals
(we will cover the following)
Access control and modifiers
Collections
Streams and Serialization
Threads
Fall 2007
cs420
16
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).
Fall 2007
cs420
17
Access Levels
Modifier
Class
Package
Subclass
World
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier
Y
Y
N
N
private
Y
N
N
N
Visibility
Fall 2007
Modifier
Alpha
Beta
Alphasub
Gamma
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier
Y
Y
N
N
private
Y
N
N
N
cs420
18
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!
Fall 2007
cs420
19
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!
Fall 2007
cs420
20
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
Fall 2007
cs420
21
Static Fun
Object: bart
Object:
bart
Type: Student
Type: Student
Name:
Bart Simpson
Name: Bart
Simpson
Age:
10
Age:
10 run() walk()
Methods:
eat(),
Class: Student
numStudents: 2
Methods: getNumStudents()
Fall 2007
Object: lisa
Type: Student
Name: Lisa Simpson
Age: 5
Methods: eat(), run() walk()
cs420
22
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
...
}
Fall 2007
cs420
23
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
}
Fall 2007
cs420
24
Using the final modifier
final for members of a class
final for classes
Fall 2007
cs420
25
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/collections
Fall 2007
cs420
26
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
Fall 2007
cs420
27
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
Fall 2007
cs420
28
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)
Fall 2007
cs420
29
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.
Fall 2007
cs420
30
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
Fall 2007
cs420
31
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!
Fall 2007
cs420
32
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();
…
Fall 2007
cs420
33
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());
Fall 2007
cs420
34
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);
}
Fall 2007
cs420
35
ArrayList: iterating
// ArrayList also supports the "iterator" style...
Iterator it = strings.iterator();
while (it.hasNext()) {
String string = (String) it.next();
pointer
System.out.println(string);
}
// get and cast
// Calling toString()
System.out.println("to string:" + strings.toString());
Fall 2007
cs420
36
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());
}
Fall 2007
cs420
37
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
*/
Fall 2007
cs420
38
Streams - Concept
An abstract representation of input or output
device, that is a source or destination of data
Fall 2007
cs420
39
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 program code for read/write operations
independent of the device involved
Fall 2007
cs420
40
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
Fall 2007
cs420
41
Relevant Classes ~ Binary Input
9 sub classes
BufferedInputStream,
DataInputStream,
CheckedInputStream,
CipherInputStream,
….
Fall 2007
cs420
42
Relevant Classes ~ Binary Output
7 sub classes
BufferedOutputStream,
….
Fall 2007
cs420
43
Relevant Classes ~ Character Input
Fall 2007
cs420
44
Relevant Classes ~ Character Output
Fall 2007
cs420
45
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!
Fall 2007
cs420
46
Channels
Fall 2007
cs420
47
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
Fall 2007
cs420
48
Fall 2007
cs420
49
Fall 2007
cs420
50
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
Fall 2007
cs420
51
Relevant Classes
Fall 2007
cs420
52
ObjectOutputStream
Fall 2007
cs420
53
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
Fall 2007
cs420
54
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
Fall 2007
cs420
55
Implementing Serializable Interface
Fall 2007
cs420
56
Fall 2007
cs420
57
Writing Objects
Fall 2007
cs420
58
Fall 2007
cs420
59
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.
Fall 2007
cs420
60
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
Fall 2007
cs420
61
Reading Objects
Fall 2007
cs420
62
Determining the Class of a Deserialized Object
Fall 2007
cs420
63
Serializing Classes Ourselves
Must have the exact signature
Fall 2007
cs420
64
Challenges
Fall 2007
cs420
65
Resetting an Object Stream
Fall 2007
cs420
66
Summary &
Questions?
That’s all for today!
Fall 2007
cs420
67