7. java.pdf

93
1 Java Xiaoqiang Wang Florida State University

Upload: ingramk

Post on 14-Apr-2018

274 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 1/93

1

Java

Xiaoqiang Wang

Florida State University

Page 2: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 2/93

2

Why Java?

 It’s almost entirely object-oriented

 It has a vast library of predefined objects andoperations

 It’s more platform independent

 this makes it great for Web programming

 It’s more secure

 It isn’t C++

Page 3: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 3/93

3

 Applets, Servlets and

 Applications

  An applet is designed to be embedded in a

Web page, and run by a browser    Applets run in a sandbox with numerous

restrictions; for example, they can’t read files

and then use the network

  A servlet is designed to be run by a web

server    An application is a conventional program

Page 4: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 4/93

4

Building Standalone JAVA

Programs (on UNIX)

 Prepare the file f oo. j ava using an editor 

 Invoke the compiler: j avac f oo. j ava

 This creates f oo. cl ass

 Run the java interpreter:  j ava f oo

Page 5: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 5/93

5

Java Virtual Machine

 The .class files generated by the compiler arenot executable binaries

 so Java combines compilation and interpretation

 Instead, they contain “byte-codes” to beexecuted by the Java Virtual Machine

 other languages have done this, e.g. UCSD

Pascal  This approach provides platform

independence, and greater security

Page 6: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 6/93

6

HelloWorld (standalone)

publ i c cl ass Hel l oWor l d {publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {

Syst em. out . pr i nt l n( "Hel l o Wor l d! " ) ;}

}

 Note that String is built in

 println is a member function for theSystem.out class

Page 7: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 7/93

7

Comments are almost like C++

 /* This kind of comment can span multiple lines */

 // This kind is to the end of the line

 /**

 * This kind of comment is a special

 * ‘javadoc’

 style comment

 */

Page 8: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 8/93

8

Primitive data types are like C

 Main data types are int, double, boolean,

char

  Also have byte, short, long, float

 boolean

 has values true

 and false

 Declarations look like C, for example,

 double x, y;

 int

 count = 0;

Page 9: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 9/93

9

Non-Primitive types in Java

 Classes

 Everything is a class, defined within a package

  Arrays

 byte[] b = new byte[100];  Strings

 string st = “scientific computing” is initialized like a

primitive type, but it is not a primitive type!

Page 10: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 10/93

10

 Array Operations

 Subscripts always start at 0 as in C

 Subscript checking is done automatically

 Certain operations are defined on arrays of 

objects, as for other classes

 e.g. myArray.length == 5

Page 11: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 11/93

11

Expressions are like C

  Assignment statements mostly look like those in C; youcan use =, +=, *=  etc.

  Arithmetic uses the familiar  + -  * / %

 Java also has ++ and --

 Java has boolean operators && || !

 Java has comparisons < <= == != >= >

 Java does not have pointers or pointer arithmetic

Page 12: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 12/93

12

Control statements are like C

 if (x < y) smaller = x;

 if (x < y){ smaller=x;sum += x;}  else { smaller = y; sum += y; }

 while (x < y) { y = y -

 x; }

 do { y = y -  x; } while (x < y)

 for (int  i = 0; i < max; i++)

sum += i;  BUT: conditions must be boolean  !

Page 13: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 13/93

13

Control statements II

 Java also introduces the try  statement,about which more later 

switch (n + 1) {  case 0: m = n -  1; break;  case 1: m = n + 1;  case 3: m = m * n; break;  default: m = -n; break;  }

Page 14: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 14/93

14

Java isn't C!

 In C, almost everything is in functions  In Java, almost everything is in classes

 There is often only one class per file  There must be only one public  class per file

 The file name must be the same as the

name of that public class, but with a .java  extension

Page 15: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 15/93

15

Java program layout

  A typical Java file looks like:

import java.awt.*;  import java.util.*;

public class SomethingOrOther  {  // object definitions go here  . . .  }

This must be in a file named SomethingOrOther.java

 !

Page 16: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 16/93

16

References

  All variable names in java that are not

primitive types are actually references

int[] a = new int[100];int[] b = a;

// b and a are references to the 100 bytes in memory

b[3] = 10;

System.out.println(“a[3]= “ + a[3]); // prints 10

Page 17: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 17/93

17

 Argument Passing

 methods in java pass arguments by value

 the dummy argument in the method is a copyof the argument passed

