java 2 presentation
TRANSCRIPT
![Page 1: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/1.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 1/118
Java LanguageAbdulmalik S. Al-Gahmi
October 4, 2001
![Page 2: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/2.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 2/118
Course Objectives
Upon completing this course you should be able to:
– Describe the three main OOP concepts.
– Differentiate between “is a” and “has a” Relationships
– Use Java standards for coding.
– Describe Java environment and how it works.
– Write java programs.
– Create packages and document them
– Create classes and interfaces.
– Create and manage a hierarchy of classes and interfaces
– Create objects out of classes.
– Use Java I/O capabilities.
– Connect to a database using JDBC
– Use Java API
![Page 3: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/3.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 3/118
Course Organization
Part 1: OOP Model
Part 2: Java Basics
Part 3: Java implementation of OOP
Model Part 4: Java OOP Design Issues
Part 5: Introduction to Java API
» Java I/O» Java JDBC
Part 6: Advanced Java Features» Treads
» Exception Handling
![Page 4: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/4.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 4/118
OOP Model
Part 1
![Page 5: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/5.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 5/118
Introduction To OOP
Philosophy:
– Abstraction Growth:
Machine Language
Assembly LanguageNon-procedural Languages (BASIC)
Procedural Languages (C, Pascal)
OOP languages (C++, Java)
– OOP model is to eliminate the mapping fromthe problem space to solution space aspossible.
![Page 6: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/6.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 6/118
Objects
Objects can be described in terms of:
– Their attributes
– Their behaviors
Object’s attributes and behaviors areencapsulated together a data type.
Objects have a lifecycle:
– Creating objects – Manipulating objects
– Cleaning up objects
![Page 7: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/7.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 7/118
OOP Five Rules
Alan Kay summarized five basiccharacteristics of Smalltalk:
1. Everything is an object.
2. A program is a bunch of objects telling eachother what to do by sending messages.
3. Each object has its own memory made up of other objects.
4. Every object has a type.
5. All objects of a particular type can receive thesame messages.
![Page 8: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/8.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 8/118
Objects Interfaces
An object has to have an interface.
The interface will
– Provide a way to let other objects to
communicate with it.
– Hide the details of the object implementation.
An example: Light bulb:
On()
Off()
Brighten()
Dim()
Light
![Page 9: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/9.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 9/118
OOP Big Goals (1)
Implementation Hiding
– Breaks up the playing field into:» Class creators (those who create new data types)
» Client programmers (those who use these types for their own
tasks. They only deal with the interfaces.)
– The goal of the class creator is to build a class thatexposes only what’s necessary to the client programmer and keeps everything else hidden.
– Two reasons for controlling the access:» To keep client programmers’ hands off portions they shouldn’t
touch.
» To allow the library designer to change the internal workingsof the class without worrying about how it will affect the clientprogrammer.
![Page 10: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/10.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 10/118
OOP Big Goals (2)
Implementation Reuse:
– Software reusability is not so easy to achieve asmany would hope; it takes experience and
insight to produce a good design. – OOP provides ways for reuse:
» Composition:
» Inheritance(Reusing the interface)
– OOP differentiates between:» “is-a” Relationship ( Inheritance)
» “has-a” Relationship (Composition)
![Page 11: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/11.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 11/118
OOP Big Goals (3)
Polymorphism
– Allows you to make the derived types behave
differently from their base types.
– It uses “late binding” instead of “early binding”
– Example:Bird
Move()
Goose
Move()
Penguin
Move()
![Page 12: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/12.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 12/118
Java Basics
Part 2
![Page 13: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/13.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 13/118
History of C++
First there was C.
C initially became widely known as the
development language of UNIX OS.
C++ evolved as an extension to C.
It mainly provides the capabilities of
Object-Oriented Programming to C world.
C++ is a hybrid language. Both C-like styleand object-oriented style can be developed
using it.
![Page 14: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/14.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 14/118
History of Java
Java first was developed in 1991 by James
Gosling at Sun Microsystems to be used
with interactive TV technology which had
failed to find a market.
When The World-Wide Web became
popular in 1995 , Java came to life again.
Java is now considered as the nativelanguage of the Internet.
Java is a C/C++ based language.
Java is a Full object-oriented language
![Page 15: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/15.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 15/118
So, what is Java?
According to Sun's definition:
Java is a "simple, object-oriented,
interpreted, robust, secure,architecture-neutral, portable,
high-performance, multithreaded,and dynamic language."
![Page 16: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/16.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 16/118
Java Environment
EditorDraft .java file
Compiler .java file .class File
Byte code VerifierByte code on RAM Verified Byte code
InterpreterVerified Byte codeExecuted machine
code
Class Loader .class File Byte code on RAM
![Page 17: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/17.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 17/118
Compiling/Running Java
Programs
To compile your program, use command:
c:\> javac MyProgramName.java To run your program, use command:
c:\> java MyProgramName
![Page 18: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/18.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 18/118
Program skeleton1 //the skeleton of a java application
2 package packagename;
3 import packagename.ClassName;
4 public class ProgramName
5 {
6 // Define program variables here.
7 . . .
8 // Define program methods here.
9 . . .
10 //Define the main method here.
11 public static main(String args[])
12 {
13 // Main method body
14 }//end of the main method.
15 } //End of class HelloWorld
Java is a case
sensitive language
Braces must occur
on matching pairs
Coding styles
should be followed.
Notes
![Page 19: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/19.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 19/118
![Page 20: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/20.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 20/118
Playing With Strings
A string is a group of characters
We use class String to define a string. Example: String name;
Strings are bounded by double quotations. Example: String name = “Jane”;
We can concatenate two or more strings using theoperator +
Strings can contain escape characters like “\n”,“\t”, “\\”, “\””.
![Page 21: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/21.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 21/118
Variables Definition
Variables are used to represent the data that a
program deals with
As the name might imply, the data that a
variable holds can change.
We have to define a variable before using it
Here is an example of defining a variable:
int number;String name;
![Page 22: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/22.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 22/118
Primitives Data types
Type Size in bits Valuesboolean 8 true or false
char 16 \u0000 - \uFFFF
byte 8 -128 - 127short 16 -32,768 – 32,767
int 32 -2,147,483,648 - +2,147,483,647
long 64-9,223,372,036,854,775,808 -
+9,223,372,036,854,775,807
float 32 -3.40292347E+38 - -+3.40292347E+38
double 64 -1.79769313486231570E+308 to -
+1.79769313486231570E+308
![Page 23: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/23.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 23/118
Arithmetic Operations
Operation Operator Java Expression
Addition + a + 8
Subtraction - b - 7
Multiplication * p * 10
Division / c / 9
Modulus % b % 6
![Page 24: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/24.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 24/118
Decision making operations
Operation Operator Java Expression
Equal to == if (x == 1) …
Not equal to != if (y != 5) …
Greater than > while (x > y) …
Less than < while (x < y) …
Greater than or equal >= if (X >= y) …
Less than or equal <= if ( y <= z) …
![Page 25: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/25.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 25/118
Assignment Operators
Operator Expression Equivalent to
= c = 5; c = 5
+= a += 10 ; a = a + 10;-= a -= b; a = a – b;
*= c *= 13; c = c * 13;
/= a /= b; a = a/b;%= b %= c ; b = b% c;
![Page 26: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/26.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 26/118
Increment /decrement
operationOperator expression Equivalent to
++ count++;
++count;
Count = count + 1;
-- --count;
Count--;
Count = count - 1;
![Page 27: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/27.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 27/118
Logical Operators
Logical operators allow more complex conditions && (logical AND)
– Returns true if both conditions are true
|| (logical OR)
– Returns true if either of its conditions are true ! (logical NOT, logical negation)
– Reverses the truth/falsity of its condition
– Unary operator, has one operand
Short circuit evaluation
– Evaluate left operand, decide whether to evaluate rightoperand
– If left operand of && is false, will not evaluate right
operand
![Page 28: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/28.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 28/118
PrecedenceOperator Associativity
( ) From left to right
++ -- From right to left
* / % From left to right
+ - From left to right
< <= > >= From left to right
== != From left to right
& From left to right
^ From left to right
| From left to right&& From left to right
|| From left to right
?: From right to left
= += -= *= /= From right to left
High
Low
![Page 29: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/29.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 29/118
Java Key words
Java Keywords
abstract boolean break byte case
catch char class continue default
do double else extends false
final finally float for if
implements import instanceof int interface
long native new null package
private protected public return short
static super switch synchronized this
throw throws transient true try
void volatile while
Keywords that are reserved but not used by Java
const goto
Keywords are words reserved for Java and cannot be
used as identifiers or variable names
![Page 30: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/30.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 30/118
If – if/else structures
if statement looks like:if (condition)
{ …
} Conditions are
evaluated to either true
or false
If/else statement looks
like:if (condition)
{//do something.
}
else
{//do something else.
}
![Page 31: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/31.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 31/118
The switch Structure
switch statements
– Useful to test a variable for different values switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}
– break; causes exit from structure
![Page 32: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/32.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 32/118
While Structure
while repetition structure
– Repeat an action while some condition remains true
– while loop repeated until condition becomes false
– Body may be a single or compound statement – If the condition is initially false then the body will never
be executed
– Example:
int product = 2; while ( product <= 1000 )
product = 2 * product;
![Page 33: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/33.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 33/118
The for Structure
for "does it all" : initialization, condition, increment
General format
for ( initialization; loopContinuationTest ; increment )
statement
If multiple statements needed, enclose in braces
Control variable only exists in body of for
structure
If loopContinuationTest is initially false, bodynot executed
![Page 34: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/34.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 34/118
Methods Methods
– Modularize a program – All variables declared inside methods are local variables
» Known only in method defined
– Parameters
» Communicate information between methods» Local variables
Benefits
– Divide and conquer
» Manageable program development
– Software reusability
» Existing methods are building blocks for new programs
» Abstraction - hide internal details (library methods)
– Avoids code repetition
![Page 35: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/35.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 35/118
Method Definitions
Method definition format return-value-type method-name( parameter-list )
{
declarations and statements
} – Method-name: any valid identifier
– Return-value-type: data type of the result (default int)
» void - method returns nothing
» Can return at most one value – Parameter-list: comma separated list, declares
parameters.
![Page 36: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/36.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 36/118
return Statement
When method call encountered
– Control transferred from point of invocation tomethod
Returning control
– If nothing returned: return; » Or until reaches right brace
– If value returned: return expression;» Returns the value of expression
Example user-defined method:
public int square( int y ){
return y * y
}
![Page 37: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/37.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 37/118
Calling methods
Three ways – Method name and arguments
» Can be used by methods of same class
square( 2 );
– Dot operator - used with references to objects
g.drawLine( x1, y1, x2, y2 );
– Dot operator - used with static methods of
classes
Integer.parseInt( myString );
![Page 38: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/38.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 38/118
Coercion of arguments Forces arguments to appropriate type for method
– Example:
» Math methods only take double
» Math.sqrt( 4 ) evaluates correctly
Integer promoted to double before passed to Math.sqrt
Promotion rules
– Specify how types can be converted without losing data
– If data will be lost (i.e. double to int), explicit cast must
be used
– If y is a double, square( (int) y );
![Page 39: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/39.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 39/118
Duration of Identifiers
Duration (lifetime) of identifiers – When exists in memory
– Automatic duration
» Local variables in a method
Called automatic or local variables» Exist in block they are declared
» When block becomes inactive, they are destroyed
– Static duration
» Created when defined
» Exist until program ends
» Does not mean can be referenced/used anywhere
See Scope Rules
![Page 40: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/40.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 40/118
Scope Rules (1)
Scope – Where identifier can be referenced
– Local variable declared in block can only be
used in that block Class scope
– Begins at opening brace, ends at closing brace
of class
– Methods and instance variables
» Can be accessed by any method in class
![Page 41: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/41.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 41/118
Scope Rules (2)
Block scope
– Begins at identifier's declaration, ends at terminatingbrace
– Local variables and parameters of methods» When nested blocks, need unique identifier names
– If local variable has same name as instance variable
» Instance variable "hidden"
Method scope – For labels (used with break and continue)
– Only visible in method it is used
O i
![Page 42: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/42.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 42/118
Method Overloading
Method overloading – Methods with same name and different parameters
– Overloaded methods should perform similar tasks» Method to square ints and method to square doubles
public int square( int x ) { return x * x; }
public float square( double x ) { return x * x; }
– Program calls method by signature
» Signature determined by method name and parameter types
» Overloaded methods must have different parameters
Return type cannot distinguish method
![Page 43: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/43.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 43/118
Arrays
Array – Group of consecutive memory locations
– Same name and type
– Static(Remain same size)
To refer to an element, specify – Array name
– Position number
Format:
– arrayname[ position number]
– First element at position 0
Every array knows its own lengthc.length
![Page 44: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/44.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 44/118
Declaring/Allocating Arrays
Declaring arrays – Specify type, use new operator
» Allocate number of elements
» Place brackets after name in declaration
– Two steps:int c[]; //declaration
c = new int[ 12 ]; //allocation
– One step:int c[] = new int[ 12 ];
– Primitive elements are initialized to zero orfalse while Non-primitive references are
initialized to null
f f
![Page 45: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/45.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 45/118
References and Reference
Parameters Passing arguments to methods
– Call-by-value: pass copy of argument
– Call-by-reference: pass original argument
» Improves performance, weakens security
In Java, you cannot choose how to passarguments
– Primitive data types passed call-by-value
– References to objects passed call-by-reference» Original object can be changed in method
– Arrays in Java treated as objects
» Passed call-by-reference
P i A t
![Page 46: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/46.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 46/118
Passing Arrays to
Functions Passing arrays
– Specify array name without brackets
int myArray[ 24 ];
myFunction( myArray );
– Arrays passed call-by-reference
» Modifies original memory locations
– Header for method modifyArray might be
void modifyArray( int b[] ) Passing array elements
– Passed by call-by-value
– Pass subscripted name (i.e., myArray[3]) to method
![Page 47: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/47.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 47/118
Multiple-Subscripted Arrays Represent tables
– Arranged by m rows and n columns ( m by n array)
– Can have more than two subscripts
Array of arrays
– Fixed rows and columns arrayType arrayName[][] = new
arrayType[ numRows ][ numColumns ];int b[][] = new int[ 3 ][ 3 ];
– Initializer lists
arrayType arrayName[][] = { { row1 sub-list},{ row2 sub-list}, ... };
» int b[][] = { { 1, 2 }, { 3, 4 } };
![Page 48: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/48.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 48/118
Java Applets
Java applets are programs that run on a java enabledbrowser. Java applets do not have main methods.
To compile your program, use command:c:\> javac MyAppletName.java
To run your program, use command:c:\> appletviewer my_html.html
Applet Developint Process:
– Step 1: Write the applet program
– Step 2: compile .java file and get .class file
– Step 3: create HTML file
– Step 4: test the applet using appletviewer
– Step 5: Publish the applet
![Page 49: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/49.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 49/118
What can an applet do?
Applets can use almost all java API capabilities.
Applets have a great graphical capabilities.
Applets can play sounds. Applets make the web page extremely interactive
Applets can usually make network connections to the
host they came from.
Applets can interact with other applets on the same
page.
![Page 50: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/50.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 50/118
What can an applet not do?
An applet cannot load libraries or define nativemethods.
It cannot read or write files on the host that'sexecuting it.
It cannot make network connections except to thehost that it came from.
It cannot start any program on the host that's
executing it. It cannot read certain system properties.
Windows that an applet brings up look different thanwindows that an application brings up.
![Page 51: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/51.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 51/118
HTML Applet Tag
<HTML>
< APPLET
CODE = appletFile
WIDTH = pixels
HEIGHT = pixels
>
</APPLET>
</HTML>
![Page 52: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/52.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 52/118
Java
Implementation of The OOP Model
Part 3
![Page 53: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/53.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 53/118
Introduction
Java is a full object-oriented programming language.
Java supports:
– Classes
– Abstract Classes
– Inner classes – Interfaces
Java OOP is build on the single rooted hierarchy which means
that all classes should be inherited from a single base class. In
Java the name of this ultimate base class is simply “Object”. A class in Java represent a data type that Encapsulates data
(attributes) and methods (behaviors) that are closely related.
The class is the unit of Java programming.
C i P k
![Page 54: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/54.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 54/118
Creating Packages (1)
Packages – Directory structures that organize classes and interfaces
– Mechanism for software reuse
Creating packages
– Create a public class
» If not public, can only be used by classes in same package
– Choose a package name and add a package statement to
source code file
– Compile class (placed into appropriate directory)
– Use Java standards in naming the packages.
![Page 55: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/55.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 55/118
Creating Packages (2)
import – Use import when classes are not of same package.
– If no package specified for a class, it is put in the defaultpackage which includes compiled classes of the current
directory – If class in same package as another, import not required
Follow these steps to create a package:
– Create a directory called classes inside directoryc:\jdk1.2\jre\
– Use the following command for compilation: javac –d c:\jdk1.2\jre\classes MyClasse.java
– Once the package has been created you can use importstatement to use its classes.
![Page 56: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/56.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 56/118
Creating Java Classes (1)
A class in Java is just a blueprint telling what the
objects created from it will look and act like.
Every class in Java is a subclass of the ultimate
base class “Object” Every Class has three components:
– Instance variables (Class Attributes).
– Member methods (Class Behavior)
– Constructors. ( For initialization and consistency)
Class body is delineated by braces { }
![Page 57: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/57.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 57/118
Creating Java Classes (2)
Cl D l i
![Page 58: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/58.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 58/118
Class Declarations For class declaration, we use
one or more of the following: – public = the class can be used by
any class regardless of its package.
– abstract = the class cannot beinstantiated.
– final = that the class cannot besubclassed.
– class NameOfClass = to indicateto the compiler that this is a classdeclaration and that the name of the class is NameOfClass .
– extends Super = to identifySuper as the superclass of theclass.
– implements Interfaces = todeclare that the class implements
one or more interfaces.
![Page 59: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/59.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 59/118
![Page 60: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/60.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 60/118
Declaring Member Variables
Member variables represent the state of the object.
They should be initialized in some way whencreating the object to make sure that the object isin a consistent state.
We use modifiers when declaring Membervariables.
![Page 61: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/61.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 61/118
Method Declaration
Methods are the ways through which objectscommunicate with each other
A method's declaration provides a lot of information about the method to the compiler, to
the runtime system, and to other classes andobjects
We use modifiers when declaring Methods.
![Page 62: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/62.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 62/118
Methods Overriding
Overriding a method in a subclass means re-
writing or modifying its code so that it acts
differently from what it used to.
Method overriding is related to a very
important feature of OOP known as
“polymorphism”
Example: Overriding methods init() orpaint() in applets.
M i I h it
![Page 63: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/63.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 63/118
Managing Inheritance (1)
Inheritance is a form of software reusability where – New classes created from existing ones
– Subclasses absorb super-classes’ attributes and behaviors, and add in
their own.
The Object class defines and implements behavior that every
class in the Java system needs. The following will be the
hierarchy that every class in Java will end up part of.
M i I h it
![Page 64: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/64.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 64/118
Managing Inheritance (2)
What Members Does a Subclass Inherit? – Subclasses inherit those superclass members declared as public or
protected.
– Subclasses inherit those superclass members declared with no accessspecifier as long as the subclass is in the same package as the superclass.
– Subclasses don't inherit a superclass's member if the subclass declares amember with the same name.
Hiding Member Variables
– Member variables defined in the subclass hide member variables thathave the same name in the superclass. While this feature of the Java
language is powerful and convenient, it can be a fruitful source of errors.
Overriding Methods
– The ability of a subclass to override a method in its superclass allows aclass to inherit from a superclass whose behavior is "close enough" andthen supplement or modify the behavior of that superclass.
![Page 65: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/65.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 65/118
Managing Inheritance (3)
A Subclass is more specific than a superclass
Every subclass can be described by its
superclass, but not vice-versa Unlike C++, Java does not support multiple
inheritance.
To inherit from a class use keyword extends
class TwoDimensionalShape extends Shape
{ ... }
Inheritance does also apply to Java interfaces.
Being a Descendent of
![Page 66: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/66.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 66/118
Being a Descendent of
Object(1)
The Object class sits at the top of the class hierarchy
tree in the Java platform. This class defines the basic
state and behavior that all objects must have.
Your classes may want to override the following
Object methods:
clone - equals/hashCode - finalize -
toString
Your class cannot override these Object methods:
getClass - notify - notifyAll - wait
Being a Descendent of
![Page 67: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/67.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 67/118
Being a Descendent of
Object (2)
The clone Method:You use the clone method tocreate an object from an existing object.
The finalize Method: The Object class provides a
method, finalize, that cleans up an object before it isgarbage collected.
The toString Method: Object's toString methodreturns a String representation of the object.
The getClass Method: The getClass method is afinal method that returns a runtime representation of the class of an object.
Controlling Access to
![Page 68: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/68.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 68/118
Controlling Access to
Class Members (1)
In Java, you can use access specifiers to protect both a
class's variables and its methods when you declare them.
The Java language supports four distinct access levels for
member variables and methods: private, protected,public, and, if left unspecified, package.
Private:
– The most restrictive access level is private.
– A private member is accessible only to the class in which it
is defined. Inheritance does not apply on the private
members. They are Just like secrets.
– Use private keyword to create private members.
Controlling Access to
![Page 69: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/69.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 69/118
Controlling Access to
Class Members (2)
Protected:
– Allows the class itself, subclasses, and all
classes in the same package to access the
members. – Use the protected access level when it's
appropriate for a class's subclasses to have
access to the member, but not unrelated classes.
Protected members are like family secrets.
– To declare a protected member, use the
keyword protected
Controlling Access to
![Page 70: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/70.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 70/118
Controlling Access to
Class Members (3)
Public:
– The easiest access specifier is public.
– Any class, in any package, has access to a class'spublic members.
– Declare public members only if such accesscannot produce undesirable results if an outsideruses them.
– There are no personal or family secrets here; thisis for stuff you don't mind anybody else knowing.
– To declare a public member, use the keyword
public.
Controlling Access to
![Page 71: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/71.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 71/118
Controlling Access to
Class Members (4)
Package
– The package access level is what you get if you don't
explicitly set a member's access to one of the other levels.
– This access level allows classes in the same package as yourclass to access the members. This level of access assumes
that classes in the same package are trusted friends.
To summarize:Specifier class subclass package world
private X
protected X X X
public X X X X
package X X
Class Scope
![Page 72: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/72.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 72/118
Class Scope Class scope
– Includes Instance variables and methods
– Class members are accessible to class methods. They can bereferenced simply by name.
– Outside scope, cannot be referenced by name
– Visible ( public) members accessed through a handleobjectReferenceName.variableName or .methodName()
– Static public members can be accessed through class namelike:Color.red, Font.PLAIN, System.out.print(“”);
Block scope
– Variables defined in a method known only to that method
– If variable has same name as class variable, class variable ishidden in that method.
final Variables,
![Page 73: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/73.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 73/118
final Variables,
Methods, and Classes Declaring variables final
– Indicates they cannot be modified after declaration
– Indicate that they are constants
– Must be initialized when declared. Can not be changed
after that – Use all-caps identifiers. Example:
private final int INCREMENT = 5;
Declaring methods final – Cannot be overridden in a subclass
– static and privatemethods are implicitly final
Declaring classes final – Cannot be a super-class (cannot inherit from it)
– All methods in class are im licitl final
Static Class Members
![Page 74: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/74.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 74/118
Static Class Members (1) Static variables
– Class data members are divided into two groups:
» Instance variables: every object of the class has its own copies of them.
» Class variables: they are allocated once for the class. All objects of class share the same variable.
– Keyword static is used to create class variables.
– static class variables shared among all objects of class
» One copy for entire class to use
» static class variables exist even when no objects do
– public static members» Accessed through references or class name and dot operator
» MyClass.myStaticVariable
– private static members
» Accessed through class methods.
Static Class Members
![Page 75: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/75.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 75/118
Static Class Members (2)
static methods
– Can only access static members
– Have no this reference
» static variables are independent of objects
– They can be called even if no object is created.
Examples:
– The main method in public static void main(String []args)
– Method exit() inSystem.exit();
– Method showMessageDialog() in JOptionPane.showMessageDialog(. . .);
Initializing Objects
![Page 76: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/76.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 76/118
Initializing Objects
Initialization is a must every time an object is createdout of a class.
Java compiler will initialize all class members and
creating default constructors that initialize data
members as follows: 0 for primitive numeric types,false for boolean, null for references.
Initialization mainly happened in the class
constructors.
A class could have more than one way (constructor)
of initialization.
Initializers are passed as arguments to constructor
Obj I i i
![Page 77: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/77.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 77/118
Object Instantiating
Classes only describe data types. To put thenin use at runtime, objects have to be created(instantiated) from them.
“new” keyword is used to instantiate an objectfrom a class. Example:
public Font myFnt = new
Font(“Arial”, Font.ITALIC, 12); No objects can be instantiated from Abstract
classes. You can not use new here.
![Page 78: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/78.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 78/118
Composition
Composition means that a class hasreferences to other objects as members
» These objects have to be initialized.
» Default constructor or available constructors areused to initialize these objects.
Composition is a powerful way of
software re-use Composition is related to the “has a”
relationship in the OOP model.
U i thi R f
![Page 79: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/79.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 79/118
Using this Reference
Each object has a reference to itself . It is called
this reference
Implicitly used to refer to instance variables
and methods Used inside methods
– If a parameter or a local variable has the same name
as an instance variable, use this.variableName
to explicitly refer to the instance variable. UsevariableName to refer to the parameter
It helps clarify the program logic.
Ab t t Cl
![Page 80: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/80.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 80/118
Abstract Classes
Sometimes, a class that you define represents an abstract conceptand, as such, should not be instantiated.
For example, the Number class in the java.lang packagerepresents the abstract concept of numbers. Number class makessense only as a superclass to classes like Integer or Float.
An abstract class is a class that can only be subclassed-- it cannotbe instantiated.
To declare that your class is an abstract class, use the keywordabstract before the class keyword in your class declaration:
abstract class Number { . . . } An abstract class may contain abstract methods, that is, methods
with no implementation. In this way, an abstract class can define acomplete programming interface, thereby providing its subclasseswith the method declarations for all of the methods necessary to
implement that programming interface.
I Cl
![Page 81: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/81.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 81/118
Inner Classes
Inner classes are classes defined inside other
classes.
Inner classes have access to all the members of the
outer classes. Usually we use inner classes as helper classes of
adapter classes.
Inner classes can be anonymous (without names)
They are used intensively to write event listeners
such as ActionListener, MouseListener,
KeyListener, and the like.
J I t f
![Page 82: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/82.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 82/118
Java Interfaces (1)
An interface defines a protocol of behavior that can beimplemented by any class anywhere in the classhierarchy.
An interface defines a set of methods but does not
implement them. A class that implements the interfaceagrees to implement all the methods defined in theinterface, thereby agreeing to certain behavior.
An interface is not part of the class hierarchy.
Unrelated classes can implement the same interface. Two elements are required in an interface declaration--
the interface keyword and the name of the interface.The public access specifier indicates that the interface
can be used by any class in any package.
Java Interfaces (2)
![Page 83: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/83.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 83/118
Java Interfaces (2)
An interface can inherit from one or more comma-
separated superinterfaces using keyword extends.
The interface body contains method declarations ; each
followed by a semicolon (;). All methods declared in an
interface are implicitly public and abstract. An interface can also contain constant declarations. All
constant values defined in an interface are implicitly
public, static, and final.
Implementing an Interface
![Page 84: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/84.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 84/118
Implementing an Interface An interface defines a protocol of behavior. A class
that implements an interface adheres to the protocoldefined by that interface.
To declare a class that implements an interface, includean implements clause in the class declaration.
Your class can implement more than one interface (theJava platform supports multiple inheritance forinterfaces. For instance,public class StockApplet extends Applet
implements StockWatcher {
public void valueChanged(String
tickerSymbol, double newValue){…}
…
![Page 85: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/85.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 85/118
Java Programming Styles
![Page 86: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/86.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 86/118
Java Programming Styles(1)
Packages: – Package names are entirely in lower case.
– Package name should start with the web domainname reversed
– Examples: package com.sun.java.lang;
package edu.nmsu.is.us.sp;
Files:
– The file name must have the same base name as thename of the public class defined in the file.
– Example:
If you have a public class named “RecordList”, the filecontaining this class should be named RecordList.java
Java Programming Styles
![Page 87: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/87.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 87/118
Java Programming Styles(2)
Classes and Interfaces:
– Use meaningful identifiers for classes ,and interfaces.
– Capitalize each word contained in aclass identifier name.
– No underscores.
– Examples: public class RecordList {…}
public interface PanelFace {…}
Java Programming Styles
![Page 88: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/88.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 88/118
Java Programming Styles(3)
Variables:
– Use meaningful identifiers for variables.
– Capitalize each word contained in a name of avariable except the first word.
– Use nouns to identify variables as possible. – For boolean variables, use identifirs that are like
questions.
– Use all-caps indentifiers for constants.
– Examples: int number;
String myName;
boolean isValid;
final int CODE = 707;
Java Programming Styles
![Page 89: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/89.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 89/118
Java Programming Styles(4)
Methods: – Use meaningful identifiers for methods.
– Capitalize each word contained in a name of amethod except the first word.
– Use verbs to identify methods as possible. – For the methods dealing with objects’ properties,
start the method identifier with get or set.
– If the method returns boolean use “is” or “are”
instead of get to name this method. – Examples:
private boolean paint()…
boolean isObjectValid()…
Font getFont()…
void setFont(Font f)…
Java Programming Styles
![Page 90: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/90.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 90/118
Java Programming Styles(5)
General Considerations: – Use three-space indentation style. Example
if(num < 10)
{
System.out.println(“Not Enough”);}
– Use comments to mark the beginning and the end of blocks
– Use three-line style to comment your code. Use either one of:
// /*
// This part is to … or * This part is to … // */
– Use empty lines to increase the readability of your code
– Use spaces between the operators such as +, -, =, … and theoperands. Example:
c = a + b;
![Page 91: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/91.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 91/118
Using Set and Get Methods
![Page 92: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/92.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 92/118
Using Set and Get Methods Set methods (Mutator methods)
– public method that sets private variables
– Does not violate notion of private data
» Change only the variables you want
– Called mutator methods (change value)
Get methods (Accessor methods)
– public method that displays private variables
– Again, does not violate notion of private data
» Only display information you want to display
– Also called accessor or query methods
If implementation changes
– Clients can still use the same methods
– Do not know implementation details
Documentation Generator
![Page 93: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/93.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 93/118
Documentation Generator
Java has its own standard tool for creatingAPI documentation on the fly. This tool is“ javadoc”.
javadoc goes through the source fileslooking for a comment of the style /** …*/ to add to the documentation.
The result of the javadoc utility is HTMLdocumentation that is the same as the Javastandard API documentation in format.
PART 5
![Page 94: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/94.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 94/118
Java Essential API
PART 5
![Page 95: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/95.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 95/118
Java I/O
![Page 96: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/96.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 96/118
Java I/O Java I/O capabilities are based on the concept of “streams”.
A stream is an ordered sequence of bytes that have a source anddestination like this
Java stream classes are divided into two class hierarchies, based on
the data type (either characters or bytes) on which they operate.
Generally, the algorithms for sequentially reading and writing dataare basically the same:
Reading Writing
open a stream open a stream
while more information while more information
read information write information
close the stream close the stream
Character Streams
![Page 97: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/97.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 97/118
Character Streams
Byte Streams
![Page 98: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/98.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 98/118
Byte Streams
Standard I/O
![Page 99: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/99.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 99/118
Standard I/O
The term standard I/O refers to the Unixconcept of a single stream of information thatis used by a program.
Following the standard I/O model, Java has
System.in, System.out, and System.err. System.out, and System.err are already
pre-wrapped as a PrintStream object, sothey can be used write away.
System.in must be wrapped as before youcan read from it.
Standard I/o Example
![Page 100: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/100.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 100/118
Standard I/o-Example
import java.io.*; public class StdInRead {
public static void main(String[] args)
throws IOException
{
System.err.print("Enter Your input. Empty line to exit.\n");
BufferedReader in =
new BufferedReader(
new InputStreamReader(System.in));
String s;
while((s = in.readLine()).length() != 0)
System.out.println("YOU ENTERED: " + s);
}
}
Accessing File System
![Page 101: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/101.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 101/118
Accessing File System
Java provides class File to let you deal with the filesand directories.
It is an abstract representation of file and directorypathnames.
Using File you can do things like:
– Checking whether or not files exists/Deleting them
– Creating/renaming/listing contents of directories
– Checking the path names
– Creating new files
– Creating the URL of the files
Using File An Example
![Page 102: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/102.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 102/118
Using File – An Example
import java.io.*;public class Files
{
public static void main (String []args)
{File d = new File("c:/jdk1.3/bin");
File[] f= d.listFiles();
for(int i = 0; i < f.length; i++)
System.out.println(f[i]);}
}
Reading / writing Files
![Page 103: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/103.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 103/118
Reading / writing Filesimport java.io.*;
public class Copy {
public static void main(String[] args)throwsIOException {
File inputFile = new File(“oldfile.txt");
File outputFile = new File(“newfile.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new
FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}
Concatenating Files
![Page 104: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/104.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 104/118
Concatenating Filesimport java.io.*;
public class Concatenate {public static void main(String[] args) throws
IOException {
File inF1 = new File(“f1.txt");
File inF2 = new File(“f2.txt");
FileInputStream in1 = new FileInputStream(inF1);FileInputStream in2 = new FileInputStream(inF2);
SequenceInputStream s = newSequenceInputStream(in1, in2);
int c;
while ((c = s.read()) != -1)
System.out.write(c);
s.close();
}
}
Object Serialization
![Page 105: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/105.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 105/118
Object Serialization
Java’s object serialization allows you to take any object thatimplements the Serializable interface and turn it into a sequence of bytes that can later be fully restored to regenerate the originalobject.
Object serialization is interesting because it allows you toimplement lightweight persistence.
Object serialization was added to the language to support two majorfeatures; Java’s (RMI) and JavaBeans.
To serialize an object, you create some sort of OutputStream
object and then wrap it inside an ObjectOutputStream object. Atthis point you need only call writeObject( ) and your object isserialized and sent to the OutputStream. To reverse the process,you wrap an InputStream inside an ObjectInputStream and callreadObject( ).
Object Serialization
![Page 106: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/106.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 106/118
jimport java.io.*;
class Data implements Serializable {int i;
Data(int x) { i = x; }
public String toString() { return "THE DATA IS " + i; }
}
public class Serialize {
public static void main(String[] args)throws IOException, ClassNotFoundException {
Data dout = new Data(100);
System.out.println("OUT OBJECT:: " + dout.toString());
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("data.out"));
out.writeObject(dout); out.close();ObjectInputStream in = new ObjectInputStream(
new FileInputStream("data.out"));
Data di = (Data) in.readObject(); in.close();
System.out.println("IN OBJECT:: " + di.toString());
}
}
JDBC
![Page 107: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/107.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 107/118
J(Introduction)
A great promise of Java has been the ability to build platform-independent client/server database applications. This has cometo fruition with Java DataBase Connectivity (JDBC).
JDBC is designed to be platform-independent, so you don’t need
to worry about the database you’re using while you’reprogramming
JDBC, like many of the APIs in Java, is designed for simplicity.The method calls you make correspond to the logical operationsyou’d think of doing when gathering data from a database:
connect to the database, create a statement and execute thequery, and look at the result set.
To allow this platform independence, JDBC provides a driver manager that dynamically maintains all the driver objects thatyour database queries will need
Database URL
![Page 108: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/108.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 108/118
Database URL
To open a database, you must create a “databaseURL” that specifies:
– That you’re using JDBC with “jdbc.”
– The “subprotocol”: the name of the driver or the name of
a database connectivity mechanism. Since the design of JDBC was inspired by ODBC, the first subprotocolavailable is the “jdbc-odbc bridge,” specified by “odbc.”
– The database identifier. This varies with the databasedriver used, but it generally provides a logical name that
is mapped by the database administration software to aphysical directory where the database tables are located.In windows it is usually called DSN.
Example:
String dbUrl = "jdbc:odbc:people";
Getting JDBC To Work (1)
![Page 109: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/109.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 109/118
Getting JDBC To Work (1)
STEP 1: Find the JDBC Driver – To Locate the driver we use the following:
try{Class.forName("sun.jdbc.odbc.JdbcOd
bcDriver");
}
catch(SQLException exp){System.err.println("Failed to
connect");}
– If the statement above does not catch anyexceptions it means that the driver is loading
properly.
Getting JDBC To Work (2)
![Page 110: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/110.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 110/118
Getting JDBC To Work (2)
STEP 2: Configure the database
– From Control Panel create a DSN for your data
base
– The DSN you create in this step will part of thedatabase URL discussed in a previous slide
– Example:
If your DSN is named “emaildsn”, the database
URL will be like:
String dbUrl = "jdbc:odbc:emaildsn";
Getting JDBC To Work (3)
![Page 111: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/111.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 111/118
STEP 3: Connect and Test the Configuration – We use the following to connect to a datadase:
try{
Connection c = DriverManager.getConnection(
dbUrl, user, password);}
catch(SQLException exp){System.err.println("Failed to connect");
}
– If the statement above does not catch anyexceptions, it means that the configurations arecorrect and the connection is established properly.
Getting JDBC To Work (3)
Getting JDBC To Work (4)
![Page 112: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/112.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 112/118
STEP 4: Generate your SQL Queries – Use something like:
Statement s = c.createStatement();
ResultSet r = s.executeQuery( “SQL QUERY");
– The ResultSet object “r” contains the result comingback from the database. The following loop can be usedto print the results.while(r.next()) {
System.out.println(
r.getString(“FIELD 1") + ", "
+ r.getString(“FIELD 2“) + . . .);
}
– Close the statement and result ser objects using:s.close();
Getting JDBC To Work (4)
![Page 113: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/113.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 113/118
Batch Jobs
![Page 114: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/114.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 114/118
Batch Jobs
JDBC allows programmers to create a list of SQL commands that can be sent as a batchto the database drivers.
Use method addBatch(Stringsql) in a statement object to add thegiven SQL command to the current list of commands for this Statement object.
The commands in this list can beexecuted as a batch by calling the methodexecuteBatch().
Part 6
![Page 115: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/115.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 115/118
Advanced Java
Features
Part 6
Exception Handling
![Page 116: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/116.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 116/118
Exception Handling
The basic philosophy of Java is that“badly formed code will not be run.”
The ideal time to catch an error is at
compile-time, before you even try to runthe program. However, not all errorscan be detected at compile-time. Therest of the problems must be handled at
run-time.
Introduction To
![Page 117: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/117.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 117/118
Multithreading Programs
References
![Page 118: Java 2 Presentation](https://reader030.vdocuments.us/reader030/viewer/2022021117/577d231c1a28ab4e1e98ff29/html5/thumbnails/118.jpg)
8/3/2019 Java 2 Presentation
http://slidepdf.com/reader/full/java-2-presentation 118/118
References
Detiel and Detiel, Java 2: How to program
Bruce Eckel, Thanking in Java
Java Tutorial athttp://java.sun.com/docs/books/tutorial/index.html
Cay S. Horstmann, Core Java 2 Vol. I