Upload
gogol-mukherjee
View
218
Download
0
Embed Size (px)
Citation preview
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 1/127
1
Programming in Java
Introduction
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 2/127
2
Java Features
y Java ± no pointers
± Is interpreted (C/C++ are Compiled)
± No Preprocessor
± No #define, #ifdef, #include, «
± Concurrent
± Lots of Libraries
± Internet applications
± R uns on the client side
± Portable
± Secure ± Event Driven
± Easy to Learn
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 3/127
3
Example
y Hello Class Progr ampublic class Hello {public static void main(String argv[]) {
System.out.println(´Hello Class");
System.exit(0);
}
}
y main has a return type of void (not int)
y The System.exit method is used to return value back to OS
y System.out.println is a print statement.
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 4/127
4
Compile/Execute
y The file name should be same as class name
y There can be multiple classes in the same file (For
now, let us consider one class per file)
y Class is same as an Objecty javac <filename> compiles the java code File name
has a . java extension eg. Hello. java
y It produces a class file (contains java byte code for
Java Virtual Machines JVM). Eg. Hello.class
y java <filename without µ.class¶> executes the
progr am
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 5/127
5
Other Utilities
y javap -package java.lang.Integer lists the methods
and variables that are available in the package
java.lang.Integer .
y javap -c <classname>. Produces a byte code of your progr am. Bytecode is written in Java Virtual
Machine.
y Javadoc <filename> produces a HTML file which is
a documentation of your progr am. One can see thedocumentation using a browser .
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 6/127
6
Names and Types
y variables
y functions, methods
y classes or Objects
y Types of variables - int, float, double, boolean
y Arr ays (unlike C or C++, in Java arr ays are treated
as an Object.)
y
Life time of a variable
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 7/127
7
Types of Methods and Variables
y Instance variable. Instance methods
y Static variables and Static Methods
y public, private and protected variables and methods
y Constructor Method
y Automatic Variables
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 8/127
8
Import
y Import Statement ±Without an import statement
java.util.Calendar c1;
± After the import statementimport java.util.Calendar;
...Calendar c1;
± Saves typingimport java.util.*; // Imports all classes
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 9/127
9
Examples
public class f act {
public static int f actorial(int n) {
if (n==0)
return 1
else
return n * f actorial(n-1);
}public static void main(String argv[]) {
int x;
x=9;
³ ´+ +´ ´+
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 10/127
10
Ex pressions
y Arithmetic expressions in Java are similar to C/C++
y Exampleint i = 5 + 12 / 5 - 10 % 3
= 5 + (12 / 5) - (10 % 3)
= 5 + 2 - 1
= 6
± Operators cannot be overloaded in Java
± Integer division vs. floating point division
± Operator precedence
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 11/127
11
Objects
y Objects
y Instances of classes are called objects
y Object variables store the address of an object ± Different from primitive variables (which store the actual value)
± Primitive Data Type exampleint i=3;
int j=i;
i=2; // i==2; j==3
± Object Example1java.awt.Button b1 = new java.awt.Button("OK");
java.awt.Button b2 = b1;b2.setLabel("Cancel"); // Change is visible via b1 also
b1 = new java.awt.Button("Cancel")
y No ex plicit dereferencing (i.e., no &, * or -> operators) ± No pointers±null = "A bsence of reference" = a variable not pointing to an object
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 12/127
12
Programming in Java
Objects, Classes, Program Constructs
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 13/127
13
Program Structure/Environment
y Java ± Is interpreted (C/C++ are Compiled)
± No Preprocessor
± No #define, #ifdef, #include, ...
y Main method (for Java applications) ± Embedded in a Class
public class Xyz {
public static void main (String args[]) {
«
}}
± Each class can define its own main method
± Program¶s starting point depends on how the interpreter is invoked.$ java Xyz
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 14/127
14
Command Line Arguments
y Command Line Args are passed to main methodpublic class Echo {public static void main(String argv[]) {
for (int i=0; i<argv.length; i++)
System.out.print(argv[i] + ´ ´);
System.out.print("\n");
System.exit(0);}
}
y main has a return type of void (not int)
y The System.exit method is used to return value back to OS
y The length property is used to return arr ay size
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 15/127
15
For Statement
y Java¶s for stmt is similar to C/C++, except:
y Comma operator is simulated in Javafor (i=0, j=0; (i<10) && (j<20); i++, j++) {
«
}
± Allowed in initialization and test sections ± Makes Java syntactically closer to C
y Variable declaration ± variables can be declared within for statement, but can¶t be overloaded
int i;
for (int i=0; i<n; i++) { « } // Not valid in Java ± declaration is all or nothing
for (int i=0, j=0; « ) // Declares both i and j
y Conditional must evaluate to a boolean ± Also true for if, while
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 16/127
16
If, While, Do While, Switch
y These are (essentially) the same as C/C++if (x != 2)y=3;
if (x == 3)
y=7;
elsey=8;
if (x >= 4) {
y=2;
k=3;}
while (x<100) {
System.out.println
("X=" + x);x *= 2;
}
do {
System.out.println ("X=" + x);
x *= 2;
} while(x<100);
char c;
...
switch (c) {
case 'Q':
return;case 'E':
process_edit();break;
default:
System.out.println ("Error");}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 17/127
17
Name S pace
y No globals
y variables, functions, methods, constants
y Scope
y Every variable, function, method, constant belongs to a C lassy Every class is part of a P ackage
y Fully qualified name of variable or method<package>.<class>.<member>
± Packages translate to directories in the ³class path´
± A package name can contain multiple componentsjava.lang.String.substring()
COM .Ora. writers.david. wid gets.Barchart.display()
- This class would be in the directory ³XXX/COM/Ora/writers/david/widgets´,
where XXX is a directory in the ³class path´
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 18/127
18
Package; Import
y Package Statement ± S pecifies the name of the package to which a class belongs
package Simple_IO; // Must be the first statement
public class Reader {
«
}
± Optional
y Import Statement ±Without an import statement
java.util.Calendar c1;
± After the import statementimport java.util.Calendar;
...
Calendar c1;
± Saves typingimport java.util.*; // Imports all classes
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 19/127
19
Access R ules
y Packages are accessible ± If associated files and directories exist and have read permission
y Classes and interf aces of a package are accessible ± From any other class in the same package
± P ublic classes are visible from other packages
y Member s of a class (C) are accessible ± [Default] From any class in the same package
± P rivate members are accessible only from C
± P rotected members are accessible from C and subclasses of C
± P ublic members are accessible from any class that can access C
y Local variables declared within a method ± Are not accessible outside the local scope
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 20/127
20
Data Types
y Primitive Types
y Integral (byte, short, char , int, long)±char is unsigned and also used for characters
y Floating Point (float, double)
y boolean
y Classes
y Predefined classes ± String, BigInteger, Calendar, Date, Vector, ...
±Wrapper classes (Byte, Short, Integer, Long, Character)
y User defined classes
y "S pecial" classes ± Arrays
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 21/127
21
Objects
y Objects
y Instances of classes are called objects
y Object variables store the address of an object ± Different from primitive variables (which store the actual value)
± Primitive Data Type exampleint i=3;
int j=i;
i=2; // i==2; j==3
± Object Example1java.awt.Button b1 = new java.awt.Button("OK");
java.awt.Button b2 = b1;b2.setLabel("Cancel"); // Change is visible via b1 also
b1 = new java.awt.Button("Cancel")
y No ex plicit dereferencing (i.e., no &, * or -> operators) ± No pointers±null = "A bsence of reference" = a variable not pointing to an object
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 22/127
22
Objects are handled by R eference
y Objects in Java are handled "by reference"
y Comparison is by reference ± Following is true if b1, b2 point to the same object
if (b1 == b2) { « }
if (b1.equals(b2)) { « } // member by member comparison
y Assignment copies the referenceb1 = b2;
b1.clone(b2); // Convention for copying an object
y Par ameter s passing is always by value
y The value is always copied into the methody For objects, the reference is copied (passed by value)
± The object itself is not copied
± It is possible to change the original object via the reference
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 23/127
23
Parameter Passing Exampleclass ParameterPassingExample {
static public void main (String[] args) {int ai = 99;
StringBuffer as1 = new StringBuffer("Hello");StringBuffer as2 = new StringBuffer("World");
System.out.println ("Before Call: " + show(ai, as1, as2));
set(ai,as1,as2);
System.out.println ("After Call: " + show(ai, as1, as2));
}
static void set (int fi, StringBuffer fs1, StringBuffer fs2) {
System.out.println ("Before Change: " + show(fi, fs1, fs2));
fi=1;
fs1.append(", World");
fs2 = new StringBuffer("Hello, World");
System.out.println ("After Change: " + show(fi, fs1, fs2));
}
static String show (int i, StringBuffer s1, StringBuffer s2) {
return "i=" + i + "s1='" + s1 + "'; s2='" + s2 + "'";
}
}Before Call : i= 99 s1='Hello'; s2='World '
Before Change: i= 99 s1='Hello'; s2='World '
After Change : i= 1 s1='Hello, World '; s2='Hello, World '
After Call : i= 99 s1='Hello, World '; s2='World '
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 24/127
24
Constants
y Constants
y Value of variable is not allowed to change after initialization ± Example
final double PI = 3.14159;
± Initialization can be done after declarationfinal boolean debug_mode;
«if (x<20) debug_mode = true; // Legal
else debug_mode = false; // Legal
«
debug_mode = false; // Error is caught at compile time
± Value of variable cannot change; value of object can changefinal Button p = new Button("OK");
p = new Button ("OK"); // Illegal. P cannot point to
// a different object
p.setLabel ("Cancel"); // Legal.
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 25/127
25
Input/Output
y java.io.OutputStream - A byte output stream ± System.out (C:stdout; C++:cout)
± System.err (C:stderr; C++:cerr)
y Convenience methods: print, println ± send characters to output streams
y java.io.InputStream - A byte input stream ± System.in (C:stdin; C++:cin)
y InputStreamR eader ± R eads bytes and converts them to Unicode characters
y BufferedR eader ± Buffers input, improves efficiency ± Convenience method: readLine()
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader (isr);
String s1 = stdin.readLine();
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 26/127
26
Echo.java
± A version of Echo that reads in data from System.inimport java.io.*;
class Echo {
public static void main (String[] args) throws IOException
{
BufferedR ead er std in = new BufferedR ead er
(new InputStreamR ead er(Syste m.in));String message;
System.out.println ("Enter a line of text:");message = stdin.readLine();
System.out.println ("Entered: \"" + message + "\"");
} // method main
} // class Echo ± java.lang.Integer.parseInt converts a string to an integer
int message_as_int = Integer.parseInt(message);
± java.io.StreamTokenizer handles more advanced parsing
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 27/127
27
Programming in Java
Classes, Inheritance, Interfaces
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 28/127
28
Array Declaration
y Arr ay Declar ation
y Exampleint[] scores = new int[10];
y Variable type is "int[]"
y Elements range from scores[0] « scores[9]
y Automatic bounds checking
y Each array has a public constant, lengthscores.length
- this evaluates to 10
y Alternate declarationsfloat[] prices;float prices[];
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 29/127
29
Arrays
y Initializer lists can be specifiedint[] units = { 147, 323, 89 };
± No new operator used
± No size specified
y Elements of an array can be object referencesStrings[] words = new String[25];
± This reserves space to store 25 references to String objects
± String objects are not automatically created
y Arrays can be passed to methods ± The reference is passed (true for all objects)
y Size of array is not part of type ± A variable of type String[] can store ANY array of Strings, of any size
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 30/127
30
Multi-Dimensional Arrays
y Multi-dimensional arr ays
y A two dimensional array is an array of arraysbyte my_array[][] = new byte[2][5]
± Memory is NOT necessarily contiguous
0,0 0,1 0,2 0,3 0,4 1,0 1,1 1,2 1,3 1,4
[C] 79 87 94 82 67 98 87 81 74 91
0,0 0,1 0,2 0,3 0,4 1,0 1,1 1,2 1,3 1,4
[Java]
79 87 94 82 67 98 87 81 74 91
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 31/127
31
Multi-Dimensional Arrays
y Each row (inner array) is independent of others ± Can reassign part of the array
my_array[1] = new byte[22];
± Each row can have a different size than other rowsint[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28},
{42, 34, 37}, {13, 26, 57, 35} };
± Can have partial declarationsbyte my_partial_array[][] = new byte[3][];
String lots_of_strings[][][][] = new String[5][3][][];
± All missing dimensions MUST be at the endString more_strings[][][] = new String[5][][3]; // Not valid
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 32/127
32
Vectors
y Arr ays
y Once memory is allocated, the array size cannot changeString[] my_array = new String[20];
my_array = new String[10]; // OK; loses pointer to old array
my_array.length = 30; // Not allowed
y java.util.Vector
y Another way to represent list of values ± Size of a Vector can change dynamically
Vector courses = new Vector(20); // Compare to array decl.
courses.addElement ("Lisp");
courses.addElement ("Perl");// courses.addElement (220); // Not allowedcourses.addElement (new Integer(220)); // OK with wrapper
courses.size () // Returns 3
courses.capacity() // returns 20
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 33/127
33
Arrays vs. Vectors
y Differences between Arr ays and Vector s
y Vectors are dynamic (size can change)
y Vector is more like a typical java class ± No special syntax or operators (for ex. No [ ] operator for accessing)
y Can only have Vectors of Objects ± Any object, but« no primitive types
± No strong type checking ( No mechanisms for templates in Java)
± Compiler cannot help prevent "Line objects" from getting into a vector
that should only contain "Point objects"
y Vector s are implemented using an arr ay of Objectprotected Object[] elementData;
± Implications of insert, remove, resize operations
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 34/127
34
Vector
y Constructor sVector(int initialCapacity)
Vector(int initialCapacity, int capacityIncrement)
Vector() // Default initial capacity is 10
y Size/Capacity methodspublic final int capacity();public final synchronized void ensureCapacity(int minCap);
public final synchronized trimToSize();
public final int size();
public final synchronized void setSize(int newSize);
y Methods overridden from Objectpublic synchronized Object clone();
public final synchronized void toString();
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 35/127
35
Vector
y Adding/Removing Elementspublic final void addElement(Object arg);
- Increases size; may increase capacitypublic final boolean removeElement (Object arg);
- Reduces size; returns false if unsuccessful
y Random Accesspublic final Object elementAt (int index)
- Analogous to an array [ ] operator public final void insertElementAt (int index)
public final void removeElementAt (int index)
public final void setElementAt (Object arg, int index)
y Finding objectspublic final int indexOf (Object arg)
public final int indexOf (Object arg, int index)
- Return -1 if object is not found
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 36/127
36
StringTokenizer, StringBuffer
y StringTokenizer class
y StringBuffer class
y Like String, but allows changes ± append
StringBuffer text1 = new StringBuffer ("Hello");text1.append (" World");
± Other useful methodsinsert (int index, char c);
charAt (int index);
setCharAt (int index, char c);
reverse();length();
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 37/127
37
StringBuffer Example
y StringBuffer .append is similar to String.concatpublic class Concat {
public static void main (String[] args) {
String s = new String ("Hello ");
String s2 = s.concat ("World");
StringBuffer sb = new StringBuffer("Hello ");
StringBuffer sb2 = sb.append ("World");
System.out.println ("s: " + s);
System.out.println ("sb: " + sb);System.out.println ("s2: " + s2);
System.out.println ("sb2: " + sb2);}
} // class Concat
y What is the difference?
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 38/127
38
Class Example
y Declar ationimport java.lang.Math;public class Circle {
public int x, y, r; // (x,y) of Center; radius
public double circumference () { return 2 * Math.PI * r; }
public double area () { return Math.PI * r * r; }
}
y UseCircle c;
c = new Circle();
c.r = 2;double a = c.area();
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 39/127
39
Constructors
y Constructor s ± Perform initialization of objects
± Declarationpublic class Circle {private int x, y, r;
public Circ
le
(int ar) {this
.x=0; y=0; r=ar; }« // Note the optional use of "this" above
}
± UseCircle c = new Circle (2);
double a = c.area();
± Can have more than one constructor public Circle (int ax, int ay, int ar) { x=ax; y=ay; r=ar; }
± Can overload the default constructor public Circle () { x=0; y=0; r=1; }
±What if a class does not define ANY constructors?
±What if a class defines constructors, but not one with NO arguments?
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 40/127
40
Constructors
y One constructor can call another (unlike C++)
y Uses "this"public Circle (int ax, int ay, int ar) { x=ax; y=ay; r=ar; }
public Circle (int ar) { this(0, 0, ar); }
y Call to an alternate constructor MUST appear fir sty Before any other statements
y Before variable declarations
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 41/127
41
Class Variables
y Class variablesimport java.lang.Math;public class Circle {
static int nu m Circle = 0;
private int x=0, y=0, r=1; // Notice the initializers
public Circle() { nu m_ circles++; }
public Circle (int ar) { this(); r=ar; }public double circumference () { return 2 * Math.PI * r; }
public double area () { return Math.PI * r * r; }
}
y Referencing Class variables ± From within the class: this.numCircle (or just numCircle)
public Circle() { this.numCircle++; }
± From outside the class: Circle.num_circleCircle c = new Circle();
System.out.println ("# Circles= " + c.numCircle);
System.out.println ("# Circles= " + Circle.numCircle);
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 42/127
42
Class Methods
y Class methodsimport java.lang.Math;public class Circle {
private int x,y,r;
int getX () { return this.x; }
static int nu m Circle = 0;public static int getNumCircle() { return this.numCircle;}
}
y Calling class methods ± From within the class
this.getNumCircle();
± From outside the classCircle c = new Circle();
int n1 = c.getNumCircle();
int n2 = Circle.getNumCircle();
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 43/127
43
(Lack of) Globals
y Java does not allow global variables
y Class variables can substitute for global variables ± Advantage: no possibility of a collision in variable names
± Example declaration in java.lang.Math:public final static double PI;
± Example usage:public double circumference () { return 2 * Math.PI * r; }
System.out.println ("Hello");
y Java does not allow global functions or methods
y
Class methods can substitute for global functions ± Example declaration in java.lang.Integer:public static int parseInt(String str);
± Example usage:int i = Integer.parseInt ("73");
double sqrt_i = Math.sqrt(i);
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 44/127
44
Inheritance
y Need a class with ability to dr aw Circles
y A pproach 1 ( Not ideal)public class GraphicCircle {
// Keep an instance var. to keep circle stuff
public Circle c;
// Delegate functionality to c
public double area() { return c.area(); }
public double circumference () {return c.circumference();}
«
// Add in GraphicCircle specific stuff
public Color outline, fill;public void draw (Graphics page) { « }
}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 45/127
45
Inheritance
y A pproach 2: Inheritance ± A "GraphicCircle" isa (more specific version of) "Circle"
public class GraphicCircle extend s Circle {
// Only need the 'additional' things
Color outline, fill;
public void draw (Graphics page) { « }
}
y Terms and Concepts ± Superclass, base class, parent class
± Subclass, derived class, child class
± isa, Class Hierarchy
± Inheritance of instance variables and methods
GraphicCircle
Circle
GraphicCircleCircle
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 46/127
46
Inheritance
y Gr aphicCircle inherits all variables and methodsGraphicCircle gc = new GraphicCircle ();gc.draw(); // Can invoke GraphicCircle methods
gc.x = 5; // Can access Circle fields
a = gc.area(); // Can invoke Circle methods
y Gr aphicCircle objects are also Circle objectsCircle c;
c = gc; // Assignment is legal
a = c.area(); // Code can treat c as any other Circle
c.draw(); // Illegal (draw is defined in GraphicCircle)
boolean b1, b2;
b1 = (c instanceof GraphicCircle); // Trueb2 = (c instanceof Circle); // True
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 47/127
47
Class Hierarchy
y All classes (except one) have a single superclass ± No multiple inheritance±Object is the default superclass
y Classes and inheritance relationships for m a Tree ± Called Inheritance Hierarchy ± R oot of Tree is Object
± All Java classes are part of this hierarchy
GraphicCircleCircleObject
Number Object
Byte
FloatBoolean
Integer
String
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 48/127
48
Constructor Chaining
y A subclass invokes a superclass constructor
y Ex plicitly - First line is a call to the superclass constructor class GraphicCircle {
«
public GraphicCircle (int r, Color o, Color f) {
super(r); // Must be first linethis.outline = o;
this.fill = f;
}
y Implicitly ± If first line of constructor is not a call to a constructor, super() is
automatically invoked- What if supertype doesn't define a constructor with no arguments?
- What if first line is a call to another constructor of the form this(«)?
y Note: Body of supertype constructor executes first (Like C++)!
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 49/127
49
Overriding Methods
y Subclass can redefine method of superclassclass Circle { «public void reset () { x=0; y=0; r=1; }
}
class GraphicCircle { «
public void reset () {
x=0; y=0; r=1;fill = Color.getColor ("black");
}
}
y Subclass method can call superclass methodclass GraphicCircle { «
public void reset () {super.reset();
fill = Color.getColor("black");
}}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 50/127
50
Polymorphism; Final Modifier
y Actual method to call is deter mined at runtime
y Depends on actual object¶s type (not variable type)Circle[] c[2];
c[0] = new Circle();
c[1] = new GraphicsCircle();
for (int i=0; i<2; i++)c[i].reset();
y C++ requires virtual keyword to implement polymorphism ± C++ default (without keyword): resolution is done at compile time
± Java: methods are ³virtual´ by default polymorphism ± Can use final keyword modifier to enable compile time resolution
class Circle { «
public final void reset () { x=0; y=0; r=1; }}
class GraphicCircle { «
public void reset () { } // No longer valid!
}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 51/127
51
Finalize Methods
y Finalize: Similar to C++ destructor
y A place to clean up an object before memory is deallocated ± Invoked before garbage collection
y Typically used for closing files, releasing resources, etc.
public class FileOutputStream extends OutputStream {« // From java.io.FileOutputStreamprotected void finalize() throws IOException {
if (fd != null) close(); // Closes file descriptor
}
}
y
Not very common in Java (compared to C++) ± Most cleanup is done automatically by the garbage collector
y Not guaranteed to be called ± Program may exit without ever calling the finalizer
± Operating system must free any outstanding resources after exit
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 52/127
52
Finalize Methods
y Java chains constructor methods (like C++
y Java does NOT chain finalize methods ± If you define a finalizer, you should invoke the super¶s finalizer ex plicitly
class GraphicCircle extends Circle { «protected void finalize () {
« local cleanup «super.finalize();
« more local cleanup «
}}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 53/127
53
Visibility Modifiers
y Public, Private, Protected, Packagepublic class Circle { // With mixed visibilitypublic int x; // Public visibility
protected int y; // Protected visibility
int r; // Package visibility (default)
private int numCircle; // Private visibility
int area() { « }}
y Package visibility is default ± classes in same package are friend-ly to each other
Accessible to Public Protected Package Private
Same Class Y Y Y YClass in same package Y Y YSubclass in different package Y YNon-subclass, different package Y
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 54/127
54
Visibility Modifier Guidelines
y Public ± Use this for methods, constants that are part of the public API
± Most variables should not be public
y Protected
± For members that might be useful to subclasses (e.g. Circle¶s x,y,r) ± But not for public use
y Package ± For things that ³cooperating classes´ need access to
y
Private ± Fields and methods that should be hidden from everyone else
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 55/127
55
Circle Class
public class Circle {protected int x=0, y=0, r=1;private static int numCircle=0; // No one has access
/* Constructors */
public Circle () { numCircle++; }
public Circle (int ar) { this(); r=ar; }
// Public way to get to variables (final for optimization)
public final int getNumCircle() { return numCircle; }
public final int getX() { return x; }
public final int getY() { return y; }public final int getR() { return r; }
// Methods to set variablespublic void moveTo (int newx, newy) { x=newx; y=newy; }
public void move (int dx, int dy) { x+=dx; x+=dy; }public void setRadius (double newr) { r = newr; }
}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 56/127
56
Final Classes; A bstract Classes
y Final (no analogy in C++)
y Method ± Cannot be redefined by subclass
y Class
± Cannot be subclassedpublic final class System extends Object { « }
public class MyClass extends System { « } // Not valid
y Abstr act
y Method (analogous to a pure virtual function in C++)
± Must be redefined by subclass
y Class ± Cannot be instantiated
± If a class has an abstract method, it must be declared an abstract class
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 57/127
57
A bstract Class Example
public abstract class Shape {public abstract double area(); // Note: no definitionpublic abstract double circumference();
}
public class Circle extends Shape {
protected int x, y, r;
public Circle(int ar) { r=ar; }
public double area() { return Math.PI * r * r; }public double circumference() { return 2 * Math.PI * r; }
}
public class Rectangle extends Shape {
protected int x, y, w, h;public Rectangle (int aw, int ah) { w=aw; h=ah; }
public double area() { return w * h; }
public double circumference() { return 2 * (w + h); }}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 58/127
58
A bstract Class Example
y Example usagepublic static void main () { «
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(2);shapes[1] = new Rectangle (3,4);
shapes[2] = new Rectangle (2,3);
«double total_area = 0;
for (int i=0; i<shapes.length; i++)total_area += shapes[i].area();
}
y Subclasses of Shape can be assigned to an array of Shape
y Area() method can be invoked on any kind of Shape ± Declared as an abstract method in Shape
± Not valid if area() method was not defined in Shape
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 59/127
59
Inheritance
y Example HierarchyShape - abstract area(), circumference()
Circle - area(), circumference()
GraphicCircle - draw()
Rectangle - area(), circumference()
GraphicRectangle - draw() ±Want to have a Drawable class, with an abstract draw()
y In C++ ± Multiple Inheritance
Circle
Shape
R ectangle
GraphicR ectangle
Drawable
GraphicCircle
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 60/127
60
Interface
y Java
y No multiple inheritance
y Java's solution: interfacepublic interface Drawable {
public void setColor (Color c);
public void setPosition (int x, int y);
public void draw (Graphics dw);
}
y Interf ace
y Looks like an abstract class; simulates some Multi-Inheritance ± But uses keyword interface instead of abstract and class
± All methods are abstract by default ± All instance variables must be constants (static and final)
y Other classes can implement an interface
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 61/127
61
Interface
public class GraphicRectangleextends Rectangle implements Drawable
{
private Color c;
public GraphicRectangle (int w, int h) { super(w,h); }
// Implement each method in Drawable
public void setColor (Color ac) { c = ac; }public void setPosition (int ax, int ay) { x=ax; y=ay; }
public void draw(Graphics dw) { ... }
}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 62/127
62
Using Interfaces
Shape[] shapes = new Shape[3];Drawable[] drawables = new Drawable[3];
GraphicCircle dc = new GraphicCircle(1);
GraphicRectangle dr = new GraphicRectangle (3,4);
GraphicCircle dc2 = new GraphicCircle(3);
// Add them to arraysshapes[0] = dc; drawables[0] = dc;
shapes[1] = dr; drawables[1] = dr;
shapes[2] = dc2; drawables[2] = dc2;
double total_area = 0;
for (int i=0; i<shapes.length; i++) {
total_area += shapes[i].area();drawables[i].setPosition(i*10, i*10);
drawables[i].draw(gc); // Assume gc is defined somewhere}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 63/127
63
Multiple Interfaces
y Each user defined classy Extends exactly one other class
y Implements 0, 1, or more interfacepublic class GraphicRectangle
extends Rectangle
implements Drawable, java.lang.Cloneable,
java.lang.Serializable
{...
}
y
Interf acey Provides a way to simulate multiple inheritance
y Every class that implements an interface MUST define all
methods of that interface
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 64/127
64
Interface Hierarchy
y Interf aces can be subtypes of other interf acesy R esults in an interface hierarchy
± Directed, Acyclic Graph (not a tree, like the class hierarchy)public interface Transformable
extends Scalable, Rotateable, Reflectable { ... }
public interface GraphicObjectextends Drawable, Transformable { ... }
public class Shape implements GraphicObject { ... }
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 65/127
65
Case Study on Inheritance
y Case Study ± Solution: Lewis: ../chap08/applications/Accounts2.java
y Bank_ Account ± Generic account with ability to make deposits and withdrawals
y Savings_ Account ± A kind of Bank_ Account
± Collects interest
y Bonus_ Saver_ Account ± A kind of Savings_ Account
± Collects more interest ± Has penalties for withdrawal
y Checking_ Account ± A kind of Bank_ Account
± Has overdraft protection
Checking_ Account
Bank_ Account
Savings_ Account
Bonus_ Saver_ Account
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 66/127
66
Define Class Hierarchy
public class Bank_Account {...
}
public class Savings_Account extends Bank_Account {
...
}
public class Bonus_Saver_Account extends Savings_Account {
...}
public class Checking_Account extends Bank_Account {
...
}
public class Accounts2 {
public static void main (String[] args) {... Create objects and test out class hierarchy ...
}}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 67/127
67
Define Methods
public class Bank_Account {public Bank_Account(int account_num,double init_bal) {...}public void deposit (double amount) { ... }
public void withdrawal (double amount) { ... }
}
public class Savings_Account extends Bank_Account {
public void add_interest () { ... }}
public class Bonus_Saver_Account extends Savings_Account {
public void withdrawal (double amount) { ... penalty ... }public void add_interest () { ... give bonus rate ... }
}
public class Checking_Account extends Bank_Account {
public void withdrawal (double amount){ ... check for overdraft ... }
}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 68/127
68
Define Methods (Details)
public class Bank_Account {protected int account;protected double balance;
public Bank_Account(int account_num,double init_bal) {...}
Bank_Account a B A = new Bank_Account(4321, 100.00);
public void deposit (double amount) { ... }a B A.deposit (50.00);
public void withdrawal (double amount) { ... }
a B A.withdraw (20.00);}
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 69/127
69
Define Methods (Details, cont.)
public class Savings_Account extends Bank_Account {protected double rate;
public Savings_Account (int account_num,
double initial_balance,
double interest_rate) { ... }
S avings_Account a S A = new S avings_Account (1234, 100.00, 0.05);
public void add_interest () { ... }a S A.add_interest();
}
public class Bonus_Saver_Account extends Savings_Account {public Bonus_Saver_Account (int account_num,
double initial_balance,
double interest_rate) { ... } Bonus_ S aver_Account a BS A = new Bonus_ S aver_Account (1234, 100.00, 0.05);
public void withdrawal (double amount) { ... penalty ... }
a BS A.withdraw ( 20.00 );public void add_interest () { ... give bonus rate ... }
a BS A.add_interest ();}
fi h d ( il )
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 70/127
70
Define Methods (Details, cont.)
public class Checking_Account extends Bank_Account {private Savings_Account overdraft;
public Checking_Account (int account_number,
double initial_balance,
Savings_Account protection) {...}
Checking_Account aCA = new Checking_Account (87323, 75.00, a BS A);
public void withdrawal (double amount) {
if (checking account has enough funds)
take funds out of checking accountelse if overdraft account has enough funds
take funds out of overdraft account
elseprint error "Insufficient funds"
}
aCA.withdraw (20.00);}
k A
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 71/127
71
Bank_ Account
class Bank_Account {protected int account;protected double balance;
public Bank_Account (int account_num, double init_bal) {
account = account_num;
balance = initial_balance;
} // constructor Bank_Account
public void deposit (double amount) {
balance += amount;
System.out.println("Deposit into account " + account);System.out.println("Amount: " + amount);
System.out.println("New balance: " + balance);
System.out.println();} // method deposit
// ... rest is on next slide
B k A ( )
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 72/127
72
Bank_ Account (cont.)
public boolean withdrawal (double amount) {boolean result = false;System.out.println("Withdrawal from account " + account);
System.out.println ("Amount: " + amount);
if (amount > balance)
System.out.println ("Insufficient funds.");
else {balance -= amount;
System.out.println ("New balance: " + balance);
result = true;
}System.out.println();
return result;} // method withdrawal
} // class Bank_Account
S i A
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 73/127
73
Savings_ Account
class Savings_Account extends Bank_Account {protected double rate;
public Savings_Account (int account_num,
double initial_balance,
double interest_rate) {
super (account_num, initial_balance);
rate = interest_rate;} // constructor Savings_Account
public void add_interest () {
balance += balance * rate;System.out.println ("Interest added to account: " +
account);
System.out.println ("New balance: " + balance);System.out.println();
} // method add_interest} // class Savings_Account
B S A
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 74/127
74
Bonus_ Saver_ Account
class Bonus_Saver_Account extends Savings_Account {private final int PENALTY = 25;private final double BONUS_RATE = 0.03;
public Bonus_Saver_Account (int account_num,
double initial_balance,
double interest_rate) {
super (account_num, initial_balance, interest_rate);} // constructor Super_Saver_Account
public boolean withdrawal (double amount) {
System.out.println ("Penalty incurred: " + PENALTY);return super.withdrawal (amount+PENALTY);
} // method withdrawal
B S A ( )
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 75/127
75
Bonus_ Saver_ Account (cont.)
public void add_interest () {balance += balance * (rate + BONUS_RATE);System.out.println ("Interest added to account: " +
account);
System.out.println ("New balance: " + balance);
System.out.println();
} // method add_interest
} // class Bonus_Saver_Account
Ch ki A t
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 76/127
76
Checking_ Account
class Checking_Account extends Bank_Account {
private Savings_Account overdraft;
public Checking_Account (int account_number,
double initial_balance,
Savings_Account protection) {
super (account_number, initial_balance);overdraft = protection;
} // constructor Checking_Account
// ... continued on next slide
Ch ki A t ( t )
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 77/127
77
Checking_ Account (cont.)
//...public boolean withdrawal (double amount) {boolean result = false;
if ( ! super.withdrawal (amount) ) {
System.out.println ("Using overdraft...");
if ( ! overdraft.withdrawal (amount-balance) )
System.out.println("Overdraft funds insufficient.");
else {balance = 0;
System.out.println ("New balance on account " +
account + ": " + balance);
result = true;}
}
System.out.println ();return result;
} // method withdrawal} // class Checking_Account
M i
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 78/127
78
Main
class Accounts2 {public static void main (String[] args) {Savings_Account savings =
new Savings_Account (4321, 5028.45, 0.02);
Bonus_Saver_Account big_savings =
new Bonus_Saver_Account (6543, 1475.85, 0.02);
Checking_Account checking =
new Checking_Account (9876, 269.93, savings);
savings.deposit (148.04);
Deposit into account 4321
Amount: 148.04
New balance: 5176.49big_savings.deposit (41.52);
Deposit into account 6543 Amount: 41.52
New balance: 1517.37
M i ( t )
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 79/127
79
Main (cont.)
savings.withdrawal (725.55);Withdrawl from account 4321
Amount: 725.55
New balance: 4450.94big_savings.withdrawal (120.38);
Penalty incurred: 25
Withdrawl from account 6543
Amount: 145.38 New balance: 1371.9899999999998
checking.withdrawal (320.18);
Withdrawl from account 9876
Amount: 320.18
Insufficient funds.
Using overdraft...Withdrawl from account 4321
Amount: 50.25
New balance: 4400.69
New balance on account 9876: 0.0} // method main
} // class Accounts2
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 80/127
80
Programming in Java
Collections
C t t
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 81/127
81
Contents
y Collections, Iter ationy The Collection Interf ace
y Set and SortedSet
y List
y Queue
y Map and SortedMap
y Enum Collections
y Wr apped Collections and the Collections Class
y Writing Iter ator Implementations
y The Legacy Collection Types
Collections
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 82/127
82
Collections
y Collections are holder s that let you store and organize objects in usefulways for efficient access.
y In the package java.util, there are interf aces and classes that provide a generic collection fr amework.
y The Collections interf aces: Collection<E>, Set<E>, SortedSet<E>,List<E>, Queue<E>, Map<K,V>, SortedMap<K,V>, Iter ator<E>,ListIter ator<E>, Iter able<E>
y Some useful implementations of the interf aces: HashSet<E>,TreeSet<E>, Arr ayList<E>, LinkedList<E>, HashMap<K,V>,TreeMap<K,V>, WeakHashMap<K,V>
y Exception Convetions:y UnsupportedOperationException
y ClassCastException
y IllegalArgumentException
y NoSuchElementException
y NullPointer Exception
T T f C ll ti
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 83/127
83
Type Trees for CollectionsIter able<E>
Arr ayList<E>
Collection<E>
Set<E> Queue<E> List<E>
SortedSet<E> PriorityQueue<E>
HashSet<E>
EnumSet<E>
LinkedHashSet<E>
TreeSet<E>
LinkedList<E>
Iter ator<E>
ListIer ator<E>
EnumMap<K,V>
Map<K,V>
WeakHashMap<K,V>SortedMap<K,V>
TreeMap<K,V>
HashMap<E>
LinkedHashMap<K,V>
Th C ll ti F k
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 84/127
84
The Collections Framework
y
The Java collection fr amework is a set of generic types that are used to createcollection classes that support various ways to store and manage objects of anykind in memory.
y A generic type for collection of objects: To get static checking by the compiler for whatever types of objects to want to manage.
Generic Class/Interf ace Type Description
The Iter ator<T> i terf e ty e Decl r es ethods f or iter ti thr ough elements of collection, one t time.
The Vector<T> ty e Supports n rr y-li e str uctur e f or storing ny type of object. The number of objects to be stor ed incr eases automatically as necessary.
The Stack<T> type Supports the stor age of any type of object in a pushdown stack.
The LinkedList<T> type Supports the stor age of any type of object in a doubly-linked list, which is a list thatyou can iter ate though f or war ds or backwar ds.
The HashMap<K,V> type Supports the stor age of an object of type V in a hash table, sometimes called a map. The object is stor ed using an associated key object of type K. To r etrieve an object you
just supply its associated key.
Generic Types
C ll ti f Obj t
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 85/127
85
Collections of Objects
Three Main Types of Collections
Sets
Sequences
Maps
Sets
The simple kinds of collection
The objects are not ordered in any particular way.
The objects are simply added to the set without any control over wherethey go.
Collections of Objects
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 86/127
86
Collections of Objects
Sequences The objects are stored in a linear fashion, not necessarily in any particular order, but in an arbitrary fixed sequence with a beginning and an end.
Collections generally have the capability to expand to accommodate asmany elements as necessary.
The various types of sequence collections
Array or Vector
LinkedList
Stack
Queue
Collections of Objects
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 87/127
87
Collections of Objects
Maps Each entry in the collection involves a pair of objects.
A map is also referred to sometimes as a dictionary.
Each object that is stored in a map has an associated key object, and the
object and its key are stored together as a ³name-value´ pair.
It t d Li tIt t
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 88/127
88
Iterators and ListIterators
y Iter ator<E> interf acey T next()
y boolean hasNext()
y void remove()
y ListIter ator<E> interf ace
y
extends Iterator y T next()
y boolean hasNext()
y int nextIndex()
y T previous()
y boolean has P revious()
y int previousIndex()
y void remove()
y void add( T obj)
y void set( T obj)
public void removeLongStrings(Collection<? Extends String> coll, intmaxLen) {
Iter ator<? Extends String> it = coll.iter ator();
while (it.hasNext()) {
String str = it.next();
if (Str .length() > maxLen) it.remove();
}
}
ListIter ator<String> it =list.listIter ator(list.size());
while (it.hasPrevious()) {
String obj = it.previous();
System.out.println(obj);
// « use obj «.
}
C bl d C t
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 89/127
89
Comparable and Comparator
y The interf ace java.lang.Compar able<T> can be implementedby any class whose objects can be sorted.
y public int compareTo (T other): return a value that is less than,equal to, or greater than zero as this object is less than, equal to,or greater than the other object.
y If a given class does not implement Compar able or if its natur al ordering is wrong for some purpose,
java.util.Compar ator object can be used
y public int compare(T o1, T o2)
y
boolean equals(Object obj)
The Collection Interface
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 90/127
90
The Collection Interface
y The ollection Interf acey The basis of much of the collection
system is the Collection interface.
y Methods:
y
public int size()y public boolean isEmpty()
y public boolean contains(Object
elem)
y public Iterator<E> iterator()
y public Object[] toArray()
y public <T > T [] toArray( T [] dest)
y public boolean add(E elem)
y public boolean remove(Object elem)
String[] strings = newString[collection.size()];
strings = collection.toArray(strings);
String[] strings = collection.toArray(newString[0]);
y public boolean
containsAll( C ollection<?> coll)y public boolean addAll( C ollection<?
extends E> coll)
y public booleanremoveAll( C ollection<?> coll)
y public boolean retainAll( C ollection<?>coll)
y
public void clear()
Collection Classes
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 91/127
91
Collection Classes
y
Classes in Sets:y H ashSet<T >
y Linked H ashSet<T >
y T reeSet<T >
y EnumSet<T extends Enum<T >>
y Classes in
Lists:
y T o define a collection whose elementshave a defined order-each element existsin a praticular poistion the collection.
y Vector<T >
y Stack<T >
y LinkedList<T >
y ArrayList<T >
y
Class in Queues:y F I F O ordering
y P riorityQueue<T >
y Classes in Maps:
y Does not extend C ollection because it has a contract that is different inimportant ways: do not add an element
to a Map(add a key/value pair), and a Map allows looking up.
y H ashtable<K,V>
y H ashMap<K,V>
y Linked H ashMap<K,V>
y Weak H ashMap<K,V>
y
Identity H
ashMap<K,V>y T reeMap<K,V> : keeping its keys sorted
in the same way as T reeSet
Writing Iterator Implementations
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 92/127
92
Writing Iterator Implementations
³ShortStrings.java´
import java.util.*;
public class ShortStrings implements Iter ator<String> {
private Iter ator<String> strings ; // source for stringsprivate String nextShort; // null if next not known
private final int maxLen; // only return strings <=
public ShortStrings(Iter ator<String> strings, int maxLen) {this.strings = strings;
this.maxLen = maxLen;nextShort = null;
}
public boolean hasNext() {if (nextShort != null) // found it already
return true;while (strings.hasNext()) {
nextShort = strings.next();if (nextShort.length() <= maxLen) return true;
}nextShort = null; // did not find one
return f alse;
}
public String next() {
if (nextShort == null && !hasNext())throw new NoSuchElementException();
String n = nextShort; // remember nextShort
nextShort = null;return n;
}
public void remove() {throw new UnsupportedOper ationException();
}}
³ShortStringsTest.java´
import java.util.*;public class ShortStringsTest {
public static void main(String[] args) {LinkedList<String> myList = new LinkedList<String>();
myList.add("Fir st String");myList.add("Second Second String");
myList.add("Third Third Third String");myList.add("Fourth Fourth Fourth Fourth String");
myList.add("Fifth Fifth Fifth Fifth Fifth String");
ShortStrings myShort = new ShortStrings(myList.iter ator(), 25);// for (String val : myShort) // Why not able ?
while(myShort.hasNext()) {
System.out.println("Short String = " + myShort.next());}} }
}
Result:Short String = Fir st StringShort String = Second Second StringShort String = Third Third Third String
Binary Tree Example Using Collection
F k
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 93/127
93
Framework
³Linked
List.java´public class LinkedList<T> implements
Iter able<T> {
«.
public Iter ator<T> iter ator() {
return new ListIter ator();
}
private class ListIter ator implements Iter ator<T> {
«.
}
«.
} // end of LinkedList
³BinaryTr ee.java´public class BinaryTree<T extends
Compar able<T>> {
some_ add_ method_for tree(T value, Node node) {
// callnode.obj.compareTo(value);
}
class Node {
«
T obj;
«
}
}Read the codes of ³LinkedList.java´, BinaryTr ee.java, and TryBinaryTr ee.java
car ef ully. nd compar e this to the contents of the slide #13.
And Run TryBinaryTr ee.
Th L C ll ti T
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 94/127
94
The Legacy Collection Types
y Enumer ation
y Analogous to Iterator.y Vector
y Analogous to ArrayList, maintains an ordered list of elements that are stored inan underlying array.
y Stack
y Analogous of Vector that adds methods to push and pop elements.
y Dictionary
y Analogous to the Map interface, although Diectionary is an abstract class, not aninterface.
y Hashtable
y Analogous HashMap.
y Propertiesy A subclass of Hashtable. Maintains a map of key/value pairs where the keys and
values are strings. If a key is not found in a properties object a ³default´ properties object can be searched.
Vector (Before 1 5)
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 95/127
95
Vector (Before 1.5)class VectorDemo {
public static void main(String args[]) {
// Create a vector and its elements Vector vector = new Vector();vector.addElement(new Integer(5));vector.addElement(new Float(-14.14f));vector.addElement(new String("Hello"));vector.addElement(new Long(120000000));vector.addElement(new Double(-23.45e-11));
// Display the vector elementsSystem.out.println(vector);
// Insert an element into the vectorString s = new String("String to be inserted");vector.insertElementAt(s, 1);System.out.println(vector);
// Remove an element from the vectorvector.removeElementAt(3);System.out.println(vector);
}}
Result :[5, -14.14, Hello, 120000000, -2.345E-10][5, String to be inserted, -14.14, Hello,120000000, -2.345E-10][5, String to be inserted, -14.14, 120000000, -2.345E-10]
Integer Float String Long
Vector
Vector (Using Generic Type)
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 96/127
96
Vector (Using Generic Type)
import java.util.Vector;
import java.util.ListIter ator;
import java.io.BufferedReader;
import java.io.InputStreamReader;import java.io.IOException;
classPer son {
// Constructor public Per son(String fir stName, String surname) {
this.fir stName = fir stName;
this.surname = surname;
}
public String toString() {
return fir stName + " " + surname;
}
private String fir stName; // Fir st name of per sonprivate String surname; // Second name of per son
}
public class TryVector {
public static void main(String[] args) {Per son aPer son = null; // A per son object
Vector<Per son> filmCast = new Vector<Per son>();
// Populate the film castfor( ; ; ) { // Indefinite loop
aPer son = readPer son(); // Read in a film star
if(aPer son == null) { // If null obtained...
break; // We are done...}
filmCast.add(aPer son); // Otherwise, add to the cast}
int count = filmCast.size();
System.out.println("You added " + count +
(count == 1 ? " per son": " people") + " to the cast.\n");
System.out.println("The vector currently has room for "+ (filmCast.capacity() - count) + " more people.\n");
// Show who is in the cast using an iter ator
ListIter ator<Per son> thisLot = filmCast.listIter ator();
while(thisLot.hasNext()) { // Output all elementsSystem.out.println( thisLot.next());
}
}
// Read a per son from the keyboard
static Per son readPer son() {
// Read in the fir st name and remove blanks front and back
String fir stName = null;String surname = null;
System.out.println(
"\nEnter fir st name or ! to end:");
try {fir stName = keyboard.readLine().trim(); // Read and trim a string
if(fir stName.charAt(0) == '!') { // Check for ! entered
return null;
} // If so, we are done...
// Read in the surname, also trimming blanks
System.out.println("Enter surname:");
surname = keyboard.readLine().trim(); // Read and trim a string
} catch(IOException e) {
System.err .println("Error reading a name.");
e.printStackTr ace();System.exit(1);
}
return new Per son(fir stName,surname);
}
static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
}
Try TryVector .java
What ar e diff er ences to those of the V1.4?
Hashtable (Before 1 5)
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 97/127
97
Hashtable (Before 1.5)class HashtableDemo {
public static void main(String args[]) {
Hashtable hashtable = new Hashtable();
hashtable.put("apple", "red");hashtable.put("str awberry", "red");
hashtable.put("lime", "green");
hashtable.put("banana", "yellow");
hashtable.put("or ange", "or ange");
Enumer ation e = hashtable.keys();
while(e.hasMoreElements()) {
Object k = e.nextElement();Object v = hashtable.get(k);
System.out.println("key = " + k +
"; value = " + v);}
System.out.print("\nThe color of an apple is: ");
Object v = hashtable.get("apple");
System.out.println(v);
}}
Result :Result #2
key = lime; value = green
key = str awberry; value = red
The color of an apple is: red
Key
Value
The Hashtable<k,V> class inherits from
the Dictionary class, and implement the
Map interf ace. All methods of it aresynchronized, unlike HashMap.
Here, you will meet warning messageof unchecked type. How can we solvethis?
Hashtable<K V> (1 5)
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 98/127
98
Hashtable<K,V> (1.5)import java.util.*;
class HashtableDemoGen {
public static void main(String args[]) {Hashtable<String,String> hashtable = new
Hashtable<String,String>();
hashtable.put("apple", "red");
hashtable.put("str awberry", "red");
hashtable.put("lime", "green");
hashtable.put("banana", "yellow");
hashtable.put("or ange", "or ange");
for (Enumer ation<String> e = hashtable.keys() ;
e.hasMoreElements() ;) {
String k = e.nextElement();
String v = hashtable.get(k);
System.out.println("key = " + k +
"; value = " + v);
}
System.out.print("\nThe color of an apple is: ");
String v = hashtable.get("apple");
System.out.println(v);
}
}
Parameterized Type
The Hashtable<k,V> class inherits from the Dictionary
class, and implement the Map
interf ace.All methods of it are
synchronized, unlike HashMap.
Miscellaneous Utilities
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 99/127
99
Miscellaneous Utilities
y For matter ± A class for producing for matted text.
y BitSet ± A dynamically sized bit vector
y Obser ver/Obser vable ± An interf ace/class pair that enables anobject to be obser vable by having one or more Obser ver objects thatare notified when something interesting happens in the Obser vableobject.
y Random ± A class to gener ate sequences of pseudor andom number s.
y Scanner ± A class for scanning text and par sing it into values of primitive types or strings, based on regular expression patterns.
y StringTokenizer ± A class that splits a string into tokens based ondelimiter s(by def ault, whitespace)
y Timer/Timer Task ± A way to schedule tasks to be run in the future.
y UUID ± A class that represents a univer sally unique identifier(UUID)
y Math ± A class perfor ming basic mathematical oper ations, such as trigonometric functions, exponentiation, logr aithms, and so on.
y StricMath ± Defines the same methods as Math but guar antees thesue of specific algorithms that ensure the same results on everyvirtual machine.
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 100/127
100
Programming in JavaThreads
A single threaded program
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 101/127
101
A single threaded program
class ABC{
«.
public void main(..)
{«
..
}
}
begin
body
end
A Multithreaded Program
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 102/127
102
A Multithreaded Program
Main Thread
Thread A Thread B Thread C
start start start
Threads may switch or exchange data/results
Single and Multithreaded Processes
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 103/127
103
Single and Multithreaded Processes
Single-threaded Process
Single instruction stream Multiple instruction stream
Multiplethreaded Process
Threads of
Execution
Common
Address S pace
threads are light-weight processes within a process
What are Threads?
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 104/127
104
What are Threads?
y A piece of code that run in concurrent with other threads.y Each thread is a statically ordered sequence of instructions.
y Threads are being extensively used express concurrency on
both single and multiprocessor s machines.
y Progr amming a task having multiple threads of control ±Multithreading or Multithreaded Progr amming.
Java Threads
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 105/127
105
Java Threads
y Java has built in thread support for Multithreadingy Synchronization
y Thread Scheduling
y
Inter-Thread Communication:y currentThread start setPriority
y yield run getPriority
y sleep stop suspend
y resume
y Java Garbage Collector is a low-priority thread.
Threading Mechanisms...
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 106/127
106
Threading Mechanisms...
y Create a class that extends the Thread classy Create a class that implements the Runnable interf ace
1st method: Extending Thread class
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 107/127
107
1st method: Extending Thread class
y Threads are implemented as objects that contains a method called run()class MyThread extends Thread
{
public void run()
{
// thread body of execution
}}
y Create a thread:MyThread thr1 = new MyThread();
y Start Execution of threads:thr1.start();
y Create and Execute:new MyThread().start();
An example
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 108/127
108
An example
class MyThread extends Thread { // the thr eadpublic void r un() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread
class ThreadEx1 { // a pr ogr am that utilizes the thr eadpublic static void main(String [] args ) {
MyThr ead t = new MyThr ead();
// due to extending the Thread class (above)
// I can call start(), and this will call
// run(). start() is a method in class Thread.t.start();
} // end main()
} // end class ThreadEx1
2nd method: Threads by implementing Runnable interface
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 109/127
109
2nd method: Threads by implementing R unnable interface
class MyThread implements Runnable{
.....
public void run()
{
// thread body of execution
}
}
y Creating Object:
MyThread myObject = new MyThread();
y Creating Thread Object:
Thread thr1 = new Thread( myObject );y Start Execution:
thr1.start();
An example
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 110/127
110
An example
class MyThread implements Runnable {public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread
class ThreadEx2 {
public static void main(String [] args ) {
Thr ead t = new Thr ead(new MyThr ead());
// due to implementing the Runnable interf ace
// I can call start(), and this will call run().t.start();
} // end main()
} // end class ThreadEx2
Life Cycle of Thread
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 111/127
111
e Cyc e o ead
new
runnable non-runnable
dead
wait()
sleep()
suspend() blocked
notify()slept
resume()
unblocked
start()
stop()
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 112/127
112
Programming in JavaGraphics and Graphical User Interfaces
Display of AkmMimic
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 113/127
113
p y
Classes used in Mimic
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 114/127
114
Appl
a l
ai
T i l
T mponent La el tton
Component
Object
Display Components
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 115/127
115
p y p
y Basic code to display componentsimport java.applet.Applet;import java.awt.*;
public class AkmMimic extends Applet {
public void init () {
this.add (new TextField(20));this.add (new Label ("No news is good news"));
this.add (new Button ("OK"));
}
}
y Applet is a type of Container
y Can add components to containers
y Container takes care of "laying out the components"
y Default behavior for A pplets is "Flow Layout" ± Left to right, goes to new rows as necessary
Events
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 116/127
116
y Events can occur on Componentsy There are many types of events
± Action, Mouse, Key, Focus, Paint, Window
y Listener s watch for events on component
y Listeners in Java are interfaces ± (must be implemented by a class)
y Examples: ± ActionListener, MouseListener, MouseMotionListener
y
Listener s are passed Event objectsy Event objects contain information (e.g. x,y position of mouse)
y Examples ± ActionEvent, MouseEvent, KeyEvent
Events
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 117/127
117
y Different components can gener ate different eventsy Button, List, TextField, MenuItem
± generate ActionEvents
y Any component can generate MouseEvents
y To handle events, have to add listener sButton b = new Button ("OK");
ActionListener al = « create an action listener «b.addActionListener (al);
y ActionListener is an interf ace
y Need a class that implements the interfacepublic abstract interface ActionListener
extends EventListener {
public abstract void actionPerformed (ActionEvent e);}
Listening to the OK button
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 118/127
118
g
import java.applet.Applet;
import java.awt.*;
i m port java.a wt.event.*;
public class AkmMimic extends Applet {
public void init () {
this.add (new TextField(20));
this.add (new Label ("No news is good news"));Button b = new Button ("OK");
ActionListener al = new OK _ Handler();
b.add ActionListener (al);
this.add ( b);
}
}
class OK _ Handler i m ple m ents ActionListener {
public void actionPerfor m ed (ActionEvent e) {
Syste m.out. println ("You pressed OK");
}
}
A pplets can also Listen
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 119/127
119
pp
import java.applet.Applet;
import java.awt.*;import java.awt.event.*;
public class AkmMimic extends Applet
i m ple m ents ActionListener {
public void init () {
this.add (new TextField(20));this.add (new Label ("No news is good news"));
Button b = new Button ("OK");
b.add ActionListener (this);
this.add (b);}
pub
lic void actionPerfor m ed (ActionEvent e) {Syste m.out. println ("You pressed OK");
}
}
Copying from TextField to Label
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 120/127
120
py g
import java.applet.Applet;
import java.awt.*;import java.awt.event.*;
public class AkmMimic extends Applet
implements ActionListener {
TextField textfield = new TextField(20);
Label label = new Label ("No news is good news");public void init () {
this.add (textfield);
this.add (label));
Button b = new Button ("OK");b.addActionListener (this);
this.add (b);
}
public void actionPerformed (ActionEvent e) {label.setText (textfield.getText());
}
}
Listeners
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 121/127
121
y Some listener s have multiple methodspublic abstract interface MouseListenerextends EventListener {
public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);public abstract void mouseReleased(MouseEvent e);
};
y Classes that implement interf aces
y MUST define code for all methods of the interface
± If you only need code in one method, solution isn't clean
Handling Mouse Events
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 122/127
122
gimport java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class AkmMimic extends Applet {
public void init () {
this.add (new TextField(20));
this.add (new Label ("No news is good news"));
this.add (new Button("OK"));this.addMouseListener (new MyMouseHandler());
}
}
class MyMouseHandler implements MouseListener {public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) {
System.out.println ("You pressed a mouse button");}
public void mouseReleased(MouseEvent e) { }
}
Using Adapters to Listen
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 123/127
123
g p
y For most listener s, there is a corresponding adapter class MouseAdapter implements MouseListener {public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }}
y You can reuse these, and only implement
necessary methodsclass MyMouseHandler extends MouseAdapter {public void mousePressed (MouseEvent e) {
System.out.println ("You pressed a mouse button");}
}
Using MouseAdapter
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 124/127
124
mport java.applet.Applet;
import java.awt.*;import java.awt.event.*;
public class AkmMimic extends Applet {
public void init () {
this.add (new TextField(20));
this.add (new Label ("No news is good news"));this.add (new Button("OK"));
this.addMouseListener (new MyMouseHandler());
}
}
class MyMouseHandler extend s MouseA da pter {
pub
lic void m ousePressed (Mo
useEvent e) {
Syste m.out. println ("You pressed a m ouse button");
}
}
Too many classes
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 125/127
125
y A typical GUI has many buttons, components, menuitems, etc.
y Need a different class for each listener
y Too many classes
y Confuses name space
y Java's solution
y Anonymous, inner classes ± Class is embedded in another class
± Class does not have to have a name provided by developer
Anonymous Classes
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 126/127
126
import java.applet.Applet;
import java.awt.*;import java.awt.event.*;
public class AkmMimic extends Applet {
public void init () {
this.add (new TextField(20));
this.add (new Label ("No news is good news"));this.add (new Button("OK"));
this.add MouseListener (new MouseA da pter () {
public void m ousePressed (MouseEvent e) {
Syste m.out. println ("You pressed a m ouse button");
}});
}
}
Left, R ight, or Middle Button?
8/6/2019 Core Java at a Glance
http://slidepdf.com/reader/full/core-java-at-a-glance 127/127
import java.applet.Applet;
import java.awt.*;import java.awt.event.*;
public class AkmMimic extends Applet {
public void init () {
this.add (new TextField(20));
this.add (new Label ("No news is good news"));this.add (new Button("OK"));
this.addMouseListener (new MouseAdapter () {
public void mousePressed(MouseEvent e) {
if (e.isMetaDown()) {System.out.println ("Right mouse button pressed");
} else if (e.isAltDown()) {
System.out.println ("Middle mouse button pressed");} else {
System.out.println ("Left mouse button pressed");}
}});