 if a primitive type is passed, it is copied  if a non-primitive type is passed, its reference

is passed. More precisely, the variable is a

reference.

Page 18: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 18/93

18

 Argument Passingclass Refer {

...

public void refer(int[] a) {

a[3] = 4;

int[] b = new int[10];

// redefines the referencea = b;

a[3] = 12.;

// the caller argument is

// unchanged!!

}

}

...

Refer ref = new Refer();int[] d = new int[20];

ref.refer(d);

...System.out.println("d[3]= "

+ d[3]);

// prints the value 4

Page 19: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 19/93

19

Scoping

  As in C/C++, scope is determined by the placement of curly

braces {}.

  A variable defined within a scope is available only to the end

of that scope.

{ int x = 12;

/* only x available */

{ int q = 96;

/* both x and q available */

}

/* only x available */

/* q “out of scope” */

}

{ int x = 12;

{ int x = 96; /* illegal */

}

}

This is ok in C/C++ but not in Java.

Page 20: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 20/93

20

 An array is an object

 Person mary = new Person ( );

 int  myArray[ ] = new int[5];

 int  myArray[ ] = {1, 4, 9, 16, 25};

 String languages [ ] = {"Prolog","Java"};

 Since arrays are objects they are allocated

dynamically

  Arrays, like all objects, are subject to garbage

collection when no more references remain

 so fewer memory leaks Java doesn’t have pointers!

Page 21: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 21/93

21

Scope of Objects

 Java objects don’t have the same lifetimes

as primitives.

 When you create a Java object using new,

it hangs around past the end of the scope.  Here, the scope of name s is delimited by

the {}s but the String object hangs around

until GC’d{

String s = new String("a string");} /* end of scope */

Page 22: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 22/93

22

Name conventions

 Java is case-sensitive; maxval, maxVal, andMaxVal  are three different names

 Class names begin with a capital letter 

  All other names begin with a lowercase letter   Subsequent words are capitalized:

theBigOne  Underscores are not used in names

 These are very strong conventions!

Page 23: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 23/93

23

JAVA Classes

 The class is the fundamental concept in JAVA(and other OOPLs)

  A class describes some data object(s), and theoperations (or methods) that can be applied tothose objects

 Every object and method in Java belongs to aclass

 Classes have data (fields) and code (methods)and classes (member classes or inner classes)

 Static methods and fields belong to the classitself 

 Others belong to instances

Page 24: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 24/93

24

Examplepublic class Circle {// A class fieldpublic static final double PI= 3.14159; // A usefulconstant

// A class method: just compute a value based on the argumentspublic static double radiansToDegrees(double

 rads) {

return rads

 * 180 / PI;

}

// An instance fieldpublic double r; // The radius of the circle

// Two methods which operate on the instance fields of anobjectpublic double area() { // Compute the area of thecirclereturn PI * r * r;

}public double circumference() { // Compute the circumference

of the circlereturn 2 * PI * r;

}

Page 25: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 25/93

25

Constructors

 Classes should define one or more methods to create or construct instances of the class

 Their name is the same as the class name

 note deviation from convention that methods begin with lower case

 Constructors are differentiated by the number and types of their arguments

  An example of overloading

 If you don’t define a constructor, a default one will be created.

 Constructors automatically invoke the zero argumentconstructor of their superclass when they begin (note that thisyields a recursive process!)

Page 26: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 26/93

26

Constructor examplepubl i c cl ass Ci r cl e {

publ i c st at i c f i nal doubl e PI = 3. 14159; / / A const ant

publ i c doubl e r ; / / i nst ance f i el d hol ds ci r cl e’ s

r adi us

/ / The const r uct or met hod: i ni t i al i ze t he r adi us f i el d

publ i c Ci r cl e( doubl e r ) { t hi s. r = r ; }

/ / Const r uct or t o use i f no ar gument s

publ i c Ci r cl e( ) { r = 1. 0; }

/ / bet t er : publ i c Ci r cl e( ) { t hi s( 1. 0) ; }

/ / The i nst ance met hods: comput e val ues based on r adi us

publ i c doubl e ci r cumf er ence( ) { r et ur n 2 * PI * r ; }

publ i c doubl e ar ea( ) { r et ur n PI * r *r ; }

}

this.r refers to the r 

field of the class

This() refers to a

constructor for the class

Page 27: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 27/93

27

Extending a class

 Class hierarchies reflect subclass-superclass relations among

