Docsity

CS361 Fall 2004 Java Notes - Prof. Bruce W. Char, Study notes of Computer Science

Toggle sidebar
bg1
1
page 1
CS 361 Concurrent programming
Drexel University
Fall 2004
Lecture 3
©Bruce Char and Vera Zaychik. All rights reserved by the author.
Permission is given to students enrolled in CS361 Fall 2004 to
reproduce these notes for their own use.
page 2
Summary of last time
• Java is Object Oriented
• Java is syntactically similar to C
– String class built-in
• Correspondence between class names and
file names
• CLASSPATH determines alternative
directories for classes (also .jar files)
page 3
More summary
• Static methods and data members: one
occurrence of member per program.
page 4
Some Definitions
•Asynchronous operation occurs because
many computer system events happen at
unpredictable times and in an unpredictable
order. As a result, a program must work
correctly for all possible timings in order to
be correct.
page 5
Some Definitions
•Concurrency – sharing of resources in the
same time frame.
When two programs execute on the same
system so that their execution is interleaved
in time, they share processor resources.
page 6
Multiprogramming
• Multiprogramming means that more than
one process can be ready to execute.
• Can be implemented for both single- and
multi-processor systems.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download CS361 Fall 2004 Java Notes - Prof. Bruce W. Char and more Study notes Computer Science in PDF only on Docsity!

page 1

CS 361 Concurrent programming

Drexel University

Fall 2004

Lecture 3

©Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce these notes for their own use.

page 2

Summary of last time

• Java is Object Oriented

• Java is syntactically similar to C

– String class built-in

• Correspondence between class names and

file names

• CLASSPATH determines alternative

directories for classes (also .jar files)

page 3

More summary

• Static methods and data members: one

occurrence of member per program.

page 4

Some Definitions

• Asynchronous operation occurs because

many computer system events happen at

unpredictable times and in an unpredictable

order. As a result, a program must work

correctly for all possible timings in order to

be correct.

Some Definitions

• Concurrency – sharing of resources in the

same time frame.

When two programs execute on the same

system so that their execution is interleaved

in time, they share processor resources.

Multiprogramming

• Multiprogramming means that more than

one process can be ready to execute.

• Can be implemented for both single- and

multi-processor systems.

page 7

Parallelism

• Pseudo-parallelism – rapid switching of the CPU

between processes (as opposed to the actual use of

several CPUs). Also called timesharing.

• Only one process running at any one time for a set

small period of time (quantum)

• No assumptions about timing can be made

• Each switch from one process to another is called

a context switch

page 8

Time and Speed

quantum 100,000,000 ns 6,3 years

disk access 7,000,000 ns 162 days

context switch 5,000 ns 167 minutes

memory access 15 ns 30 seconds

cache access 1 ns 2 seconds

processor cycle 0.5 ns 1 second

Scaled time in

human terms

Item Time

page 9

Naming conventions for classes,

variables

• These are rules borrowed from Reiss’

“Software Design” textbook used in cs350.

Java does not insist on them but we

recommend following coherent naming

rules to reduce software engineering costs.

page 10

Naming conventions for classes,

variables, constants

• Names of classes: First letter capitalized, e.g.

class Movie { ….}

• Names of methods: first letter lower case; multi-

word method names capitalized second and

successive words:

public int getTime();

public void clear();

• Names of constants: all caps

final int BOARD_SIZE;

I/O

• from command line arguments

• from the terminal

• from files

I/O stream classes

• Compose them together to read/write

to/from files: text, binary data, other kinds.

page 19

Vector example

import java.io.; import java.util.;

public class vectorExample { public static void main(String argv[]) throws IOException{ FileInputStream stream = new FileInputStream(argv[0]); InputStreamReader reader = new InputStreamReader(stream); StreamTokenizer tokens = new StreamTokenizer(reader); Vector v = new Vector(); while(tokens.nextToken() != tokens.TT_EOF) {// TT_EOF a system constant int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; tokens.nextToken(); System.out.println("read: " + x + " " + y + " " + z); v.addElement(new Movie2(x,y,z)); }; stream.close(); for (int counter = 0; counter < v.size(); counter++) { System.out.println( ((Movie2) (v.elementAt(counter))).rating()); } } } page 20

Vector elements can be assigned

any subclass of Object

