Upload
lora-atkinson
View
216
Download
0
Embed Size (px)
DESCRIPTION
Institute for Visualization and Perception Research 3 © Copyright 1998 Haim Levkowitz Creating objects new class (arg list) java.awt.Button b = new java.awt.Button(); ComplexNumber c = new ComplexNumber(1.0, 1.414); 2. String s = " This is a string"; 3. newInstance() method of a Class object generally only dynamically loading classes
Citation preview
Institute for Visualization and Perception ResearchI VPR 1
© Copyright 1998 Haim Levkowitz
Reference type summary ...• All object & arrays are handled by reference
• = and == op's assign & test ref's to objects• clone() and equals() copy or test objects themselves• Necessary ref'ing and deref'ing of objects and arrays
handled automatically• Ref type can never be cast to primitive type• Primitive type can never be cast to ref type• No pointer arithmetic• No sizeof operator• null is special value, means "no object" or indicates
absence of reference
Institute for Visualization and Perception ResearchI VPR 2
© Copyright 1998 Haim Levkowitz
Objects ...
• Creating objects ...• Accessing objects ...• Garbage collection ...
Institute for Visualization and Perception ResearchI VPR 3
© Copyright 1998 Haim Levkowitz
Creating objects ...
• 1. new class (arg list)• java.awt.Button b = new java.awt.Button();• ComplexNumber c = new ComplexNumber(1.0,
1.414);• 2. String s = " This is a string";• 3. newInstance() method of a Class object
• generally only dynamically loading classes
Institute for Visualization and Perception ResearchI VPR 4
© Copyright 1998 Haim Levkowitz
Accessing objects ...• ComplexNumber c = new ComplexNumber();• c.x = 1.0;• c.y = 1.414;• By ref ==> dot in Java more like -> in C• Object's methods as if fields in the object
• ComplexNumber c = new ComplexNumber(1.0, 1.414);
• double magnitude = c.magnitude();
Institute for Visualization and Perception ResearchI VPR 5
© Copyright 1998 Haim Levkowitz
Garbage collection ...
• Automatic• When no longer referred to
Institute for Visualization and Perception ResearchI VPR 6
© Copyright 1998 Haim Levkowitz
Arrays ...• Same as reference type an object,
mostly ...• Creating and destroying arrays ...• Multidimensional arrays ...• Accessing array elements ...• Are arrays objects? ...• Declaring array variables and arguments ...
Institute for Visualization and Perception ResearchI VPR 7
© Copyright 1998 Haim Levkowitz
Same as reference type an object, mostly ...• Manipulated by reference• Dynamically created with new• Automatically garbage collected when
no longer referred to
Institute for Visualization and Perception ResearchI VPR 8
© Copyright 1998 Haim Levkowitz
Creating and destroying arrays ...• 1. w / new, specify how large ...• 2. Static initializer (looks like C) ...
Institute for Visualization and Perception ResearchI VPR 9
© Copyright 1998 Haim Levkowitz
1. w / new, specify how large ...• byte octet_buffer[] = new byte[1024];• Button buttons[] = new Button[10];• Doesn't create object stored in array
• ==> No constructor to call• No arg list• Elements initialized to default of type
Institute for Visualization and Perception ResearchI VPR 10
© Copyright 1998 Haim Levkowitz
2. Static initializer (looks like C) ...• int lookup_table[] = {1, 2, 4, 8, 16, 32, 64,
128};• Dynamically create array• Initialize elements to specified values• Elements my be arbitrary expressions
(diff from C, where must be constant expressions)
Institute for Visualization and Perception ResearchI VPR 11
© Copyright 1998 Haim Levkowitz
Multidimensional arrays ...
• Arrays-of-arrays• byte TwoDimArray[][] = new byte[256]
[16]; ...• Nested initializers• Need not be rectangular ...
Institute for Visualization and Perception ResearchI VPR 12
© Copyright 1998 Haim Levkowitz
byte TwoDimArray[][] = new byte[256][16]; ...• 1. Declare var name TwoDimArray; type byte[][]• 2. Dynamically allocate array w/256 elements. Each
element is single-dim array of byte• 3. Dynamically allocate 256 arrays of byte, 16 bytes
ea. • 4. Store ref to array in 256 element array. • 5. Init values to default, 0• Don't have to spec number of elements in all ...
Institute for Visualization and Perception ResearchI VPR 13
© Copyright 1998 Haim Levkowitz
Don't have to spec number of elements in all ...• byte ThreeDimArray[][][] = new
byte[256][][]; // legal• byte ThreeDimArray[][][] = new
byte[256][16][]; // legal• byte ThreeDimArray[][][] = new
byte[256][][16]; // illegal
Institute for Visualization and Perception ResearchI VPR 14
© Copyright 1998 Haim Levkowitz
Need not be rectangular ...e.g., triangularshort triangle[][] = new short[10][]; // 1-D arrayfor (int i = 0; i < triangle.length; i++) { // for ea. elem.
triangle[i] = new short[i + 1]; // new arrayfor (int j = 0; j < i + 1; j++) // for ea. elem. of new
triangle[i][j] = i + j; // init to value}
Institute for Visualization and Perception ResearchI VPR 15
© Copyright 1998 Haim Levkowitz
Accessing array elements ...• int a[] = new int[100];• a[0] = 0;• for (int i = 1; i < a.length; i++) a[i] = i + a[i - 1];• length: only field arrays support
• read-only• If index out of bounds ==>
ArrayIndexOutOfBoundsException
Institute for Visualization and Perception ResearchI VPR 16
© Copyright 1998 Haim Levkowitz
Are arrays objects? ...• Yes ...
• Object syntax .length• May be assigned to var's of type Object• Methods of Object class may be invoked for arrays
• ... and no• Special syntax• ==> Useful to consider them diff
Institute for Visualization and Perception ResearchI VPR 17
© Copyright 1998 Haim Levkowitz
Declaring array variables and arguments ...• C style ...• Array bracket after type name ...• Can mix styles• Size not part of type• ==> Can declare var of type String[]• Assign array of String object to it,
regardless of length
Institute for Visualization and Perception ResearchI VPR 18
© Copyright 1998 Haim Levkowitz
C style ...
• void reverse(char strbuff[], int buffer_size) {• char buffer[500];• ...
• }• Have to declare buffer as array variable• Allocate array with new
Institute for Visualization and Perception ResearchI VPR 19
© Copyright 1998 Haim Levkowitz
Array bracket after type name ...• void reverse(char[] strbuf, int
buffer_size) {• char[] buffer = new char[500];• ...
• }• Easier to read, understand
Institute for Visualization and Perception ResearchI VPR 20
© Copyright 1998 Haim Levkowitz
Strings ...• NOT null-terminated array of characters• Almost primitive types (for compiler) …• Immutable …• Impossible to examine value of terminator
after last char of string• java.lang Package ...
Institute for Visualization and Perception ResearchI VPR 21
© Copyright 1998 Haim Levkowitz
Almost primitive types (for compiler) ...• E.g., auto create String objects when
encounter double-quoted constant• Language defined operator on String
objects: + for string concatenation
Institute for Visualization and Perception ResearchI VPR 22
© Copyright 1998 Haim Levkowitz
Immutable ...• No method to change contents of String• To modify contents
• Create StringBuffer from String object• Modify StringBuffer contents• Create new String from StringBuffer
contents
Institute for Visualization and Perception ResearchI VPR 23
© Copyright 1998 Haim Levkowitz
java.lang Package ...
• Classes • E.g., String, StringBuffer
• and methods• E.g., length(), charAt(), equals(),
compareTo(), indexOf(), astIndexOf(), substring()
Institute for Visualization and Perception ResearchI VPR 24
© Copyright 1998 Haim Levkowitz
Operators ...
• Almost all standard C operators• Differences …• New operators ...
Institute for Visualization and Perception ResearchI VPR 25
© Copyright 1998 Haim Levkowitz
Differences ...
• No comma op to combine 2 expr'ns into 1• for statement simulates
• No *, &, sizeof• [ ] (array access), . (field access) not
considered operators
Institute for Visualization and Perception ResearchI VPR 26
© Copyright 1998 Haim Levkowitz
New operators ...
• + applied to String values ...• instanceof ...• >>> ...• & and | …
Institute for Visualization and Perception ResearchI VPR 27
© Copyright 1998 Haim Levkowitz
+ applied to String values ...• Concatenate them• If only one operand String, convert other• Automatic for primitive types• By calling toString() for non-primitive• Same precedence• += as expected for String values
Institute for Visualization and Perception ResearchI VPR 28
© Copyright 1998 Haim Levkowitz
instanceof ...
• Return true if object on LHS is instance of class on RHS, or implements interface
• Return false if not, or if spec'd object is null
• Same precedence as <, <=, >, >=
Institute for Visualization and Perception ResearchI VPR 29
© Copyright 1998 Haim Levkowitz
>>> ...
• All integral types signed ==> >> right shift w / sign extension
• >>> Treat value to be shifted as unsigned number
• Shift bits right with 0 extension• >>>= as expected
Institute for Visualization and Perception ResearchI VPR 30
© Copyright 1998 Haim Levkowitz
& and | ...• Applied to integral types
• Bitwise AND and OR• Applied to boolean types
• Logical AND and OR• Always evaluate both operands
• Even when result determined by LHS• Useful for side effects in expressions to occur
• "Short-circuited" && and ||• &=, |= as expected
Institute for Visualization and Perception ResearchI VPR 31
© Copyright 1998 Haim Levkowitz
Statements ...• The if/else, while, and do/while statements ...• The switch statement
• Same as in C• The for loop ...• Labeled break and continue statements
• Without labels: same as C• Labeled ...
• No goto statement ...• The synchronized statement ...• The package and import statements ...
Institute for Visualization and Perception ResearchI VPR 32
© Copyright 1998 Haim Levkowitz
The if/else, while, and do/while statements ...• Boolean type cannot be cast to other
types• 0, null not same as false• non-0, non-null not same as true• ==> Conditional must be boolean
• e.g., while (i--) --> while (i-- > 0)
Institute for Visualization and Perception ResearchI VPR 33
© Copyright 1998 Haim Levkowitz
The for loop ...
• Multiple comma-separated expressions ...
• Declare local loop var's in initialization (C++) ...
Institute for Visualization and Perception ResearchI VPR 34
© Copyright 1998 Haim Levkowitz
Multiple comma-separated expressions ...• Only in initialization, increment section• Not in test section
Institute for Visualization and Perception ResearchI VPR 35
© Copyright 1998 Haim Levkowitz
Declare local loop var's in initialization (C++) ...• for (int i = 0; i < my_array.length; i++)
• System.out.println("a[" + i + "] = " + my_array[i]);
• Var's declared so have for loop as scope
• ==> no effect on var's w / same name outside
Institute for Visualization and Perception ResearchI VPR 36
© Copyright 1998 Haim Levkowitz
Labeled …
• break …• continue ...
Institute for Visualization and Perception ResearchI VPR 37
© Copyright 1998 Haim Levkowitz
break ...
• Without label: terminate nearest enclosing for, while, do or switch
• Followed by label of enclosing statement: control xfer'd out of that statement
• Any req'd finally clauses executed• E.g., ...
Institute for Visualization and Perception ResearchI VPR 38
© Copyright 1998 Haim Levkowitz
E.g., ...test: if (check(i)) {
try {for (int j = 0; j < 10; j++) {
if (j > i) break; // terminate this loopif (a{i][j] == null)
break test; // do the finally clause and} // terminate the if statement
}finally { cleanup(a, i, j); }
}
Institute for Visualization and Perception ResearchI VPR 39
© Copyright 1998 Haim Levkowitz
continue ...
• Without label: stops iteration in progress ...
• Followed by label of enclosing loop ...
Institute for Visualization and Perception ResearchI VPR 40
© Copyright 1998 Haim Levkowitz
Without label: stops iteration in progress ...• Resume execution after last statement
in while, do, for loop, just before loop iteration to begin again
Institute for Visualization and Perception ResearchI VPR 41
© Copyright 1998 Haim Levkowitz
Followed by label of enclosing loop ...• skip execution to end of spec'd loop• finally clauses executed• E.g., ...
Institute for Visualization and Perception ResearchI VPR 42
© Copyright 1998 Haim Levkowitz
E.g., ...
big_loop: while(!done) {if (test(a, b) == 0) continue // control goes to pt. 2try {
for (int i = 0; i < 10; i++) {if (b[i] == null)
continue; // control goes to pt. 1else if (b[i] == null)
continue big_loop; // control goes to pt. 2// after doing the finally block
doit(a[i], b[i]);// pt. 1. Increment and start loop again with
test}
}finally { cleanup(a, b); }
// pt. 2. Start loop again with the (!done) test
}
Institute for Visualization and Perception ResearchI VPR 43
© Copyright 1998 Haim Levkowitz
No goto statement ...
• Reserved word, but not currently part of the language
• Labelled break, continue replace some uses
• try / catch / finally replace others
Institute for Visualization and Perception ResearchI VPR 44
© Copyright 1998 Haim Levkowitz
The synchronized statement ...• Multithreaded ==> prevent corruption from
multiple modification• Critical sections: cannot execute
concurrently• synchronized (expression) { critical section
statements }• expression: must resolve to object / array
• Don't execute critical section till obtain lock• Used as method modifier
• Method is critical section
Institute for Visualization and Perception ResearchI VPR 45
© Copyright 1998 Haim Levkowitz
The package and import statements ...• Already mentioned
Institute for Visualization and Perception ResearchI VPR 46
© Copyright 1998 Haim Levkowitz
Exceptions and Exception Handling ...• Exceptions ...• Exception objects ...• Exception handling ...• Declaring exceptions ...• Defining and generating exceptions ...
Institute for Visualization and Perception ResearchI VPR 47
© Copyright 1998 Haim Levkowitz
Exceptions ...
• Signal indicating exceptional condition• catch : handle it• Exceptions propagate up through
method, then up through method call stack, till caught
• ==> Error handling more regular
Institute for Visualization and Perception ResearchI VPR 48
© Copyright 1998 Haim Levkowitz
Exception objects ...
• Instance of subclass of java.lang.Throwable• Throwable: two standard subclasses
• java.lang.Error Subclasses ...• java.lang.Exception Subclasses ...
• Contain data, define methods ...
Institute for Visualization and Perception ResearchI VPR 49
© Copyright 1998 Haim Levkowitz
java.lang.Error Subclasses ...• Linkage problems related to dynamic
loading• VM problems
• e.g., out of memory• Almost always unrecoverable
• ==> Should not be caught
Institute for Visualization and Perception ResearchI VPR 50
© Copyright 1998 Haim Levkowitz
java.lang.Exception Subclasses ...• May be caught and recovered from• E.g., java.io.EOFException• java.lang.ArrayAccessOutOFBounds
Institute for Visualization and Perception ResearchI VPR 51
© Copyright 1998 Haim Levkowitz
Contain data, define methods ...• Throwable object: String message in def
• Set when exception object created• Pass arg to constructor method
• Inherited by all exception classes• Store error message to humans• Read w/ Throwable.getMessage()• Most exceptions contain only this• Some add, e.g., java.io.InterruptedIOException
• public in bytesTransferred• How much I/O completed before
Institute for Visualization and Perception ResearchI VPR 52
© Copyright 1998 Haim Levkowitz
Exception handling ...
• try / catch / finally ...• try ...• catch ...• finally ...
Institute for Visualization and Perception ResearchI VPR 53
© Copyright 1998 Haim Levkowitz
try {// normally, run top to bottom// sometimes exception, or exit // via break, continue, return
}catch (SomeException e1) {
// handle exception obj e1 of type SomeException or of subclass
}catch (AnotherException e2) {
// handle exception e2}finally {
// Always execute this after leave try clause// regardless of how left
}
try / catch / finally ...
Institute for Visualization and Perception ResearchI VPR 54
© Copyright 1998 Haim Levkowitz
try ...
• Establish block of code • Handle its abnormal exits
• break, continue, return, exception• Doesn't do anything by itself
Institute for Visualization and Perception ResearchI VPR 55
© Copyright 1998 Haim Levkowitz
catch ...
• Zero or more, following try block• Specify code to handle exceptions• Syntax: ea. clause w/ argument
• Type: Throwable / subclass• Exception invoke first catch w/ approp.
type arg• Code within implements handling
Institute for Visualization and Perception ResearchI VPR 56
© Copyright 1998 Haim Levkowitz
finally ...
• Usually clean up after try• Guaranteed to execute always• Normally: at end of try block• Otherwise, executed before control
transfers to new destination• If there is catch block, xfer control to it
first
Institute for Visualization and Perception ResearchI VPR 57
© Copyright 1998 Haim Levkowitz
Declaring exceptions ...
• Either catch exception, or specify type w/ throws clause in method declaration• E.g., ...
• Any subclass of Throwable that is not subclass of Error or RuntimeException
Defining and generating exceptions …
Institute for Visualization and Perception ResearchI VPR 58
© Copyright 1998 Haim Levkowitz
E.g., …public void open_file() throws IOException {
// statements might generate uncaught// java.io.IOException
}public void myfunc(int arg) throws
MyException1, MyException2 ...
}
Institute for Visualization and Perception ResearchI VPR 59
© Copyright 1998 Haim Levkowitz
Defining and generating exceptions ...• Can signal own exception with throw statement• Must be followed by Throwable object, or
subclass• throw new myException("condition occurred.");• ==> normal exec stopr; look for catch clause• finally blocks executed• Example 2-3
Institute for Visualization and Perception ResearchI VPR 60
© Copyright 1998 Haim Levkowitz
Miscellaneous Differences ...
• Local variable declarations ...• Forward references ...• Method overloading ...• The void keyword ...• Modifiers ...• No structures or unions ...• No enumerated types ...• No bitfields ...• No typedef ...• No variable-length argument lists ...
Institute for Visualization and Perception ResearchI VPR 61
© Copyright 1998 Haim Levkowitz
Local variable declarations ...• Anywhere in method body / block of
code• Not only as first statement in block
• Still, good style to group, usually at beg.
Institute for Visualization and Perception ResearchI VPR 62
© Copyright 1998 Haim Levkowitz
Forward references ...
• Allowed, very flexible• Not allowed in variable initialization
Institute for Visualization and Perception ResearchI VPR 63
© Copyright 1998 Haim Levkowitz
Method overloading ...
• Methods with same name, different signature• E.g., return different values• Take diff args (number, type, order)
• Usually same basic function• Diff ways, as convenient
Institute for Visualization and Perception ResearchI VPR 64
© Copyright 1998 Haim Levkowitz
The void keyword ...
• Indicate function returns no value• Constructor methods diff
• Declare function(): no arguments• No void * type• No need (void) cast to ignore results
returned by non-void method
Institute for Visualization and Perception ResearchI VPR 65
© Copyright 1998 Haim Levkowitz
Modifiers ...
• final ...• native ...• synchronized ...• transient ...• volatile ...
Institute for Visualization and Perception ResearchI VPR 66
© Copyright 1998 Haim Levkowitz
final ...
• class: never subclassed• method: never overridden• variable: never have value set
Institute for Visualization and Perception ResearchI VPR 67
© Copyright 1998 Haim Levkowitz
native ...
• Applied to method declaration• Indicates method implemented
elsewhere in C, or other platform dependent way
• Should have semicolon in place of body
Institute for Visualization and Perception ResearchI VPR 68
© Copyright 1998 Haim Levkowitz
synchronized ...
• Mark critical section (seen already)• Indicates method modifies internal
state of class / instance of class ==> not thread-safe
• ==> Should obtain lock before running
Institute for Visualization and Perception ResearchI VPR 69
© Copyright 1998 Haim Levkowitz
transient ...
• Applied to instance variables in class• Specified var no part of persistent
state of object• E.g., scratch var's
• Not currently used
Institute for Visualization and Perception ResearchI VPR 70
© Copyright 1998 Haim Levkowitz
volatile ...• May be applied to variables• Specifices var changes asynchronously
• E.g., mem mapped H/W register on periph. dev.
• ==> Compiler should not attempt optimization
• read var's value from mem; shouldn't attempt save copy in register
Institute for Visualization and Perception ResearchI VPR 71
© Copyright 1998 Haim Levkowitz
No structures or unions ...
• Class same as struct• Can simulate union features with
subclassing
Institute for Visualization and Perception ResearchI VPR 72
© Copyright 1998 Haim Levkowitz
No enumerated types ...
• No enum keyword• Can partially simulated with static final
constant values
Institute for Visualization and Perception ResearchI VPR 73
© Copyright 1998 Haim Levkowitz
No bitfields ...
• In C, mostly to interface with H/W devices
• Never needed in Java• Platform independent programming
model
Institute for Visualization and Perception ResearchI VPR 74
© Copyright 1998 Haim Levkowitz
No typedef ...
• Cannot define aliases to type names• Much simpler type naming scheme ==>
no need
Institute for Visualization and Perception ResearchI VPR 75
© Copyright 1998 Haim Levkowitz
No variable-length argument lists ...• Cannot define method w/ var number of
args• Strongly typed• No way to do type checking on method
with variable args• Can simulate with method overloading
for simple cases
Institute for Visualization and Perception ResearchI VPR 76
© Copyright 1998 Haim Levkowitz
Variables...
• Fibonacci ...
Institute for Visualization and Perception ResearchI VPR 77
© Copyright 1998 Haim Levkowitz
Fibonacci ...class Fibonacci {
/** Print out the Fibonacci sequence for values < 50 */public static void main(String[] args) {
int lo = 1;int hi = 1;
cont. ...System.out.println(lo);while (hi < 50) {
System.out.println(hi);hi = lo + hi; // new hilo = hi - lo; /* new lo is (sum - old lo)
i.e., the old hi */}
}}