classes.

 One arranges classes in hierarchies:

  A class inherits instance variables and instance methods fromall of its superclasses. Tree -> BinaryTree -> BST

 You can specify only ONE superclass for any class.

 When a subclass-superclass chain contains multiple instancemethods with the same signature (name, arity, and argument

types), the one closest to the target instance in the subclass-

superclass chain is the one executed.

  All others are shadowed/overridden.

 Something like multiple inheritance can be done via interfaces

(more on this later)

 What’s the superclass of a class defined without an extendsclause?

Page 28: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 28/93

28

Extending a classpubl i c cl ass Pl aneCi r cl e ext ends Ci r cl e {

/ / We aut omat i cal l y i nher i t t he f i el ds and met hods of Ci r cl e,/ / so we onl y have t o put t he new st uf f her e./ / New i nst ance f i el ds t hat st or e t he cent er poi nt of t he ci r cl epubl i c doubl e cx, cy;

/ / A new const r uct or met hod t o i ni t i al i ze t he new f i el ds/ / I t uses a speci al synt ax t o i nvoke t he Ci r cl e( ) const r uct orpubl i c Pl aneCi r cl e( doubl e r , doubl e x, doubl e y) {

super ( r ) ; / / I nvoke t he const r uctor of t he super cl ass, Ci r cl e( )t hi s . cx = x; / / I ni t i al i ze t he i nst ance f i el d cxt hi s . cy = y; / / I ni t i al i ze t he i nst ance f i el d cy

}

/ / The ar ea( ) and ci r cumf er ence( ) met hods ar e i nher i t ed f r om Ci r cl e/ / A new i nst ance met hod t hat checks whet her a poi nt i s i nsi de t he ci r cl e/ / Not e t hat i t uses t he i nher i t ed i nst ance f i el d rpubl i c bool ean i sI nsi de( doubl e x, doubl e y) {

doubl e dx = x - cx, dy = y - cy; / / Di st ance f r om cent erdoubl e di st ance = Mat h. sqr t ( dx*dx + dy*dy) ; / / Pyt hagor ean t heor emr et ur n ( di st ance < r ) ; / / Ret ur ns t r ue or f al se

}}

Page 29: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 29/93

29

Data hiding and encapsulation

 Data-hiding or encapsulation is an important partof the OO paradigm.

 Classes should carefully control access to their data and methods in order to

 Hide the irrelevant implementation-level details so theycan be easily changed

 Protect the class against accidental or maliciousdamage.

 Keep the externally visible class simple and easy to

document

 Java has a simple access control mechanism tohelp with encapsulation

 Modifiers: public, protected, private, and package(default)

Page 30: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 30/93

30

Package

 Every class name lies in a file with an identical name

 Every class is defined within a package

// this file is in directory /path../gordon/grid

package gordon.grid

class Shape {...}

---------------------------------

package gordon

// import all classes in the package gordon.grid

import gordon.grid.*

class SubShape extends Shape {

Shape sh1; // short name allowed since class is imported (.*)

gordon.grid.Shape sh2; // fully qualified name (not necessary)

public void perimeter(...);

}

Page 31: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 31/93

31

 Access control

  Access to packages

 Java offers no control mechanisms for packages.

 If you can find and read the package you can access it

  Access to classes

  All top level classes in package P are accessibleanywhere in P

  All public top-level classes in P are accessibleanywhere

  Access to class members (in class C in packageP)

 Public: accessible anywhere C is accessible

 Protected: accessible in P and to any of C’s subclasses

 Private: only accessible within class C

 Package: only accessible in P (the default)

Page 32: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 32/93

32

Page 33: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 33/93

33

