Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Introduction to Object-Oriented
Programming and Java
1
Java Historical Aspects
Software engineers tried to write
portable software
April 1991, “Green” conducted by Sun
to develop a system for developing
consumer electronics’ logic
– realized the needs of a platform
independent environment.
2
Historical Aspects, cont..
May 23, 1995 the Java Environment
was announced by Sun Microsystems.
Popular browsers, such as Netscape
Navigator and Internet Explorer,
incorporate Java-based technology.
Stand alone environments developed.
3
Versions of Java
Three major versions released by Sun:
Java 1.0.2 - still most widely supported
by browsers
Java 1.1.5 Spring 1997, improvements
to user interface, event handling.
Java 2 - released in December 1998.
Check:
http://java.sun.com
for JDK
4
Java 2
Swing - new features for creating a
graphical user interface
Improvements to audio features
Drag and drop
5
Introduction to Java
Java Overview
– Java is a (relatively) New Object-Oriented
Programming Language.
– Designed for the network.
– Java syntax is simple.
– Java is platform neutral.
6
Introduction to Java
Java Overview
– Secure, High performance.
– Multi-Threaded.
– Java is defined with a very comprehensive
class and object libraries (packages).
7
Introduction to Java
New Object-Oriented Language
– All data structures, and programs that
operate on it are encapsulated in the
context of objects.
– Code reuse is supported by Java's
inheritance properties.
8
Introduction to Java
Designed to run on the net.
– Net could be the Internet or an Intranet.
– Built-in networking capability in a language
package Java.net
– Support client/server computing between
different computers.
9
Introduction to Java
Java is relatively simple yet powerful
– Java’s syntax is based on C & C++ syntax
that makes it easy to learn.
– Java forbids the use of pointers. Java
automatically handles the referencing and
de-referencing of objects. Eliminates
memory leaks.
– Rich pre-defined classes for I/O, net, &
graphics.
10
Introduction to Java
Java can be “platform neutral”.
– Java can be an interpreted language.
Programs are interpreted to an
intermediate optimized form called “bytecode”
– The run-time interpreter reads the bytecode and executes using a model of an
abstract machine (JVM).
11
Introduction to Java
Java can be “platform neutral”.
– Java virtual machine converts byte-code to
the specific machine code.
– JVM & interpreter perform a very strong
type checking.
– Built-in Java memory model that performs
“garbage collection” to prevent memory
leaks.
12
Introduction to Java
Java Applet Security.
– No Pointers.
– Memory allocations and de-allocations are
handled by JVM.
– Byte-code verification every time an applet
is loaded.
13
Introduction to Java
High Performance
– Compared to other interpreted languages
such as Basic, Visual Basic, etc. Java is
much faster.
– Although 20 times slower then C/C++, with
JIT-compilers Java’s speed is somewhat
comparable.
– Compiled Java is as fast as other compiled
languages
14
Introduction to Java
Java is Multi-Threaded
– Native support for multi-tasking in the form
of multi-threading.
Multi-Threading = Several lines of execution
run independently and simultaneously.
15
Introduction to Java
Class is the basic building block
– The reserved word class indicates the
beginning of a new class
Syntax: (constructs in [ ] are optional)
[<qualifier>] class classname [extends
classname1] [implements interfacename]
{
….. Class body;
}
16
Introduction to Java
<class_qualifier> is one of the following
reserved keywords
– public
– private
– abstract
– final
17
Introduction to Java
What’s in the class body?
– Data members
– Methods/messages that operate on the
data.
18
Introduction to Java
Data Members Syntax:
[<access_qualifier>] <Member type> MemberName;
– Access qualifier can be one of the following
• public
• private
• static
final
protected
– Member Type
• int, long, short, float, double, byte or a class
name
19
Introduction to Java
Methods/Messages Syntax:
<access_qualifier> <return_type>
methodName (arg1, arg2, …, argN)
{
method_body
}
20
Java Methods
<access_qualifier>
– public
– protected
– final
private
abstract
<return_type>
– void, int, long, float, … or class name
21
Introduction to Java
Application are either:
– Stand-alone.
– Browser-Based.
– Or both.
22
Introduction to Java
Stand-alone application
– In a stand-alone application, JAVA’s runtime transfers execution to a specific
method named main
– The main method must be defined as
public and static and should return no
value void.
– And one parameter as an array of Strings
23
Introduction to Java
Example:
class HelloWorld {
… methods and members
public static void main(String Args[]) {
// method body
}
… more methods
}
24
Introduction to Java
Simple Stand-alone application
class HelloWorld {
public static void main(String Args[]) {
system.out.println(“Hello World\n”);
}
}
25
Introduction to Java
Browser-Based Application (Applet)
– Must derive from java.applet.Applet
– Must define the following methods
• public void init()
• public void start()
• public void stop()
• public void destroy()
• public void paint(Graphics g)
26
Introduction to Java
Let’s put it together - structure of Java
program
Optional Package Statement
Optional import Statements
Class Definition(s)
A Class Definition
main() and/or init(),start(),
stop(), destroy() are defined
27
Introduction to Java
Language Constructs and Semantics
– Data types & Variables
– Operators
– Statements
•
•
•
•
Expression
Block
Assignment
Flow Control
– Classes
28
Introduction to Java
Built-in data types - integer numbers
– byte = 8-bit signed integer -128 to +127
– short = 16-bit or 2-byte signed integer
– int = 32-bit or 4-byte
– long = 64-bit or 8-byte.
29
Introduction to Java
Built-in data types - Real Numbers
– float = 32-bits
– double = 64-bits
Both float and double are defined
according to IEEE 754-1975.
30
Introduction to Java
Built-in data types - characters & strings
– Sequence of characters enclosed in double
quotes are string literals - string is not a
type. String is class
Ex:
“blue”
‘A’
“black dog”
‘c’
“1st line\n2nd line”
31
Introduction to Java
Built-in data type - Boolean
– Boolean = can hold two values (true,false)
– Boolean variables can only be involved in
logical operation or expressions that
evaluate to (true or false)
32
Introduction to Java
Variables must start with a letter
followed by any number of letters, digits,
underscore ( _ )or the dollar sign ($).
Ex: MyHouse
valid
Her_Car_$ valid
My_2nd_Car valid
12_ab_$
Invalid
33
Introduction to Java
Arithmetic Operators:
– Binary operators
•
•
•
•
•
*, / multiplication and division
+, - addition and subtraction
% remainder
<<, >> shift left and shift right.
>>> shift-right fill zero extension.
34
Introduction to Java
Arithmetic Operators
– Unary Operators
• ++, -- increment and decrement they can
appear before the variable and is called preincrementing or pre-decrement
ex: ++a , --b and are equivalent to a=a+1, b=b+1.
• - unary negative sign.
35
Introduction to Java
Assignment
a=b
for basic types, old value of a disappears to be
replaced by the value of b.
for objects a and b are pointing to the same
object that is the object b is pointing to.
a += b, is the same as a = a + b
a -= b is the same as a = a - b
a *= b is the same as a = a * b
36
Introduction to Java
Expressions
– Operators are evaluated left-to-right.
– Operators are grouped into16 precedence
level.
37
Introduction to Java
Java evaluates expressions with mixed
data types.
– Implicit conversion occurs among basic
data type byte, int, short, long, float, double
– Implicit conversion promote types in an
attempt to preserve precession.
38
Introduction to Java
Block statement
– any number of statements enclosed within
a pair of curl-brackets { }
– Examples
• body of main()
• body of class
• for any reason
39
Introduction to Java
Flow control statements (conditional)
– if (BooleanExpression)
statements-block-1
[ else
statements-block-2 ]
when BooleanExpression evaluates to true
block-1 is executed, otherwise block-2 if it
exists.
40
Introduction to Java
True
Boolean Expression
False
If-then-else
Java
Statements
Java
Statements
41
Introduction to Java
True
Boolean Expression
If-then
Java
Statements
42
Introduction to Java
Flow Control statements (branching)
– switch (expression)
case const_1: statement-block-1
case const_2: statement-block-2
case ….
[default: statement-block-n ]
value evaluated for expression should match
one of the const_n otherwise the defaultblock is executed.
43
Introduction to Java
Eval. switch
C1?
True
C2?
C3?
44
Introduction to Java
Flow Control (branching)
– Break [label]
– continue [label]
– return [ expression]
All three statement cause execution to
branch to the Label or return to the calling
program.
45
Introduction to Java
Control Flow (repetition)
– while (BooleanExpression)
statement-block
– do statement-block
while (booleanExpression)
– for (exp1; BooleanExpression; exp2)
statement-block
46
Introduction to Java
While-stmt
Ex?
47
Introduction to Java
Ex?
False
48
Introduction to Java
Eval I
Is I?
Inc.
49
Introduction to Java
Classes - definition
[<modifiers>] class <classname> {
class_methods and Data …
}
<Modifiers>
– public
– private
- protected
- final
-abstract
50
Introduction to Java
Method signature = method name &
parameters type & order of parameters
method return value is not part of the
signature.
Same name Methods in the same class
or derived classes are called
overloaded.
51
Introduction to Java
Arrays
– Basic types
• int a[] = new int[10] array of 10 integers.
• Int[] a = new int[10]
– Objects
• fish[] f = new fish[9]; creates place holders for 9 fish. the class
name is used as a type
• to create the 9 instances of fish try the following code: (notice
the use of constructor to create instances)
for (int I=0; I<10; I++)
f[I] = new fish(2*I, 1, 2*I);
52
Introduction to Java
Multi-dimensional arrays
• int mat[][] = new int[10][20]; 10x20 matrix.
• Int[][] mat = new int[15][] 15 row matrix
– for (int I=0; I<15; I++)
mat[I] = new int[I+1];
This will create a lower triangular matrix
53
Introduction to Java
Classes as user-defined types
– Syntax
classname <variablename>
– Example
MyClass C; // creates a “place holder”/reference
to an object C of type MyClass
To assign an object to C
C = new MyClass();
54
Introduction to Java
More Examples
MyClass C1;
MyClass C2;
C1 = new MyClass();
C2 = C1; // C2 and C1 are two distinct
objects?
NO
C1 and C2 are pointing to the same object.
55
Introduction to Java
C1
C2
56
Introduction to Java
How do we create two separate
objects?
C1 = new MyClass();
C2 = new MyClass();
57
Introduction to Java
Basic data types are different
int a; // a is a real object it is not a reference
int b; // b is too and it occupies a different
location in memory
a = 7;
b = a; // will assign the value 7 to b.
58
Introduction to Java
Type Wrapper Classes - What are they?
– Are Java classes that encapsulate the
basic data types.
– Are Java classes that defines additional
methods on the basic data types
59
Introduction to Java
Type Wrapper Classes - Distinguish?
– Integer
// full word instead of int
– Long
// First letter is capital
– Character
– Double
– Float
– Boolean
60
Introduction to Java
Type Wrapper Classes - Common
methods
– public basictype classtypeValue()
– public classtype( basictype)
– public String toString()
– public boolean equals( Object )
– public int hashCode()
61
Introduction to Java
Example - The “Integer” wrapper
class Integer {
public Integer( int a ) { … } // as constructor
public int IntegerValue() { … }
public String toString() { … }
public boolean equals( Object Obj) { … }
….
}
62
Introduction to Java
How Do we use them?
a = new Integer(33);
b = new Integer(14);
if (a.equals(b)) {
system.out.println(“a is equal to b”);
}
int c = a.IntegerValue();
63
Introduction to Java
Character Wrapper - Additional
– public static boolean isLowerCase(char c)
– public static boolean isUpperCase(char c)
– public static int digit(char c, int radix)
– public static boolean is Digit(char c)
– public static char forDigit(char c) …
• Note: All methods are static !!!
64
Introduction to Java
More Methods for Integer, Long Float,
and Double
– public final static datatype MIN_VALUE;
– public final static datatype MAX_VALUE;
– public static classtype valueOf(String s);
– public static final datatype NaN;
– public static final datatype
NEGATIVE_INFINITY ...
65
Introduction to Java
Is that All? Definitely Not
– More and more methods - Where can you
find them?
• On-line Documentation
66
Introduction to Java
Basic Input/Output classes
– All Java I/O operations are defined in the
java.io package
– Only two classes are exposed in this
session
• FileOutputStream
• PrintStream
67
Introduction to Java
FileOutputStream
– use this class to write data to file
Ex: FileOutputStream F = new
FileOutputStream(“afile.dat”);
– More Methods to write, close, flush ..
• F.write(a) // a can be int, char, …
• F.close() // close the file and dispose F.
• F.flush() // flush the buffer
68
Introduction to Java
PrintStream
– is a printing to a steam class
– PrintStream requires a FileOutputStream
to be constructed a prior
– to create a PrintStream instance use the
constructor
FileOutputStream fos = new FileOutputStream();
PrintStream pst = new PrintStream(fos);
69
Introduction to Java
Predefined PrintStream
– system.in // Keyboard input
– system.out // screen output
– system.error // default screen output
Methods defined for PrintStream
– println, print a pair for each basic data type
– println, print a pair for generic objects
70
Introduction to Java
Arrays in Java
– Arrays are collection of objects, or data
types that can be referenced by an index.
– Indexes identify location of object or the
cells where objects are stored.
– Each object is an Element of the array.
71
Introduction to Java
How do we create them?
– Syntax:
type[ ] arrayname = new type[size]; // syntax #1
type arrayname[ ] = new type[size]; // syntax #2
– Examples
int a[] = new int[10];
int[ ] a = new int[100];
72
Introduction to Java
What if the size is not known until the
run-time?
– Syntax:
type arrayname;
– Example:
int size;
int[ ] a;
…
size = getSizeValue(); // any method
a = new int[size];
73
Introduction to Java
Can we initialize them “in-bulk” ?
– Syntax:
type arrayname[ ] = { v1, v2, v3, … vn };
type[ ] arrayname = { v1, v2, v3, … vn };
– Example:
• int[ ] a = { 12, 14, 16, 18, 20 }; // size is 5
• char vowels[ ] = { ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ };
74
Introduction to Java
Can we form collections of Objects? Yes
How do we create them?
– Create “place-holder” - step 1
– Create each individual element - step 2
75
Introduction to Java
Examples:
Turtles[] turtle = new Turtles[10]; // 10 cat placeholder
for ( x=0; x<10; x++) {
turtle[x] = new Turtles(); // run the
constructor
}
76
Introduction to Java
Multi-dimensional arrays
– Examples:
int a[ ][ ] = new int[5][10];
77
Introduction to Java
More Examples:
– 3-D arrays
int a[][][] = new int[10][10][5]; // 3-D array
– Variable size arrays
int a[10][ ] = new int[10][ ];
for (x=0; x<10;x++) {
a[x] = new int[x+1];
} // creating a lower triangular matrix
78
Introduction to Java
The String Class
– String class is an object with an array of
characters with lot of methods
– Several overloaded constructors
•
•
•
•
public String(); // null string
public String( String S); // string from a string
public String(char[ ] s ); // string from array of char
public String(char[ ] s, int offset, int count); ..
79
Introduction to Java
String class
– Examples:
String S1 = new String(“Joe Doe”);
char vowels[ ] = { ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ };
String Vowels = new String(vowels);
80
Introduction to Java
Parameter passed by value (basic types)
…
int aMethod( int x ) {
x++;
return x; }
…
a = 7;
b = aMethod(a);
system.out.println(a); // what’s the value of a
81
Introduction to Java
Parameter Passing by value - (Objects)
…
int aMethod(Elephant E) {
E.Weight(150);
return 150; }
…
Elephant Mimi = new Elephant();
Mini.Weight(95);
b = aMethod(Mimi);
system.out.println(Mimi.WeightTell()); //
what’s it?
82
Introduction to Java
Scope
– Scope is the region in which a variable is
assumed in existence.
– Regions are defined as the code inside a
block
– Java compiler search for referenced
variables starting by the region in which
are referenced and expand to the outer
region until the variable is founf.
83
Introduction to Java
Scope
Outermost Scope
Class
{
{
{
}
{
}
}
{
}
}
84
Introduction to Java (2)
85
Object-Oriented Programming
Is JAVA an Object-Oriented Language?
– Classes/Collections in JAVA.
– Encapsulation in JAVA.
– Inheritance in JAVA.
– Abstraction in JAVA.
– Polymorphism in JAVA.
– Identity of Objects in JAVA.
86
Object-Oriented Programming
Classes/Collections in JAVA.
– Everything in JAVA is defined in the context
of an object.
– Objects are defined by Classes (class)
– Exampleclass Dogs {
….. Dogs attributes and behavior definitions
}
87
Object-Oriented Programming
Encapsulation In JAVA.
– JAVA provides the implementers with four
ways to classify attributes and behaviors of
a class.
•
•
•
•
Private members (private)
Public members (public)
Protected members (protected)
Friendly members (No keyword designator)
88
Object-Oriented Programming
Encapsulation in JAVA.
– Example
class Dogs {
public Dogs_Color;
private Dogs_Length_of_intestinal_tract
protected Dogs_genetic_material
…. Other attributes and behaviors.
}
89
Object-Oriented Programming
Single-Inheritance in JAVA.
– Classes in JAVA can be defined using
already defined classes and extends them.
– Example
class Dolmation_dogs extends Dogs {
…. Attributes and Behaviors
}
90
Object-Oriented Programming
Multiple-Inheritance in JAVA.
– It is not Supported.
– Indirectly JAVA provides a replacement
concept (interface)
– Several JAVA classes can provide
implementation for same interface.
(implements).
91
Object-Oriented Programming
Abstraction In JAVA.
– Abstract Classes (abstract)
• JAVA allows the implementers to define classes
with partial implementation.
• Abstract classes are useful for modeling basic
behavior and leave detail implementation to
subclasses
92
Object-Oriented Programming
Abstraction in JAVA.
– JAVA allows classes not related by
inheritance to exhibit and support same
behavior/protocol through the interface
concept.
93
Object-Oriented Programming
Polymorphism In JAVA.
– Three different type of polymorphism
• Within the same class
– Methods same name different signature/parameters
(Method overloading)
• Through inheritance (extends)
– Methods same name same signature
• Through implementation of same interface.
– Methods same name.
94
Object-Oriented Programming
Object Instantiation In JAVA.
– New objects are instantiated in JAVA using
the new language construct.
– Example
MyDog = new Dogs(Dog.Color.BLACK);
95
Introduction to Java (3)
96
Introduction to Java
Structure of a JAVA Program.
– Optional Package construct.
– Optional Import statements.
– Class implementation (class).
– Interface implementations(interface)
97
Introduction to Java
JAVA Packages
– java.applet
– java.awt, java.awt.peer & java.awt.image
– java.io
– java.net
– java.lang
– java.util
98
Introduction to Java
Java.applet
– Package that enables construction of
applets. It also provides information about
an applet's parent document, about other
applets in that document, and enables an
applet to play audio.
99
Introduction to Java
Java.awt
– Package that provides user interface
features such as windows, dialog boxes,
buttons, checkboxes, lists, menus,
scrollbars and text fields. (Abstract Window
Toolkit)
100
Introduction to Java
Java.awt.image
– Package for managing image data, such
as the setting the color model, cropping,
color filtering, setting pixel values and
grabbing snapshots.
101
Introduction to Java
Java.awt.peer
– Package that connects AWT components
to their platform-specific implementation
(such as Motif widgets or Microsoft
Windows controls).
102
Introduction to Java
Java.io
– Package that provides a set of input and
output streams to read and write data to
files, strings, and other sources.
103
Introduction to Java
Java.net
– Package for network support, including
URLs, TCP sockets, UDP sockets, IP
addresses and a binary-to-text converter.
104
Introduction to Java
Java.lang
– Package that contains essential Java
classes, including numerics, strings,
objects, compiler, runtime, security and
threads. Unlike other packages, java.lang
is automatically imported into every Java
program.
105
Introduction to Java
Java.util
– Package containing miscellaneous utility
classes, including generic data structures,
settable bits class, time, date, string
manipulation, random number generation,
system properties, notification, and
enumeration of data structures.
106
Introduction to Java
JAVA application programs
– Programs without the (package) statement
are application code.
– Applications are either
• Stand-alone Application.
• Browser-Based Application (Applet).
107
Introduction to Java
Stand-alone
– In a stand-alone application, JAVA’s runtime transfers execution to a specific
method named (main)
– The main method must be defined as
public and static and should return no
value void.
– And one parameter as an array of strings
108
Introduction to Java
Browser-based Applet
– To define an application that the JAVA run-time
embedded within a browser would execute one
should define the following methods
• public init() to initialize the application code.
• public start() to start/resume the application.
• public stop() to stop the application
• public destroy() to unload the application.
• public paint(Graphics g) to (re)draw the applet.
109
Introduction to Java
Object
Component
Container
Panel
Applet
110
Introduction to Java
Main Features of Applets
– Code is small (few Kilobytes).
– Support interactive input from the user.
– Support for multi-media (Audio, images).
– Support Graphical User Interface (GUI)
elements.
– Limited access to client resources
(security).
111
Introduction to Java
Creating Applets
– Derive from java.applet.Applet
Ex:
public class MyFirstApplet extends
java.applet.Applet {
… // Applet Code
}
112
Introduction to Java
Essential methods
– One must provide implementation code for
the following methods
•
•
•
•
•
public void init()
public void start()
public void stop()
public void destroy()
public void paint(Graphics g)
113
Introduction to Java
public void init()
– Called by the browser immediately after
the applet is loaded.
– The method primary function is to initialize
the applet
• create other objects
• set & initialize parameters
• load images, sound files, fonts …etc.
114
Introduction to Java
public void init() - (Cont.)
– init() is called only once by the browser
during its life time, but applet code can call
init() later.
115
Introduction to Java
public void start()
– after init() the browser invokes start()
– unlike init(), the browser invokes start()
several times to restart a suspended
applet.
– start() is generally used display images,
invoke methods on other objects, create
Threads for parallel processing
116
Introduction to Java
public void stop()
– stop() method is called by the browser
whenever the applet is to be suspended.
– stop() method is called every time the web
user leaves the page containing the applet.
– Applet is restarted by by the browser by
invoking the start() method.
117
Introduction to Java
public void destroy()
– destroy() is specific designed for Java
applets. Different from finalize()
– destroy() is executed once when the applet
or the browser is terminated.
– destroy() is a general cleanup method close file, stop threads, … etc.
118
Introduction to Java
public void paint(Graphics g)
– paint is called by the browser whenever the
applet need to be redrawn
• resized, uncovered, moved, initialized … etc.
• Graphics g, is the display device defined by the
browser (You do not have to create it)
• you must override this method to create any
useful applet.
119
Introduction to Java
Simple Applet
public class HelloWorld extends Applet {
public void init() {
resize(500,500); // pixels.
}
// public void start() use default from parent
120
Introduction to Java
Simple applet - (cont.)
// public void stop(), use default from parent
// public void destroy(), use default from
parent.
Public void paint(Graphics g) {
g.drawString(“Hello World!”, 10, 20);
}
}
121
Introduction to Java
To run a Browser-based Applet
– You must create an HTML file that contains
a tag similar to:
<applet code=“applet_name.class”
[codebase=“directory”] width=w, height=h>
<param param_name=value>
...
</applet>
122
Introduction to Java
More HTML Tags
– ALIGN= LEFT, RIGHT, TOP, TEXTOP
…etc.
– HSPACE=, VSPACE= pixels
– <ALT=alternate text> for not Java enabled
browser.
123
Introduction to Java
The Graphics g object
– g class provides several methods
•
•
•
•
setFont()
setColor()
drawString()
standard colors (black, blue, … white, yellow).
124
Introduction to Java
Simple applet II
– add the following lines
• private Font StFont = new Font(“Times
Roman”, Font.ITALIC, 20);
• before drawString in the paint() method add,
g.setFont(StFont);
g.setColor(Color.blue);
– And run the applet to have hello World in
times roman, blue italic font.
125
Introduction to Java
Passing Parameters
– Use <PARAM Param_name=Param_value> tag
in the HTML file
– Use getParameter(Param_name) in the
applet init(method)
– convert Param_value from String to the
appropriate type using the methods
defined on the type wrapper classes.
126
Introduction to Java
Example - HTML Param Tags
<applet code=“Hello.class”, width=200,
height=100>
<param COLOR=“red”>
<param SIZE=“36”>
</applet>
127
Introduction to Java
Example - applet init() code
String color;
String size;
color = getParameter(“COLOR”);
size = getParameter(“SIZE”);
128
Introduction to Java
The Graphics g Object
– it is a rectangular region
– its size is specified by the resize()
invocation in init() - resize(500,500)
– the unit is pixels = picture element
129
Introduction to Java
(0,0)
(10)
x
y
(20)
130
Introduction to Java
More Methods
–
–
–
–
–
–
–
drawLine( x_start,y_start, x_end,y_end)
drawRect(x_top_left,y_top_left,width,height)
fillRect(x_top_left,y_top_left,width,height)
drawRoundRect(…, arc_width, arc_height)
fillRoundRect(…, arc_width, arc_height)
draw3DRect(…, true/false) raised/indented.
fill3DRect(…,true/false) .
131
Introduction to Java
Height
Width
132
Introduction to Java
More Methods
– fillOval, drawOval
• x_top_left, y_top_left, width, height
– fillArc, drawArc
• x_top_left, y_top_left, width, height,
start_angle, sweep_angle
133
Introduction to Java
(0,0)
900
1800
g.drawArc(0,0,20,20,90,180)
134
Introduction to Java
Draw Polygons
– drawPolygon(int x[ ], int y[ ], length)
– drawPolygon(Polygon P)
– or the fillPolygon methods
135
Introduction to Java
Draw Triangle
End points
int x[ ] = {10, 40, 25, 10 };
int y[ ] = {60, 60, 10, 60 };
g.drawPolygon(x, y, 4); // outlined triangle
or
g.fillPolygon(x, y, 4); // filled triangle
136
Introduction to Java
Draw Triangle
int x[ ] = {10, 40, 25, 10 };
int y[ ] = {60, 60, 10, 60 };
Polygon triangle = new Polygon(x, y, 4);
g.drawPolygon(triangle); // outlined triangle
or
g.fillPolygon(triangle); // filled triangle
137
Introduction to Java
(5,5)
(25,15)
15
g.copyArea(5,5,15,10,15,10)
g.clearRect(5,5,15,10)
138
Introduction to Java
Applets and Fonts Information
– setFont(), getFont() are inherited from
Component
– getFontMetrics(Font Fnt)
–
–
–
–
–
getLeading()
getAscent()
getDescent()
getHeight()
many others (straightforward).
139
Introduction to Java
Baseline
Graphics
Java
Ascent
Descent
Height = Leading+Ascent+Descent
140
Introduction to Java
Java Support Multi-threading
– an application can execute multiple blocks
of code (thread) in parallel.
– Issues
• How do we create them
• How do we manage them
• How do we get rid on them
141
Introduction to Java
Main Thread
Thread 1
Th1
Th2
Thread 2
142
Introduction to Java
Threads
– Two ways to Create threads in Java
• Derive & extend the “Thread” class
class MyClass extends Thread
• Implement the “Runnable” interface in you
applet.
class MyClass extends Applet implements
Runnable
143
Introduction to Java
Approach#1- extends Thread
class MyThread extends Thread {
private int a;
private int b;
String Thname;
public MyThread(String Thname,int a, int b) {
this.a = a;
this.b = b;
this.Thname = Thname
}
144
Introduction to Java
(Cont.)
public void run() {
for(int I=0; I<3; I++) {
if (a>0) a *=a;
else a = (a==0) ? 0 : a = -(a*a);
if (b>0) b *=b;
else b = -(a - 1);
system.out.println(Thname+” a= “+a+” b=“+b);
sleep(1000); // sleep 1000 milliseconds
}
}
145
Introduction to Java
(Cont.)
public static void main(String[ ] args) {
MyThread t1 = new MyThread(“Thread#1”, 2, 0);
MyThread t2 = new MyThread(“Thread#2”, 0, 4);
t1.start();
t2.start();
} // end the main method
} // end of MyThread
146
Introduction to Java
Let’s Run the Example
1. main creates th1 and th2
2. main starts th1
3. main starts th2
4. Let’s analyze the output on the next slide
147
Introduction to Java
Th1
Thread#1 a=4 b= -3
Thread#1 a=16 b= -15
Thread#1 a=256 b= -255
Th2
Thread#2 a=0 b= 16
Thread#2 a=0 b= 256
Thread#2 a=0 b= 65536
148
Introduction to Java
Approach #2 - Implement the
“Runnable” interface
– class myClass extends Aclass implements
Runnable
– Ex: re-write the previous example by
extending “Object” and implement
Runnable.
– Code should look the same.
149
Introduction to Java
To implement a multi-threaded applet,
use the following
class ThreadedApplet
extends java.applet.Applet
implements Runnable {
… // Your Applet Code
// override the run() method
}
150
Introduction to Java
Can we manage them?
– Suspend & Resume using suspend() &
resume()
– stop() & start()
– ask threads to yield using yield()
– ask for the identity of the thread using
CurrentThread() static method.
– Ask if thread isAlive()
151
Introduction to Java (4)
152
Introduction to Java
Exceptions and Errors
– Error in Java is an indication of a serious
problem that happened during the
execution of the application.
– Error subclasses are not required to be
specified in the method’s throw clause.
– Errors need not be caught by the catch by
the application.
153
Introduction to Java
Exceptions & Errors
– Exceptions are indication of an error that
the application want to catch and
programmers can provide a handler for.
– Exceptions must be specified in the
method’s throws clause if the method is
expected to throw such an exception.
154
Introduction to Java
Object
Throwable
Error
Exception
155
Introduction to Java
Exceptions and Errors
– Java Language defines plenty of Error and
Exception objects
156
Introduction to Java
Extending The exception class
public class anException extends
Exception
{
public anException() { super(); }
// and/or
public anException(String s) { super(s); }
}
157
Introduction to Java
Methods must specify the exceptions
that can be thrown any time during the
method execution.
<qualifier> <return_type> method(params)
throws excep1, excep2, …, excepN
{
// your code
}
158
Introduction to Java
When Exceptions/Errors occur in the
method body are thrown as follows
public void aMethod(int I) throws anException
{
…. Method code
if (aCondition==ExceptionCondition){
throw new anException(“a Message”);
}
… Method code
}
159
Introduction to Java
Exceptions are caught as follows
try
block-statement
catch (exception_class e)
block-statement .. Handling the exception
catch (another_exception_class e)
another-block … handling this exception
…
finally // optional
the-finally-block
160
Introduction to Java
Input/Output with Java
– Java provides a framework for defining
input/output classes.
– The framework defines input/output as
streams
– A Stream is either output stream or input
stream
– Streams are ordered sequence of of data
items
161
Introduction to Java
Object
InputStream
OutputStream
RandomAccessFile
162
Introduction to Java
InputStream is an abstract that class
defines the following methods
public abstract int read() throws IOException
public int read(byte b[]) throws IOException
public int read(byte b[], int off, int len) throws IOException
public long skip(long n) throws IOException
public int available() throws IOException
public void close() throws IOException
public synchronized void mark(int readlimit) throws
IOException
public synchronized void reset() throws IOException
public Boolean markSupported()
163
Introduction to Java
Typical code to open a file
InputStream InSt = null;
try
{
InSt = new FileInputStream(“file.txt”);
}
catch (FileNotFound e)
…
catch (IOException e)
...
164
Introduction to Java
Typical code to read a character data
from a file
try
{
c = InSt.read();
}
catch (IOException e)
{
System.out.println(e);
}
165
Introduction to Java
OutputStream
– Abstract class for output streams
– Defines basic methods that must defined
by subclasses
– Java like for InputStream provides several
subclasses for OutputStream as well
166
Introduction to Java
Important methods in the OutputStream
public abstract void write(int b) throws
IOException
public void write(byte b[]) throws
IOException
public void write(byte b[], int off, int len)
throws IOException
public void flush() throws IOException
public void close() throws IOException
167
Introduction to Java
Typical code to open a file for output
OutputStream OutSt = null;
try
{
OutSt = new FileOutputStream(“file.txt”);
}
catch (IOException e)
… handle exception
}
168
Introduction to Java
Typical code to write data out to a file
try
{
OutSt.write()
}
catch (IOException e)
… handle Exception
}
169
Introduction to Java
Other Input/Output Classes
– File
– ByteArrayInputStream & the Output one
– StringBufferInputStream
– FilterInputStream & FilterOutputStream
– BufferedInputStream &
BufferedOutputStream
– DataInputStream & DataOutputStream
170
Introduction to Java
More
– PipedInputStream & PipedOutputStream
– SequenceInputStream
– LineNumberInputStream
– PushbackInputStream
– PrintStream
– RandomAccessFile
171
Introduction to Java
And Two Interfaces
– DataInput
– DataOutput
172
Introduction to Java
The File Class
– The file class provides a platform neutral
way to describe files and directories
– The file class defines several static
methods to let you construct files/
directories name compatible with the client/
server platform
– The file class let you check if the file exists/
readable/ writable …
173
Introduction to Java
Some constants from the File class
public static final char separatorChar;
public static final String separator;
public static final char pathSeparatorChar;
public static final String pathSeparator;
174
Introduction to Java
ByteArrayInputStream / Output
– This class allows application to handle arrays of
bytes as files.
– ByteArrayXXXStream classes redefines some of
the methods EX:
• available() always returns bytes not read.
• reset() reset to the beginning of the array.
StringBufferInputStream / Output
– same as ByteArray it uses a String object instead
175
Introduction to Java
FilterInputStream / FilterOutputStream
– This class is used to define a chain of
filters
– Each filter will optionally performs some
processing on the data and sends it to the
next filter in the chain and so on until it
reaches the file stream
176
Introduction to Java
InputStream
Filter#2
Filter#3
177
Introduction to Java
BufferdInputStream / Output
– As the name indicates this class reads/
write data to a buffer a prior.
– Programmers can specify the size of the
buffer
– Subsequent activities will be statisfied from
the buffer if it contains the requested
information.
178
Introduction to Java
DataInputStream/ DataOutputStream
– All previous classes processed data as a
stream of bytes this pair of classes allows
the programmer to read data directly into
Java basic data types such as Boolean,
Integers, Floating point numbers, etc.
– This pair extends the Filter classes and
provide an implementation for the Data
intefaces
179
Introduction to Java
LineNumberInputStream
– This class is an input stream filter that provides the
added functionality of keeping track of the current
line number.
PipedInputStream / PipedOutputStream
– Allows two threads to communicate by one
producing the data and write it using output pipe,
while the other threads consumes it by reading it
first using and input pipe.
180
Introduction to Java
SequenceInputStream
– It provides a framework to combine two
separate InputStream(s) into one logical
InputStream.
– Once the EOF on the first stream is
reached the stream continues on the next
Stream.
181
Introduction to Java
PushbackInputStream
– Allows the user to push back a character to
the input stream by using the unread()
method.
– Using read() and unread() allows the
programmer to take a peak (lookahead)
into the input stream.
182
Introduction to Java
PrintStream
– allows the Java programmer to write out
data to console or files in a human
readable format.
– System.out is a PrintStream predefine in
Java.
183
Introduction to Java
RandomAccessFile
– This class extends Object
– This class enables programmers to read
and write bytes, text, Java data types to
any location in a file.
– This class provides implementation for
both the DataInput and the DataOutput
interfaces.
184
Java Additional Slides
185
Object-Oriented Programming
How Old is Object-Oriented?
– SIMULA 1960s
– Smalltalk-80 late 1970s
– Most Popular - C++
– New (relatively) - Java
186
Object-Oriented Programming
What Does It Mean to Be ObjectOriented?
– Identity
– Abstraction
– Encapsulation (Information Hiding)
– Inheritance
– Polymorphism
– Event Driven
187
Object-Oriented Programming
Definition (Grady Booch)
– “Object-Oriented Programming is a method
of implementation in which programs are
organized as cooperative collections of
Objects, each of which represents an
instance of some Class, and whose
classes are all members of hierarchy of
classes united via inheritance
relationships”
188
Object-Oriented Programming
What’s an Object?
– Attributes(Properties)
– Behavior (Operations/Methods/Messages)
– State (Rules and Constraints on Attribute
to Control Behavior).
What’s an Object Identity?
– Two similar objects have separate Identity,
behave separately, change state
independently.
189
Object-Oriented Programming
What’s a Class (Abstraction)
– Collection of Objects.
– Objects in the Class share common
semantics.
– Objects in the Class share common
attributes.
– Objects behave similarly under similar
conditions.
190
Object-Oriented Programming
What’s Abstraction?
– Is one of the fundamental ways we cope
with complexity.
– Recognize Similarities.
– Ignore Differences.
– Similarities & Differences are relative to the
perspective of the observer.
191
Object-Oriented Programming
What’s Encapsulation?
Information Hiding
– Implementers of objects concern
themselves with the details of the
abstraction.
– Users of objects should only see what’s
relevant to use the object.
– Need not know implementation details.
192
Object-Oriented Programming
What’s Inheritance?
– Do implementers need to start from scratch
when designing new classes? No.
– Inheritance is the concept of (re)using an
existing abstraction(s) and expanding upon
them or modifying behavior.
– Inheritance from multiple classes is defined
as Multiple-Inheritance.
Inheritances Defines an “Is-A” relationships
Among Classes.
193
Object-Oriented Programming
What’s Polymorphism?
– “Poly-Morph” - Many forms.
– Similar Objects/Classes can exhibit same
behavior under different stimuli.
– Different Objects/Classes can exhibit
different behavior under same stimuli.
– Polymorphism is an abstraction of
behavior.
194
Object-Oriented Programming
What’s Abstract Classes?
– As Level of abstraction increases, Generic
definition for certain known behaviors
cannot be defined (implemented).
– Classes with one or more unimplemented
behavior are called Abstract Classes.
– Mathematically speaking Abstract Classes
are empty classes - no objects can be
instantiated.
195
Introduction to Java
Three types of JAVA programs
– Programs with the package statement as
the first line of code defines a package
• Package Package_name
– Programs without the package reserved
word are either:
• Java program code (Default Package)
• Application.
196
Introduction to Java
An application could run in either mode
if it is constructed as follows.
class myclass extends java.applet.Applet {
public static void main() {
myclass A = new myclass();
A.init();
A.start();
}…
}
197
Introduction to Java
Built-in data types - characters & strings
– char = 16-bit unsigned, Unicode.
• Non-printable characters are presented as
newline
CR
Tab
backspace
form feed
\n \u000A
\r \u000D
\t \u0009
\b \u0008
\f \u000C
backslash
\\
\u005C
single quote \’ \u0027
double quote \” \u0022
any char (octal)
\ddd
any Unicode (hex) \udddd
198