  • import java.util.Vector; class Test { public static void main(String argv[]) { Vector v; v = new Vector(0); v.addElement(new Integer(1));// creates integer // object v.addElement("abc"); for (int i=0; i<v.size(); i++) { System.out.println("item " + i + " is: "+ v.elementAt(i)); }; } } Anything except a primitive type (int, float, boolean, char) is a subclass of Object.

page 21

Execution

In input2.data: 4 7 9 3 2 6 1 1 1 Output: e:\My Documents\mcs361\Sp02>java vectorExample input2.data java vectorExample input2.data read: 4 7 9 read: 3 2 6 read: 1 1 1 20 9 3

page 22

Inheritance

• to have class B be a subclass of class A,

write “public class B extends A {….”

abstract classes

• Subclasses used in program, inherit

methods and fields of superclass.

• But you can’t create an instance of the

superclass.

Abstract class example

public abstract class Attraction{ public int minutes; public Attraction() {minutes = 75;} public int getMinutes() {return minutes;} public void setMinutes (int d) { minutes = d;} } then class definitions for Movie and Symphony: public Movie extends Attraction { ….} and public Symphony extends Attraction { …} can use Attraction x; x = new Movie() or x = new Symphony; in a program

page 25

Interfaces

• Java does not have general multiple

inheritance. It does have limited multiple

inheritance.

• An interface B is a class that has only class

declarations.

• public class A implements B, C, D {…} means that A

inherits the methods of B,C, and D (and can

have methods and members of its own).

page 26

What methods does this class

have? Which ones did the

programmer of the class have to

implement?

public class DrawableScalableRectangle extends DrawableRectangle implements Drawable, Scalable { … }

page 27

Defining an abstract class

• public abstract class GeometricObject

// class definition goes here as normal

page 28

Defining an interface class

//Definition starts with “interface” instead of “class”

interface FloatingVessel {

int navigate(Point from, Point to);

// Point is another user-defined class

void dropAnchor();

void weighAnchor();

What is the UML static class

relationship implied by the

declaration

public class DrawableScalableRectangle extends DrawableRectangle implements Drawable, Scalable { …

}

As with C++ a pointer for the

superclass can point to an object

of the subclass

class A1 implements A {….} class B1 extends B {….} class C { public int method1(A a, B b) {…} … public method2(…) { int result; B1 b1Object; A1 a1Object; b1Object = new B1(…); a1Object = new A1(…): result = method1(a1Object, b1Object); ….} }

page 37

Supplemental: More Java

Concurrent Programming

Spring 2004

©Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Spring 2004 to reproduce these notes for their own use.

page 38

API

• Best reference is online:

http://java.sun.com/j2se/1.4/docs/api/

page 39

Garbage Collection

• All memory allocated on the heap that is no

longer referenced is freed up by the

Garbage Collector

• There is no telling when that will happen

• There is a way to force garbage collection if

needed (System.gc())

page 40

Java procedures are mainly call

by reference

• This means that procedures can easily alter

objects passed to them as parameters.

Building your own exceptions.

• Class ArgumentNegativeException extends

Exception{};

Programming with exceptions.

class Factorial{ Public static int compute(int k) throws ArgumentNegativeException, other exceptions { if (k<0) throw new ArgumentNegativeException(); else return 1; } (and later in a program) …. try { System.out.println (“answer is: “ + Factorial.compute(n)); } catch(ArgumentNegativeException e) { System.err.println(e + “oops”); continue; }; ….

page 43

super

• used to call the parent class's constructor, with

arguments if desired, using the syntax

super(arg0, arg1, ...).

• must be the very first line in every constructor

unless omitted, in which case it will be

automatically inserted without arguments

• super.xxx( ) to call methods of the parent

• only goes one level up (no super.super)

page 44

Java lacks some C++ features

• No templates. But superclass is Object. Could

program a stack class with Objects, and then cast

into an object of another class.

• Exception: primitive data types such as int, float

are not subclasses of Object. However, there are

wrapper classes Integer, Double, etc.

• No overloading of operators (although function

overloading is okay).

• No i/o operators <<, >>.

• No general multiple inheritance.

page 45

No environment variables in Java

• No such thing as environment variables as

there are with C/C++ and Unix because this

is not OS independent. There’s a system

property setting mechanism that accesses

properties declared in the command line

invocation called System.getProperty()…

read about it in the Java documentation.

page 46

instanceOf

• can upcast and downcast, but wrong cast

can cause exceptions during runtime

• To check whether a certain object is of a

particular class use instanceOf

keyword this

• To invoke one method from another in the same

class an object must send a message to itself

• this.methodName( ) does the job

• To refer to a field, use this.fieldName

• When no ambiguity is possible, this is optional

private String text; public Greeting(String text) { this.text = text; }

Object

• equals(Object e)

• finalize()

• hashCode()

• toString()

page 55

Set

• Like a List

– can grow as needed

– can contain only Objects (heterogeneous)

– easy to add/delete

– API independent of implementation

(HashSet, TreeSet)

• Unlike a List

– elements have no positions

– duplicate entries not allowed

page 56

Collection API methods (some)

• int size();

• boolean add( Object obj );

returns true if Collection changes as a result of the

add (it always will for List, may not for Set)

• boolean contains( Object obj );

• to see the rest, study the API

(warning: look at List , not List (a GUI class)

page 57

Iterator Interface

// suppose Collection of Programmer objects Iterator iter = engineers. iterator() ; while (iter .hasNext() ) { Programmer p = (Programmer)iter .next() ; p.feed("pizza"); }

• Note cast (Programmer) since Collection and

Iterator manage anonymous objects

• When collection has a natural ordering, Iterator will

respect it

• Supports safe remove() of most recent next

page 58

StringTokenizer

• Like an Iterator for a String

• Elements are (white space delimited) words

StringTokenizer st = new StringTokenizer(“now is the time …”); while (st .hasMoreTokens() ) { String word = st. nextToken() ; ... }

• Should implement Iterator interface (hasNext, next)

Map

• Table lookup abstraction

– void put( Object key, Object value)

– Object get( Object key)

– can grow as needed

– any Objects for key and value

(keys tested for equality with .equals, of course)

– API syntax independent of implementation

(HashMap, TreeMap)

– Iterators for keys, values, (key, value) pairs

Conversions String < > Object

• String s = “I am ” + obj;

invokes obj. toString ()

• s = String. valueOf (Object obj);

ditto, and overloaded for primitive types

char[], boolean, char, int, long, float, double

int Integer. valueOf (String s);

// Integer is wrapper class for int

Integer Integer. parseInt (String s);

page 61

Equality (reminder)

• for objects, == tests pointer, not contents

• Object class implements

public boolean equals (Object obj) { return this == obj; } public int hashCode(); // probable unique id

• String class overrides

if (g.equals(“goodbye”)) ... // not == if “goodbye”.equals(g)) ... // ok too

• Strings hash as they should

• for deep copy, override

Object clone () // field by field copy page 62

String matches and searches

boolean equalsIgnoreCase (String anotherString); int compareTo (String anotherString); // +,-,

boolean startsWith (String prefix); boolean endsWith (String suffix); boolean regionMatches (int toffset, String other, int ooffset, int len);

int indexOf (int ch); int indexOf (String str); int indexOf (..., int fromIndex); int lastIndexOf (...);

page 63

Methods Returning/Constructing New Strings

concat (String str); // Can also use +

replace (char old, char new); // Not in place!

substring (int beginIndex); // New string! substring (int beginIndex, int endIndex);

toLowerCase (); // New string! toLowerCase (Locale locale); toUpperCase (); toUpperCase (Locale locale);

trim ();

page 64

Class StringBuffer

• mutable size and content

StringBuffer str = new StringBuffer("World"); str. insert (0, "Jello, "); str. append ("!"); str. setCharAt (0,'H'); // now "Hello, World!" str. reverse (); // now "!dlroW ,olleH" String s = str.toString();

public class File

• Information about files, not their contents

• Constructors

File (String path) or (String path, String name) or (File dir, String name)

• Methods

boolean exists (), isFile (), isDirectory (), canRead (), canWrite (); long length (), lastModified (); boolean delete (), mkdir (), mkdirs (), renameTo (File dest); String getName (), getParent (), getPath (), getAbsolutePath ()

Useful System Constants

final, static , portable?

Windows Unix File. pathSeparator ; ";" ":" File. separator ; "" "/”

System.getProperty ("line.separator") " \n\r" "\n" // System.getProperty gets other properties too

public static final FileDescriptor in ; public static final FileDescriptor out ; public static final FileDescriptor err ;