The static keyword

 Java methods and variables can be declared static (to createfields and methods that belong to the class, rather than to aninstance of the class. )

 These exist independent of any object

 This means that a Class’s

 static methods can be called even if no objects of that classhave been created and

 static data is “shared” by all instances (i.e., one rvalue per class instead of one per instance

class StaticTest {static int i = 47;}

StaticTest st1 = new StaticTest();StaticTest st2 = new StaticTest();

// st1.i == st2.I == 47

StaticTest.i++; // or st1.I++ or st2.I++// st1.i == st2.I == 48

Page 34: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 34/93

34

 Abstract classes and methods

  Abstract vs. concrete classes

  Abstract classes can not be instantiatedpublic abstract class shape { }

  An abstract method is a method w/o a bodypublic abstract double area();

 (Only) Abstract classes can have abstract

methods

 In fact, any class with an abstract method is

automatically an abstract class

Page 35: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 35/93

35

Example: abstract classpubl i c abst r act cl ass Shape {

publ i c abst r act doubl e ar ea( ) ; / / Abst r act met hods: not epubl i c abst r act doubl e ci r cumf er ence( ) ; / / semi col on i nst ead of body.

}

cl ass Ci r cl e ext ends Shape {publ i c st at i c f i nal doubl e PI = 3. 14159265358979323846;pr ot ect ed doubl e r ; / / I nst ance dat apubl i c Ci r cl e( doubl e r ) { t hi s. r = r ; } / / Const r uctorpubl i c doubl e get Radi us( ) { r et ur n r ; } / / Accessorpubl i c doubl e ar ea( ) { r et ur n PI *r *r ; } / / I mpl ement at i ons of publ i c doubl e ci r cumf er ence( ) { r et ur n 2*PI *r ; } / / abst r act met hods.

}

cl ass Rect angl e ext ends Shape {pr ot ect ed doubl e w, h; / / I nst ance dat apubl i c Rect angl e( doubl e w, doubl e h) { / / Const r uct or

t hi s. w = w; t hi s. h = h;}publ i c doubl e get Wi dt h( ) { r et ur n w; } / / Accessor met hodpubl i c doubl e get Hei ght ( ) { r et ur n h; } / / Anot her accessorpubl i c doubl e ar ea( ) { r et ur n w*h; } / / I mpl ement at i ons of publ i c doubl e ci r cumf er ence( ) { r et ur n 2*( w + h) ; } / / abst r act met hods.

}

Page 36: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 36/93

36

Syntax Notes

 No global variables

 class variables and methods may be applied toany instance of an object

 methods may have local (private?) variables

 No pointers

 but complex data objects are “referenced”

Page 37: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 37/93

37

Single Inheritance, but

  A class may extend only one class, but it may

implement many others   A subclass inherits the variables and

methods of its superclass(es), but mayoverride them

 Overrides the methods defined in the

class(es) it implements

Page 38: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 38/93

38

Classes and Interfaces  The methods of an abst r act class are

implemented elsewhere   A f i nal class cannot be extended

Page 39: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 39/93

39

Interfaces

 Java does not allow “multiple inheritance” because it introduces

 problems as well as benefits. Fortunately,

 Java allows you to impose requirements on a class from multipleclass-like interfaces.

 An interface is like an abstract class in that it can hold abstractmethod definitions that force other classes to implement ordinarymethods.

 But it is also different:

 An interface does NOT have instance variables (but itcan have constants)

 All methods in an interface are abstract (they each havea name, parameters, and a return type, but noimplementation)

 All methods in an interface are automatically public.

Page 40: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 40/93

40

Classes vs. Interfaces

  A class definition that implements an interface mustdefine all the methods specified in that interface. Inthis respect, an interface is like an abstract class.

  An interface differs from an abstract class, however,in several respects:

  An interface only imposes definition requirements;

interfaces do not supply definitions.

  A class extends exactly one superclass; a class canimplement an unlimited number of interfaces.

 Thus, the purpose of the interface is strictly toimpose requirements via its abstract methods; thereare no method implementations:

Page 41: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 41/93

41

Interfaces

 Interfaces provide no mechanism for enforcingmethod specifications, other than method

signatures

 you are free to deposit descriptive comments inan interface, however.

 Interfaces are excellent places for descriptivecomments for two reasons:

 Interfaces, unlike class definitions, are free of 

clutter from implementing code.

 Programmers look to interfaces for method andclass documentation.

Page 42: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 42/93

42

Interfaces

 The interface mechanism is an enormously

important aid to good programming practice.

 Interfaces allow you to shift to the Java compiler arequirement-managing responsibility

 Interfaces encourage you to document your classes by acting, by convention, asdocumentation centers.

 Syntax:publ i c cl ass someClassName i mpl ement s I1, I2

{ … }

Page 43: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 43/93

43

Interfaces Example

  java.lang defines a Comparable interface as:publ i c i nt er f ace Compar abl e {i nt

compar eTo( Obj ect ot her ) ; } // noimplementation

 If you wantclass to provide some function, implementan appropriate interface

publ i c cl ass Movi e3 ext ends At t r act i on i mpl ement sComparabl e {

publ i c i nt compar eTo ( Obj ect ot her Movi e){ Movi e3 ot her = ( Movi e3) ot her Movi e;

i f ( r at i ng( ) < ot her . r at i ng( ) ) r et ur n - 1;el se i f ( r at i ng( ) > ot her . r at i ng( ) ) r et ur n 1;

el se r et ur n 0; } }

Page 44: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 44/93

44

Exceptions

 If an error does occur, that error is said to beexceptional behavior that throws an exception.

 Whenever an expression has the potential tothrow an exception, you can embed thatexpression in a try – catch statement, in which you

specify explicitly what Java is to do when anexception actually is thrown.

 Exceptions are objects in their own right

 They can be generated, caught and handled under program control

 Examples: IOException, ArithmeticException, etc.

Page 45: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 45/93

45

try/catch/finally

  Associates a set of statements with one or 

more exceptions and some handling codet ry {

 Thr ead. sl eep( 200) ;

}cat ch( I nt er r upt edExcept i on e) {

Syst em. out . pr i nt l n( e) ;

}f i nal l y {

Syst em. out . pr i nt l n( “Wakeup”) ;

}

Page 46: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 46/93

46

Exceptions

 Java will “throw an exception” when unusual

conditions arise during execution of programs, e.g.,

 E.g., Attempt to divide an integer by zero

 To handle the exception, use the following:

t ry {statement with potential to throw exception}cat ch ( exception-class-name parameter )

{exception-handling-code }

 To catch I/O exceptions, use:

 FileNotFoundException or IOException class.

Page 47: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 47/93

47

Exceptions

 Suppose, for example, that you want to open a file

for reading using a FileInputStream instance.

 You can acknowledge that the attempt may throw

an exception by embedding the reading expressions

in a block following the try keyword.

 Java stops executing statements in the try block as

soon as an exception is thrown:

try {

... <-- An attempt to attach a stream to a file occurs here

}

Page 48: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 48/93

48

Exceptions

 You specify what to do in the event that the

exception is an instance of the IOExceptionclass by writing the keyword catch, followed

by a parameter typed by IOException,

surrounded by parentheses, followed by

another block:

catch (IOException e) {...

}

Page 49: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 49/93

49

Exceptions

 To shut a program down, use System.exit(0);

 To have a block of statements executed after a try (whether or 

not an exception was thrown) use:f i nal l y { clean-up statements }

 You can create (and throw) your own exceptions, e.g.,

public class StrangeNewException extends Exception { }throw (new StrangeNewException () )

catch ( StrangeNewException e) { … }

  Alternative method to handle exceptions:publ i c st at i c voi d f ( params) t hr ows Except i on- cl ass{ … }

Page 50: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 50/93

50

variables & objects

 what happens when you run this?

String a = “foo”;

System.out.println (a);

 it prints

foo

 what is “foo”?

 a string literal that evaluates to a String object

 what is a?

 a variable whose value is an object reference

 what is String a = “foo”?

 a declaration and an assignment in one

“foo”(String)

a

Page 51: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 51/93

51

method calls

 what happens when you run this?String a = “foo”;

String b = a.toUpperCase ();

System.out.println (a);

 it prints

foo

 what is toUpperCase?

a method of class String

 type is String -> String

 declared as public String toUpperCase ()

 what is a.toUpperCase ()?a method call on the object a

 does it change a?

no, it creates a new string

“foo”

(String)

a

“foo”

(String)

b

Page 52: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 52/93

52

null references

 what happens when you run this?String a = null;

System.out.println (a);

 it prints

null

 what happens when you run this?String a = null;

String b = a.toUpperCase ();System.out.println (b);

it throws a NullPointerException

 why?

because a method call must have a subject

Page 53: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 53/93

53

sharing & equality

 what happens when you run this?String a = “foo”;

String b = “foo”;System.out.println (b);

 it printsfoo

 is that the same as this?String a = “foo”;

String b = a;

System.out.println (b);

 yes, because String is immutable.

 There is no way to distinguish these cases and, in fact, Java

virtual machine may produce upper or lower state in this case.

“foo”

(String)

a

“foo”(String)

b

“foo”

(String)

a

b

Page 54: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 54/93

54

mutable containerswhat happens when you run this?Vector v = new Vector ();

String a = “foo”;

v.addElement (a);

System.out.println (v.lastElement ());

it prints

foo

what happens when you run this?

Vector v = new Vector ();String a = “foo”;

String b = “foo”;

v.addElement (a);

System.out.println (v.lastElement ());

v.addElement (b);System.out.println (v.lastElement ());

it prints

foo

foo

(Vector)

v

“foo”

(String)

a

“foo”

(String)

b

Page 55: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 55/93

55

aliasingwhat about this?

Vector v = new Vector ();

Vector q = v;

String a = “foo”;v.addElement (a);

System.out.println (q.lastElement ());

it prints

foowhy?

 because v and q are aliased: they arenames for the same object

what if we now do this?if (v == q) System.out.println (“same object”);

if (v.equals (q)) System.out.println (“same value”);

it printssame object

same value

(Vector)

v

“foo”

(String)

a

q

 Aliasing occurs when several different 

identifiers refer to the same object. The termis very general and is used in many contexts.

Page 56: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 56/93

56

aliasing & immutables

 what does this do?String a = “foo”;

String b = a;a.toUpperCase ();

System.out.println (b);

it printsfoo

 why?

because strings are immutable

 The objects created by thetoUpperCase method is eventuallyGCed (garbage collected.)

“foo”

(String)

a

b

“foo”

(String)

a

“FOO”

(String)

b

Page 57: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 57/93

57

polymorphism

 what does this do?

Vector v = new Vector ();

Vector e = new Vector ()

v.addElement (e);

e.addElement (“foo”);

System.out.println (((Vector) v.lastElement ()).lastElement ());

 it printsfoo

 what kind of method is addElement?

declared as public void addElement (Object o)

(Vector)

v

(Vector)

e

(String)

“foo”

Page 58: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 58/93

58

On polymorphism

 First identified by Christopher Strachey (1967) anddeveloped by Hindley and Milner, allowing types such as alist of anything.

 E.g. in Haskell we can define a function which operates on alist of objects of any type a (a is a type variable).

l engt h : : [ a] - > I nt

 Polymorphic typing allows strong type checking as well asgeneric functions. ML in 1976 was the first language withpolymorphic typing.

  Ad-hoc polymorphism (aka overloading) is the ability to use

the same syntax for objects of different types, e.g. "+" for addition of reals and integers.

 In OOP, the term is used to describe variables which mayrefer at run-time to objects of different classes.

Page 59: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 59/93

59

reference loops

 can i even add v to itself?

Vector v = new Vector ();

v.addElement (v);

System.out.println (v.lastElement ())

 yes, try it!

 and this?

v.addElement (5);

 no, 5 is a primitive value, not an object

(Vector)

v

“foo”

Page 60: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 60/93

60

a pair of methods

 some types

 what are the types of addElement, lastElement?

addElement (Object), return voidlastElement (), return Object

 a puzzle

 how are x and e related after this?

v.addElement (e);

x = v.lastElement ();

 they denote the same object

 can the compiler infer that?

 no! not even that x and e have the same class

Page 61: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 61/93

61

downcasts

 what does this do?

Vector v = new Vector ();

String a = “foo”;

v.addElement (a);String b = v.lastElement ();

System.out.println (b);

 compiler rejects it: v.lastElement doesn’t return a String!

 what does this do?Vector v = new Vector ();

String a = “foo”;

v.addElement (a);

String b = (String) v.lastElement ();

System.out.println (b);

 it prints

foo

Page 62: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 62/93

62

upcasting and downcasting  Suppose we have object O of class C1 with

superclass C2  In Java, upcasting is automatic but

downcasting must be explicit.

 Upcasting: treating O as a C2

 Downcasting: treating O as a C1

Page 63: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 63/93

63

variable & object classes

 what does this do?Vector v = new Vector ();

String a = “foo”;

v.addElement (a);

Object o = v.lastElement ();

System.out.println (o.getClass ());

 it prints java.lang.String

 what’s going on here?

 getClass returns an object representing a class

 o.getClass () is the class o has at runtime

 System.out.println prints a string representation, ie, thename

Page 64: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 64/93

64

Some key concepts

 variables & objects

 variables hold object references (or primitive values like 5)

 null is a special object reference

 sharing, equality & mutability

 distinct objects can have the same value

 state is held in value of instance variables

 an object can be mutable (state may change) or immutable

 two variables can point to the same object; changing oneaffects the other 

 methods

 a method has a ‘subject’ or ‘target’ object

 may be polymorphic, ie. work on several types of object

 compile-time & runtime types

 an object has a type at runtime: the class of its constructor 

 a variable has a declared, compile-time type or class

 runtime class is subclass of compile-time class

Page 65: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 65/93

65

The Java API

  java.applet

  Applet class

  java.awt

 Windows, buttons,

mouse, etc.

  java.awt.image

 image processing

  java.awt.peer 

 GUI toolkit

  java.io

 System.out.print

  java.lang

 length method for arrays;

exceptions

  java.net

 sockets

  java.util

 System.getProperty

See http://java.sun.com/j2se/1.3/docs/api/for the current APIs

Page 66: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 66/93

66

Page 67: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 67/93

67

Page 68: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 68/93

68

Page 69: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 69/93

69

The package java.lang

 The class Obj ect

 The root class in Java

 Example methods: cl one( ) , equal s( ) ,t oSt r i ng( )

 Subclasses may override these methods

 The class Cl ass

 Example methods: get Name( ) ,get Super Cl ass( )

Page 70: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 70/93

70

Observing an object’s class

voi d pr i nt Cl assName ( Obj ect obj ) {Syst em. out . pr i nt l n( "The cl ass of " + obj +

" i s " + obj . get Cl ass( ) . get Name( ) ) ;}

Page 71: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 71/93

71

Strings in Java

 Strings are not a primitive data type, but

represented as objects.

 Many methods defined in class java.lang:

 Several constructors

 Lots of methods: concat(), equals(), indexOf(), length()

 strings are concatenated with +

 Strings are constants (immutable)

 You can concatenate two strings to produce a new,longer string, using the + operator, but you cannot add,

delete, insert into, or delete from any particular string.

Page 72: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 72/93

72

StringBuffers in Java

 Several methods defined in class

 java.lang:  Constructors can specify length or initial

value  append(), insertf(), length(), toString()

Page 73: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 73/93

73

Java.lang.system  Printstreams

 System.out.err(“Error message”);

 Inputstreams

 System.in.read(inputCharacter)

 System.in.read(inputBuffer, 0, maxChars)

Page 74: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 74/93

74

The Cloneable Interface   A class implements the cl oneabl e interface

by overriding the Obj ect method cl one( )  For example, we could add a cl one( )

method to the FIFO class, if we wanted to be

able to make copies of queues.

Page 75: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 75/93

75

The class java.util  Interface to host OS

 Some basic functions and data structures

 BitSet, Dictionary (the superclass of Hashtable),

Stack, Vector 

 Random number generation

Page 76: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 76/93

76

System Properties  System properties are like UNIX environment

variables, but platform independent  The API class java.util  has methods for 

accessing the system properties

/ / d t i i t i bl

Page 77: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 77/93

77

/ / det er mi ne envi r onment var i abl esi mpor t j ava. ut i l . * ;cl ass envSnoop {

publ i c st at i c voi d mai n ( St r i ng ar gs[ ] ) {Pr oper t i es p;

St r i ng s;p = Syst em. get Pr oper t i es( ) ;p. l i st ( Syst em. out ) ;

s = Syst em. get Pr oper t y( "user . name") ;Syst em. out . pr i nt l n( "user . name="+s) ;s = Syst em. get Pr oper t y( "user . home") ;Syst em. out . pr i nt l n( "user . home="+s) ;

}}

Page 78: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 78/93

78

Java GUI  The awt class allows you to create

 frames

 buttons

 menus and menubars

 checkboxes

 text areas

 scrolling lists

Page 79: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 79/93

79

Java.net  Defines several useful objects:

 URLs

 Internet Addresses

 Sockets

 Datagrams

 packets

 sockets

Page 80: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 80/93

80

Java I/O

 In Java, there is clear distinction between

 streaming in formation to and from a program (bytes, char, binary)

 formatting data (number of decimal places, ints, etc.)

 flexibility comes at the price of more coding

 flexibility implies generality: read from sockets, createreaders/writers with more capabilities

 In C and Fortran this distinction is not there

 can read and format with little verbosity

 flexible in terms of formatting

 price to pay: cannot extend the routines provided by thelanguage to more general situations

 In C++, the iostream file (cin/cout) can be extended at the cost of efficiency

Page 81: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 81/93

81

Efficiency

 scientific computing usually deals with numbers

written to and read from files

 C++

 printf/scanf/fprintf/fscanf are more efficient than cin/cout

 Java

 flexibility comes at the price of efficiency

 use buffered I/O for more efficiency

 Fortran 90/95

 ideally suited to scientific program (its main reason for 

being created)

Page 82: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 82/93

82

Streams  Reader/Writer: abstract classes

 cannot be instantiated

 meant for character streams (mostly unicode)

 unicode: 2 bytes/character (for most languages)

 InputStream/OutputStream: regular class

 for byte input and output

Page 83: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 83/93

83

Reader   Subclasses of Reader (package

 java.io.reader)

 BufferedReader 

 LineNumberReader (subclass of BufferedReader)

 CharArrayReader 

 FilterReader 

 InputStreamReader 

 PipedReader 

 StringReader 

Page 84: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 84/93

84

Writer   Subclasses of Writer (package java.io.writer)

 BufferedWriter 

 CharArrayWriter 

 FilterWriter 

 OutputStreamWriter 

 PipedWriter 

 PrintWriter 

 StringWriter 

Page 85: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 85/93

85

InputStream  Subclasses of InputStream

 ByteArrayInputStream

 FileInputStream

 FilterInputStream

 DataInputStream

 ObjectInputStream

 PipedInputStream

 SequenceInputStream

 StringBufferInputStream

Page 86: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 86/93

86

OuputStream  Subclasses of OuputStream

 ByteArrayInputStream

 FileOutputStream

 FilterOutputStream

 DataOutputStream

 ObjectOutputStream

 PipedOutputStream

 SequenceOutputStream

 StringBufferOutputStream

Page 87: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 87/93

87

 java.io Package  Most (if not all) of the Java I/O classes are

contained in the package java.io  To use these classes, simply insert at the top

of your code (below any package definitions):

import java.io.*

 This will import all the classes (*) in the java.io package

Page 88: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 88/93

88

Unbuffered Reading  FileInputStream os = new

FileInputStream(new File(“gordon”));

Disk/file Read asingle byte

Program

Read 1 byte from the file/disk

Page 89: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 89/93

89

Buffered Reading

BufferedInputStream(InputStream in); // constructor 

BufferedInputStream(InputStream in, int size);BufferedInputStream os = new BufferedInputStream(new File(“gordon”));

String s = os.readLine(); // s=reference, readLine specific to BufferedInputStream

Disk/file Read asingle byte

Program

Read 1 byte from the buffer 

Buffer of n bytes

Page 90: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 90/93

90

Buffered Writing

BufferedOutputStream(OutputStream out); // constructor 

BufferedOutputStream(OutputStream out, int size);void write(byte[] b, int off, int len) throws IOException; // particular method

BufferedOutputStream os = new BufferedOuputStream(new FileInputStream(“gordon”));

Disk/file Read asingle byte

Program

write 1 byte to the buffer 

Buffer of n bytes

Page 91: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 91/93

91

Binary Data

 Consider an int (or float) (4 bytes): float f;

 Computers can write this data to a file in one of twoways:

 BIG_ENDIAN (network order: order used byDataOutputStream)

 byte 1 (msb), byte 2, byte 3, byte 4 (lsb)

 LITTLE_ENDIAN

 byte 4 (lsb), byte 3, byte 2, byte 1 (msb);

 msb: most significant bit

 lsb: least significantn b

 http://www.netrino.com/Embedded-Systems/How-To/Big-Endian-Little-Endian

Page 92: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 92/93

92

Writing Binary// public class DataOutputStream extends FilterOutputStream

// implements DataOutput { // class definition

// DataOutputStream(OutputStream out); // constructor 

DataOutputStream os = new DataOutputStream(new File(“gordon.bin”));

os.writeBytes(“gordon”);

double d=4.5; os.writeDouble(d);

//int j; os.writeInt(j); // will not compile: j is not defined

long lg=3455; os.writeLong(lg);

byte[] b = new byte[100];

… initialize b …

offset=10; len=20;

os.writeBytes(b, offset, len); // write bytes b[9] through b[29]

Page 93: 7. Java.pdf

7/27/2019 7. Java.pdf

http://slidepdf.com/reader/full/7-javapdf 93/93

Reading Binary//DataInputStream(InputStream out);

DataInputStream is = new DataInputStream(new File(“gordon.bin”));

double d = os.readDouble(d);

int j = os.readInt();

long lg = os.readLong(lg);

int offset = 10; len = 30;

byte[] b = new byte[100];os.read(b, off, len); // read len bytes starting from b[offset]

// Cannot read multiple longs, ints, etc. at a given time.

// To do this, one must call writeLong(), etc. multiple times

// This is inefficient since “writeLong()” has a cost associated with calling it

// In C++, fread(char* ptr, int size, int nb, FILE* fd);

// can read n bytes calling the routine once. Therefore, it is expected to be

// quite a bit faster than the Java version.