J2EE (Workshop) : Dhiraj Thakkar (SEG-Director) (MS-IT, SE-J2EE Application 2.5 Years)

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 192

J2EE (Workshop)

Dhiraj Thakkar (SEG-Director)

(MS-IT,SE-J2EE Application 2.5 years)


Course Map

 Core Java
 Web Application

 XML

 JSF (Java Server Faces)

 EJB (Enterprise Java Beans)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Course Map
Core Java

 Object Oriented Features


 Java Introduction
 Java Features
 How Java Differs from other OO languages
 Java and the World Wide Web
 Java Environment
 Build Your First Java Program
 Practice Exercise
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Course Map

 Core Java
 Web Application

 XML

 JSF (Java Server Faces)

 EJB (Enterprise Java Beans)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Course Map
Web Application

 Features of Web Application


 Servlet Programming
 JSP (Java Server Pages)
 Deploying Web Application
 MVC Architecture
 Creating Data source

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Course Map

 Core Java
 Web Application

 XML

 JSF (Java Server Faces)

 EJB (Enterprise Java Beans)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Course Map
XML

 Principles of XML
 Creating XML
 Validating XML
 Viewing XML
 XML Vocabularies
 DTD (Document Type
Definition)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Course Map

 Core Java
 Web Application

 XML

 JSF (Java Server Faces)

 EJB (Enterprise Java Beans)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Course Map
JSF (Java Server Faces)

 JSF framework
 To master configuring JSF
 How JSF integrates with JSP
 How to use JSF UI components
 Navigation and event handling
 JSF form validation framework
 Custom JSF components

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Course Map

 Core Java
 Web Application

 XML

 JSF (Java Server Faces)

 EJB (Enterprise Java Beans)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Course Map
EJB (Enterprise Java Beans)

 EJB architecture and concepts


 EJB roles, Main EJB framework
 EJB interfaces and EJB bean
 EJB deployment descriptor, EJB client view
 Client EJB interaction
 Session ,Entity ,Message-Driven Beans

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Tools & Tech
IDE Tools

 Eclipse 3.1(IDE for Java Development)

 Dream Weaver MX

 WSAD 5.x(Websphere Application Developer)

 NetBeans

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Tools & Tech
Servers

 Apache Tomcat 5.5

 IBM Websphere Application Server 5.1

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Object-Oriented

 Java supports OOD

 Objects and Classes


 Polymorphism
 Inheritance
 Encapsulation
 Java programs contain nothing but
definitions and instantiations of classes
 Everything is encapsulated in a class!

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Objects

 Objects can be described in terms of:


 Their attributes
 Their behaviors
 Object’s attributes and behaviors are
encapsulated together a data type.
 Objects have a lifecycle:
 Creating objects
 Manipulating objects
 Cleaning up objects

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Object Oriented Paradigm
OOP allows us to decompose a problem into a number of entities objects
and then build data and function around these entities. The combination of
data and methods make up an object

Method Method

Data

Method
Method

Object = Data + Method

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Object and Class
Objects are the basic runtime entities in an object oriented system.

Object
Person

Name Data

BasicPay

Salary()
Methods

Tax()

Representation of an object

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Data Abstraction and Encapsulation
The Wrapping up of data and methods into a single unit is known as encapsulation. Abstraction refers to
the act of representing essential features without including the background details or explanations.
Class Sample{

Information “in” Data Information “out”


and
Method

Encapsulation-Object as “black boxes”

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Inheritance
Inheritance is the process by which object of one class acquire the
properties of objects of another class.
Bird
Attributes:
Feathers
Lay eggs
Nonflying
flying Bird Bird
Attributes: Attributes:

Robin Swallow Penguin Kiwi


Attributes: Attributes: Attributes: Attributes:

Property Inheritance
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Polymorphism
Polymorphism is another important OOP concept.
Polymorphism means ability to take more than one form.

Shape

Draw()

Circle Object Box Object Triangle Object

Draw (circle) Draw (box) Draw (triangle)

Polymorphism

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java - An Introduction

 Java - The new programming language


developed by Sun Microsystems in 1991.
 Originally called Oak by James Gosling,
one of the inventors of the Java
Language.
 Java -The name that survived a patent
search
 Java Authors: James , Arthur Van , and
others

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


It was meant to!!
A programming language for appliances!

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Must Run on Any Architecture
debug
“WRITE ONCE, RUN ANYWHERE!”
pretty portable
Program Java Java
in Java Compiler Bytecode

Java Virtual Machine Java Virtual Machine

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java Milestones
Year Development
1990 Sun decided to developed special software that could be
used for electronic devices. A project called Green Project
created and head by James Gosling.
1991 Explored possibility of using C++, with some updates
announced a new language named “Oak”

1992 The team demonstrated the application of their new


language to control a list of home appliances using a
hand held device.
1993 The World Wide Web appeared on the Internet and
transformed the text-based interface to a graphical rich
environment. The team developed Web applets (time
programs) that could run on all types of computers
connected to the Internet.
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Java Milestones
Year Development
1994 The team developed a new Web browsed called “Hot
Java” to locate and run Applets. HotJava gained instance
success.
1995 Oak was renamed to Java, as it did not survive “legal”
registration. Many companies such as Netscape and
Microsoft announced their support for Java
1996 Java established itself it self as both 1. “the language for
Internet programming” 2. a general purpose OO
language.
1997- A class libraries, Community effort and standardization,
Enterprise Java, Clustering, etc..

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Sun white paper defines Java as:

 Simple and Powerful


 Safe
 Object Oriented
 Robust
 Architecture Neutral and Portable
 Interpreted and High Performance
 Threaded
 Dynamic

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java Attributes
 Familiar, Simple, Small
 Compiled and Interpreted
 Platform-Independent and Portable
 Object-Oriented
 Robust and Secure
 Distributed
 Multithreaded and Interactive
 High Performance
 Dynamic and Extensible

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java is Compiled and Interpreted

Hardware and
Programmer
Operating System

Source Code Byte Code


Text Editor Compiler Interpreter
.java file .class file
Notepad, javac java
emacs,vi appletviewer
netscape

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Compiled Languages

Programmer

Source Code Object Executable


Code Code
Text Editor Compiler linker
.c file .o file a.out file
Notepad, gcc
emacs,vi

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Total Platform Independence

JAVA COMPILER
(translator)

JAVA BYTE CODE


(same for all platforms)

JAVA INTERPRETER
(one for each different system)

Windows 95 Macintosh Solaris Windows NT


Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Architecture Neutral & Portable

 Java Compiler - Java source code (file


with extension .java) to bytecode (file
with extension .class)

 Bytecode - an intermediate form, closer


to machine representation

 A interpreter (virtual machine) on any


target platform interprets the bytecode.
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Architecture Neutral & Portable

 Porting the java system to any new


platform involves writing an interpreter.

 The interpreter will figure out what the


equivalent machine dependent code to
run

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Rich Class Environment

 Core Classes
language
Utilities
Input/Output
Low-Level Networking
Abstract Graphical User Interface
 Internet Classes
TCP/IP Networking
WWW and HTML
Distributed Programs

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


How Does Java Compares to C+
+ and Other OO Languages
Overlap of C, C++, and Java
Java First Cousin of C++ and Second Cousin of C
Superset of C

C++

C Java

Subset of C++
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
 Java better
Typedefs, Defines, orthan C++
Preprocessor ?
 No Global Variables
 No Goto statements

?
 No Pointers
 No Unsafe Structures
 No Multiple Inheritance
 No Operator Overloading

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Object Oriented Languages -A Comparison

Feature C++ Java

Encapsulation Yes Yes


Inheritance Yes Yes
Multiple Inherit. Yes No
Polymorphism Yes Yes
Binding (Early or Late) Both Late
Concurrency Poor Yes
Garbage Collection No Yes
Genericity Yes Limited
Class Libraries Yes Yes

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java Integrates
Power of Compiled Languages
and
Flexibility of Interpreted Languages

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java Applications

 We can develop two types of Java


programs:

 Stand-alone applications
 Web applications (applets)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Applications v/s Applets

 Different ways to run a Java executable


are:
Application- A stand-alone program that can be invoked
from command line . A program that has a “main”
main
method

Applet- A program embedded in a web page , to be run


when the page is browsed . A program that contains
no “main” method

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Applets v/s Applications

 Different ways to run a Java executable are


Application- A stand-alone program that can be invoked
from command line . A program that has a “main”
main
method
Applet- A program embedded in a web page , to be run
when the page is browsed . A program that contains no
“main” method
 Application –Executed by the Java
interpreter.
 Applet- Java enabled web browser.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java and World Wide Web

Turning the Web into an


Interactive and Application
Delivery Platform
What is World Wide Web ?
 Web is an open-ended information retrieval
system designed to be used in the Internet
wide distributed system.
 It contains Web pages (created using HTML)
that provide both information and controls.
 Unlike a menu driven system--where we are
guided through a particular direction using a
decision tree, the web system is open ended
and we can navigate to a new document in any
direction.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Execution of Applets

1 2 3 4 5
APPLET hello.class Create Accessing The browser
Development AT SUN’S Applet from creates
“hello.java” WEB tag in Unimelb.edu.au a new
AT SERVER HTML window and
SUN.COM document a new thread
and
then runs the
code

Hello Java
<app=
“Hello”> The Internet
Hello

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Significance of downloading Applets

 Interactive WWW
 Flashy animation instead of static web
pages
 Applets react to users input and
dynamically change
 Display of dynamic data
 WWW with Java - more than a document
publishing medium

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java Development Kit

 javac - The Java Compiler


 java - The Java Interpreter
 jdb- The Java Debugger
 appletviewer -Tool to run the applets
 javap - to print the Java bytecodes
 javaprof - Java profiler
 javadoc - documentation generator
 javah - creates C header files
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Java Environment
Java Development Kit

 javac - The Java Compiler


 java - The Java Interpreter
 jdb- The Java Debugger
 appletviewer -Tool to run the applets
 javap - to print the Java bytecodes
 javaprof - Java profiler
 javadoc - documentation generator
 javah - creates C header files

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Process of Building and Running Java
Programs
Text Editor

Java Source
javadoc HTML Files
Code

javac

Java Class File javah Header Files

java jdb

Outout
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Let us Try Out

Building your first Java Program


Hello Internet

// hello.java: Hello Internet program


class HelloInternet
{
public static void main(String args[])
{
System.out.println(“Hello Internet”);
}
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Comment Styles
 To increase the readability if it.
 Comments are ignored by the compiler.
 Java uses three types of comments:
 Single-line comment(//). Example:
//single-line comment here
 Multiple-line comment(/*…*/). Example:
/*
line 1 here
line 2 here …
*/
 Documentation comment(/**…*/). It is
multiple-line and used with “javadoc” utility
to create application documentation.
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Program Processing

 Compilation
# javac hello.java
results in HelloInternet.class
 Execution
# java HelloInternet
Hello Internet
#

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java Data Types
 Sizes fully specified by Java standard.
 Java is a very strongly typed language
 Integer types
 int (4 bytes )
 short (2 bytes )
 long (8 bytes )
 byte (1 byte )
 Floating-point types
 float (4 bytes) use suffix F (eg 1.28F)
 double( 8 bytes)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Additional Data Types

 char
 Two-byte unicode
 Assignment with ‘ ‘
 e.g. char c = ‘h’;
 boolean
 true or false
e.g. boolean x = true;
if (x){…};

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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;

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Arithmetic Operations

Operation Operator Java Expression


Addition a + 8
+
Subtraction b - 7
-
Multiplication p * 10
*
Division c / 9
/
Modulus b % 6
%
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
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 >= if (X >= y) …


equal
Less than or <= if ( y <= z) …
equal
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Increment /decrement operation

Operator expression Equivalent to

++ count++; Count = count + 1;


++count;
-- --count; Count = count - 1;
Count--;

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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 right operand
 If left operand of && is false, will not evaluate right operand

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Conditional Operator

 the “ternary conditional operator”


 (x < 5) ? 0 : x*.03
 often used in assignment
 result is second operand if condition is
true, third otherwise
 second, third operands only evaluated if
necessary

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Precedence
Operator Associativity High
( ) 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 Low
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Java Key words
Keywords are words reserved for Java and cannot be used as
identifiers or variable names
J a va Ke ywo rd s
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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


If – if/else structures
 if statement looks  If/else statement looks
like: if like:
(condition) { if (condition)
… {
} //do something.
}
 Conditions are
else
evaluated to either
{
true or false
//do something else.
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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;
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
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, body
not executed

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


jumps
 break and continue
 labelled breaks : restricted to labelling
loops and switches
safety:
while (unfinished) {
if (x > 2000 || y < x) { x = 0; continue; }
while (x <= 2000) {
y = computeTally (x);
if (y < x) { // !!!! what?
break safety;
} else unfinished = false;
}
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Methods
 Methods
 Modularize a program
 All variables declared inside methods are local variables
 Known only in method defined
 Benefits
 Divide and conquer
 Manageable program development
 Software reusability
 Existing methods are building blocks for new programs
 Abstraction - hide internal details (library methods)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


return Statement
 When method call encountered
 Control transferred from point of invocation to
method
 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
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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 );

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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 private methods are implicitly final
 Declaring classes final
 Cannot be a super-class (cannot inherit from it)
 All methods in class are implicitly final

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Scope Rules (2)
 Block scope
 Begins at identifier's declaration, ends at terminating brace
 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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Arrays and Strings
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 length c.length

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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
or false while Non-primitive references
are initialized to null
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
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 } };

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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 pass
arguments
 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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Strings

 core Java class, defined in library as


java.lang.String
 our first Java class
 some special treatment syntactically

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


String Operations

 size
 int x = myString.length ();
 equality / comparison
 if (er.equals (”Stamp
Required”))

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


String Operations

 substring
 p = s.substring (0,s.indexOf
(’-’));
 concatenation
 System.out.print (”Hello, “ +
name);

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


String Initialization

 String s = null;
 String t = “”;
 String u = “The letter u.”;
 String v = u;
 Strings are immutable
 StringBuffer is a modifiable
alternative

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Classes And Objects
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.
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Creating Packages
 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.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Creating Packages
 import
 Use import when classes are not of same package.
 If no package specified for a class, it is put in the default
package 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 directory
c:\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 import
statement to use its classes.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Creating Java Classes
 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 { }

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Creating Java Classes (2)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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 be
instantiated.
 final = that the class cannot be
subclassed.
 class NameOfClass = to indicate to the
compiler that this is a class declaration
and that the name of the class is
NameOfClass.
 extends Super = to identify Super as
the superclass of the class.

implements Interfaces = to declare


that the class implements one or
more interfaces.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Class Constructors
 All Java classes have constructors that are used to initialize a new
object of that type.
 A constructor has the same name as the class. Example
public Stack() {
items = new Vector(10);
}
 Java supports name overloading for constructors so that a class can
have any number of constructors. Example:
public Stack(int initialSize) {
items = new Vector(initialSize);
}
 The compiler differentiates these constructors based on the number of
parameters in the list and their types.
 Constructors cannot return values. There is no return type, not even void.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Declaring Member Variables
 Member variables represent the state of the object.
 They should be initialized in some way when creating the
object to make sure that the object is in a consistent state.
 We use modifiers when declaring Member variables.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Method Declaration
 Methods are the ways through which objects
communicate 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 and objects
 We use modifiers when declaring Methods.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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()
or paint() in applets.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Controlling Access to Class Members
 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.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Controlling Access to Class
Members
 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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Controlling Access to Class
Members
 Public:
 The easiest access specifier is public.
 Any class, in any package, has access to a
class's public members.
 Declare public members only if such access
cannot produce undesirable results if an
outsider uses them.
 There are no personal or family secrets here;
this is for stuff you don't mind anybody else
knowing.
 To declare a public member, use the keyword
public.
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Controlling Access to Class
Members
 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 your
class to access the members. This level of access assumes
that classes in the same package are trusted friends.
 To summarize:
Specifie
class subclass package world
r
private X

protected X X X
public X X X X
package X X
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Initializing Objects
 Initialization is a must every time an object is
created out 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
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Object Instantiating
 Classes only describe data types. To put
then in use at runtime, objects have to be
created (instantiated) from them.
 “new” keyword is used to instantiate an
object from 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.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Abstract Classes
 Sometimes, a class that you define represents an abstract
concept and, as such, should not be instantiated.
 For example, the Number class in the java.lang package
represents the abstract concept of numbers. Number class
makes sense only as a superclass to classes like Integer or
Float.
 An abstract class is a class that can only be subclassed-- it
cannot be instantiated.
 To declare that your class is an abstract class, use the
keyword abstract before the class keyword in your class
declaration:
abstract class Number { . . . }

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Abstract Methods
 An abstract class may contain abstract methods, that
is, methods with no implementation. In this way, an
abstract class can define a complete programming
interface, thereby providing its subclasses with the
method declarations for all of the methods necessary to
implement that programming interface.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Interfaces:
A New concept in
JAVA
Java Interfaces
 An interface defines a protocol of behavior that
can be implemented by any class anywhere in the
class hierarchy.
 An interface defines a set of methods but does not
implement them. A class that implements the
interface agrees to implement all the methods
defined in the interface, thereby agreeing to
certain behavior.
 An interface is not part of the class hierarchy.
Unrelated classes can implement the same
interface.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java Interfaces
 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.
 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.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java Interfaces
 An interface can also contain constant
declarations. All constant values defined in an
interface are implicitly public, static, and final.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Implementing an Interface
 An interface defines a protocol of behavior. A class that
implements an interface adheres to the protocol defined by that
interface.
 To declare a class that implements an interface, include an
implements clause in the class declaration.
 Your class can implement more than one interface (the Java
platform supports multiple inheritance for interfaces. For instance,
public class StockApplet extends Applet
implements StockWatcher {
public void valueChanged(String
tickerSymbol, double newValue){…}

}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Inheritance
 Inheritance permits software reusability
 New classes can be created from old classes
 The attributes (data) and behavior (methods) of the old
 class are available to the new class
 New data and methods can be added to the new class also
 Inheritance allows you to write key pieces of code once and
 use it over and over
 This can get kind of confusing, just remember you can write
 lots of simple little C++ or Java programs without using
 inheritance and polymorphism (and you will often be using
 them without knowing it !)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Inheritance
Notation

Base Class
Java.awt.Dialog (or Parent Class
or Superclass)

Is-a relationship
Derived Class
Java.awt.FileDialog (or Child Class
or Subclass)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Inheritance
Subtype
Base Class
Java.awt.Dialog

Is-a relationship

Java.awt.FileDialog Derived Class

 The derived class has all the members (i.e.


attributes and methods) of the base class
 Any object of the derived class can be used in any
context that expect an object of the base class
 fp = new FileDialog() is both an object of class Dialog

and an object of class File Dialog

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Method Binding
Classes Student and Professor
derive from class Person

Method print_mailing_list
is polymorphic

Results depend on the


binding: static or dynamic

Print_mailing_label redefined for student and professor classes

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Method Binding
Static and Dynamic
 In static method binding, method selection
depends on the type of the variable x and y
 Method print_mailing_label() of class person is executed
in both cases
 Resolved at compile time

 In dynamic method binding, method selection


depends on the class of the objects s and p
 Method print_mailing_label() of class student is executed
in the first case, while the corresponding methods for
class professor is executed in the second case
 Resolved at run time

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Polymorphism and Dynamic Binding

 The is-a relationship supports the development of


generic operations that can be applied to objects
of a class and all its subclasses
 This feature is known as polymorphism
 E.g. paint() method is polymorphic (accepts multiple

types)
 The binding of messages to method definitions is
instance-dependent, and it is known as dynamic
binding
 It has to be resolved at run-time
 Dynamic binding requires the virtual keyword in C++

 Static binding requires the final keyword in Java

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Dynamic Binding Implementation

 A common implementation is based on a


virtual method table (vtable)
 Each object keeps a pointer to the vtable that
corresponds to its class

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Dynamic Binding Implementation
 Given an object of class foo, and pointer f
to this object, the code that is used to
invoked the appropriate method would be
this (self)

(polymorphic) method invocation

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Dynamic Binding Implementation
Simple Inheritance
 Derived classes extend the vtable of their
base class
 Entries of overridden methods contain the
address of the new methods

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Dynamic Binding Implementation
Multiple Inheritance
 A class may derive from more that one
base class
 This is known as multiple inheritance
 Multiple inheritance is also implemented
using vtables
 Two cases
 Non-repeated multiple inheritance
 Repeated multiple inheritance

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Dynamic Method Binding
Non-Repeated Multiple Inheritance

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Dynamic Method Binding
Non-Repeated Multiple Inheritance
 The view of this must be corrected, so it
points to the correct part of the objects
 An offset d is use to locate the appropriate
vtable pointer
this  d is known at compile time
(self)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Dynamic Method Binding
Repeated Multiple Inheritance
 Multiple inheritance introduces a semantic problem:
method name collisions
 Ambiguous method names

 Some languages support inherited method renaming

(e.g. Eiffel)
 Other languages, like C++, require a

reimplementation that solves the ambiguity


 Java solves the problem by not supporting multiple

inheritance
 A class may inherit multiple interfaces, but, in the absence
of implementations, the collision is irrelevant

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Benefits of Inheritance

 One view of inheritance is that it provides a


way to specify some properties/behaviors
that all subclasses must exhibit
 Inheritance can be used to re-use code
 Inheritance also provides the ability to
generalize
 A method can be written to work with the
super-class but subclasses can be passed as
arguments

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


A Third Look At Java
A Little Demo
public class Test {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
System.out.println(i/j);
}
}

> javac Test.java


> java Test 6 3
2
>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Exceptions
> java Test
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at Test.main(Test.java:3)
> java Test 6 0
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:4)

In early languages, that’s all that happened: error message,


core dump, terminate.
Modern languages like Java support exception handling.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Outline

 Throwable classes
 Catching exceptions
 Throwing exceptions
 Checked exceptions
 Error handling
 Finally

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Some Predefined Exceptions
Java Exception Code to Cause It

NullPointerException String s = null;


s.length();
ArithmeticException int a = 3;
int b = 0;
int q = a/b;
ArrayIndexOutOfBoundsException int[] a = new int[10];
a[10];

ClassCastException Object x =
new Integer(1);
String s = (String) x;

StringIndexOutOfBoundsException String s = "Hello";


s.charAt(5);

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


An Exception Is An Object
 The names of exceptions are class names,
like NullPointerException
 Exceptions are objects of those classes
 In the previous examples, the Java
language system automatically creates an
object of an exception class and throws it
 If the program does not catch it, it
terminates with an error message

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Throwable Classes
 To be thrown as an exception, an object
must be of a class that inherits from the
predefined class Throwable
 There are four important predefined
classes in that part of the class hierarchy:
 Throwable
 Error
 Exception
 RuntimeException

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Classes derived from Java will only throw
Error are used for Object objects of a class descended
serious, system- from Throwable
generated errors, like
OutOfMemoryError, Throwable
that usually cannot be
recovered from Error Exception

...

RuntimeException ...
Classes derived from Classes derived from
RuntimeException are ... Exception are used
used for ordinary system- for ordinary errors that a
generated errors, like program might want to
ArithmeticException catch and recover from
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Outline

 Throwable classes
 Catching exceptions
 Throwing exceptions
 Checked exceptions
 Error handling
 Finally

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


The try Statement
<try-statement> ::= <try-part> <catch-part>
<try-part> ::= try <compound-statement>
<catch-part> ::= catch (<type> <variable-name>)
<compound-statement>

 Simplified… full syntax later


 The <type> is a throwable class name
 Does the try part
 Does the catch part only if the try part
throws an exception of the given <type>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Example
public class Test {
public static void main(String[] args) {
try {
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
System.out.println(i/j);
}
catch (ArithmeticException a) {
System.out.println("You're dividing by zero!");
}
}
} This will catch and handle any ArithmeticException.
Other exceptions will still get the language system’s default
behavior.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Example
> java Test 6 3
2
> java Test 6 0
You're dividing by zero!
> java Test
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at Test.main(Test.java:3)
 Catch type chooses exceptions to catch:
 ArithmeticException got zero division
 RuntimeException would get both
examples above
 Throwable would get all possible exceptions

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


After The try Statement

 A try statement can be just another in a


sequence of statements
 If no exception occurs in the try part,
the catch part is not executed
 If no exception occurs in the try part, or
if there is an exception which is caught in
the catch part, execution continues with
the statement following the try
statement

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Exception Handled
System.out.print("1, ");
try {
String s = null;
s.length();
}
catch (NullPointerException e) {
System.out.print("2, ");
}
System.out.println("3");

This just prints the line


1, 2, 3

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Throw From Called Method

 The try statement gets a chance to


catch exceptions thrown while the try
part runs
 That includes exceptions thrown by
methods called from the try part

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Example
void f() {
try {
g();
}
catch (ArithmeticException a) {

}
}
 If g throws an ArithmeticException,
that it does not catch, f will get it
 In general, the throw and the catch can
be separated by any number of method
invocations
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
z’s activation
 If z throws an record

exception it does not


y’s activation
catch, z’s activation record

stops…
 …then y gets a chance ...

to catch it; if it doesn’t,


g’s activation
y’s activation stops… record

 …and so on all the way f’s activation


back to f record

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Long-Distance Throws

 That kind of long-distance throw is one of


the big advantages of exception handling
 All intermediate activations between the
throw and the catch are stopped and
popped
 If not throwing or catching, they need
not know anything about it

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Multiple catch Parts
<try-statement> ::= <try-part> <catch-parts>
<try-part> ::= try <compound-statement>
<catch-parts> ::= <catch-part> <catch-parts>
| <catch-part>
<catch-part> ::= catch (<type> <variable-name>)
<compound-statement>
 To catch more than one kind of exception,
a catch part can specify some general
superclass like RuntimeException
 But usually, to handle different kinds of
exceptions differently, you use multiple
catch parts

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Example
public static void main(String[] args) {
try {
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
System.out.println(i/j);
}
catch (ArithmeticException a) {
System.out.println("You're dividing by zero!");
}
catch (ArrayIndexOutOfBoundsException a) {
System.out.println("Requires two parameters.");
}
} This will catch and handle both ArithmeticException
and ArrayIndexOutOfBoundsException

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Example
public static void main(String[] args) {
try {
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
System.out.println(i/j);
}
catch (ArithmeticException a) {
System.out.println("You're dividing by zero!");
}
catch (ArrayIndexOutOfBoundsException a) {
System.out.println("Requires two parameters.");
}
catch (RuntimeException a) {
System.out.println("Runtime exception.");
}
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Overlapping Catch Parts

 If an exception from the try part


matches more than one of the catch
parts, only the first matching catch part
is executed
 A common pattern: catch parts for
specific cases first, and a more general
one at the end
 Note that Java does not allow
unreachable catch parts, or
unreachable code in general
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Outline

 Throwable classes
 Catching exceptions
 Throwing exceptions
 Checked exceptions
 Error handling
 Finally

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


The throw Statement

<throw-statement> ::= throw <expression> ;

 Most exceptions are thrown automatically


by the language system
 Sometimes you want to throw your own
 The <expression> is a reference to a
throwable object—usually, a new one:
throw new NullPointerException();

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Custom Throwable Classes
public class OutOfGas extends Exception {
}

System.out.print("1, ");
try {
throw new OutOfGas();
}
catch (OutOfGas e) {
System.out.print("2, ");
}
System.out.println("3");

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Using The Exception Object
 The exception that was thrown is available
in the catch block—as that parameter
 It can be used to communicate information
from the thrower to the catcher
 All classes derived from Throwable inherit
a method printStackTrace
 They also inherit a String field with a
detailed error message, and a
getMessage method to access it

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Example
public class OutOfGas extends Exception {
public OutOfGas(String details) {
super(details);
}
}
This calls a base-class constructor to
initialize the field returned by
getMessage().

try {
throw new OutOfGas("You have run out of gas.");
}
catch (OutOfGas e) {
System.out.println(e.getMessage());
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


About super In Constructors

 The first statement in a constructor can


be a call to super (with parameters, if
needed)
 That calls a base class constructor
 Used to initialize inherited fields
 All constructors (except in Object) start
with a call to another constructor—if you
don’t include one, Java calls super()
implicitly

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


More About Constructors

 Also, all classes have at least one


constructor—if you don’t include one, Java
provides a no-arg constructor implicitly

public class OutOfGas extends Exception {


}

public class OutOfGas extends Exception {


public OutOfGas() {
super();
} These are equivalent!
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
public class OutOfGas extends Exception {
private int miles;
public OutOfGas(String details, int m) {
super(details);
miles = m;
}
public int getMiles() {
return miles;
}
}
try {
throw new OutOfGas("You have run out of gas.",19);
}
catch (OutOfGas e) {
System.out.println(e.getMessage());
System.out.println("Odometer: " + e.getMiles());
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Outline

 Throwable classes
 Catching exceptions
 Throwing exceptions
 Checked exceptions
 Error handling
 Finally

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Checked Exceptions
void z() {
throw new OutOfGas("You have run out of gas.", 19");
}

 This method will not compile: “The


exception OutOfGas is not handled”
 Java has not complained about this in our
previous examples—why now?
 Java distinguishes between two kinds of
exceptions: checked and unchecked

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Checked Exceptions
Throwable

Error Exception checked


exceptions

...

RuntimeException ...

...

The checked exception classes are Exception and


its descendants, excluding RuntimeException
and its descendants

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


What Gets Checked?

 A method that can get a checked


exception is not permitted to ignore it
 It can catch it
 That is, the code that generates the exception
can be inside a try statement with a catch
part for that checked exception
 Or, it can declare that it does not catch it
 Using a throws clause

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


The Throws Clause
void z() throws OutOfGas {
throw new OutOfGas("You have run out of gas.", 19);
}

 A throws clause lists one or more


throwable classes separated by commas
 This one always throws, but in general,
the throws clause means might throw
 So any caller of z must catch OutOfGas,
or place it in its own throws clause

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


 If z declares that it z’s activation
record
throws OutOfGas…
y’s activation
 …then y must catch it, record

or declare it throws it
too… ...

 …and so on all the way


g’s activation
back to f record

f’s activation
record

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Why Use Checked Exceptions

 The throws clause is like documentation:


it tells the reader that this exception can
result from a call of this method
 But it is verified documentation; if any
checked exception can result from a
method call, the compiler will insist it be
declared
 This can make programs easier to read
and more likely to be correct

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


How To Avoid Checked Exceptions

 You can always define your own


exceptions using a different base class,
such as Error or Throwable
 Then they will be unchecked
 Weigh the advantages carefully

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Outline

 Throwable classes
 Catching exceptions
 Throwing exceptions
 Checked exceptions
 Error handling
 Finally

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Handling Errors

 Example: popping an empty stack


 Techniques:
 Preconditions only
 Total definition
 Fatal errors
 Error flagging
 Using exceptions

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Preconditions Only

 Document preconditions necessary to


avoid errors
 Caller must ensure these are met, or
explicitly check if not sure

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


/**
* Pop the top int from this stack and return it.
* This should be called only if the stack is
* not empty.
* @return the popped int
*/
public int pop() {
Node n = top;
top = n.getLink();
return n.getData();
}

if (s.hasMore()) x = s.pop();
else …

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Drawbacks

 If the caller makes a mistake, and pops


an empty stack:
NullPointerException
 If that is uncaught, program crashes with an
unhelpful error message
 If caught, program relies on undocumented
internals; an implementation using an array
would cause a different exception

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Total Definition

 We can change the definition of pop so


that it always works
 Define some standard behavior for
popping an empty stack
 Like character-by-character file I/O in C:
an EOF character at the end of the file
 Like IEEE floating-point: NaN and signed
infinity results

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


/**
* Pop the top int from this stack and return it.
* If the stack is empty we return 0 and leave the
* stack empty.
* @return the popped int, or 0 if the stack is empty
*/
public int pop() {
Node n = top;
if (n==null) return 0;
top = n.getLink();
return n.getData();
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Drawbacks

 Can mask important problems


 If a client pops more than it pushes, this
is probably a serious bug that should be
detected and fixed, not concealed

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Fatal Errors

 The old-fashioned approach: just crash!


 Preconditions, plus decisive action
 At least this does not conceal the
problem…

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


/**
* Pop the top int from this stack and return it.
* This should be called only if the stack is
* not empty. If called when the stack is empty,
* we print an error message and exit the program.
* @return the popped int
*/
public int pop() {
Node n = top;
if (n==null) {
System.out.println("Popping an empty stack!");
System.exit(-1);
}
top = n.getLink();
return n.getData();
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Drawbacks
 Not an object-oriented style: an object
should do things to itself, not to the rest
of the program
 Inflexible: different clients may want to
handle the error differently
 Terminate
 Clean up and terminate
 Repair the error and continue
 Ignore the error
 Etc.
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Error Flagging

 The method that detects the error can


flag it somehow
 By returning a special value (like C malloc)
 By setting a global variable (like C errno)
 By setting an instance variable to be checked
by a method call (like C ferror(f))
 Caller must explicitly test for error

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


/**
* Pop the top int from this stack and return it.
* This should be called only if the stack is
* not empty. If called when the stack is empty,
* we set the error flag and return an undefined
* value.
* @return the popped int if stack not empty
*/
public int pop() {
Node n = top;
if (n==null) {
error = true;
return 0;
}
top = n.getLink();
return n.getData();
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
/**
* Return the error flag for this stack. The error
* flag is set true if an empty stack is ever popped.
* It can be reset to false by calling resetError().
* @return the error flag
*/
public boolean getError() {
return error;
}

/**
* Reset the error flag. We set it to false.
*/
public void resetError() {
error = false;
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


/**
* Pop the two top integers from the stack, divide
* them, and push their integer quotient. There
* should be at least two integers on the stack
* when we are called. If not, we leave the stack
* empty and set the error flag.
*/
public void divide() {
int i = pop();
int j = pop();
if (getError()) return;
push(i/j);
}
The kind of explicit error check required
by an error flagging technique.
Note that divide’s caller may also
have to check it, and its caller, and so
on… Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using Exceptions

 The method that first finds the error


throws an exception
 May be checked or unchecked
 Part of the documented behavior of the
method

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


/**
* Pop the top int from this stack and return it.
* @return the popped int
* @exception EmptyStack if stack is empty
*/
public int pop() throws EmptyStack {
Node n = top;
if (n==null) throw new EmptyStack();
top = n.getLink();
return n.getData();
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


/**
* Pop the two top integers from the stack, divide
* them, and push their integer quotient.
* @exception EmptyStack if stack runs out
*/
public void divide() throws EmptyStack {
int i = pop();
int j = pop();
push(i/j);
}

Caller makes no error check—just passes


the exception along if one occurs

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Advantages

 Good error message even if uncaught


 Documented part of the interface
 Error caught right away, not masked
 Caller need not explicitly check for error
 Error can be ignored or handled flexibly

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Outline

 Throwable classes
 Catching exceptions
 Throwing exceptions
 Checked exceptions
 Error handling
 Finally
 Farewell to Java

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


The Full try Syntax
<try-statement> ::= <try-part> <catch-parts>
| <try-part> <catch-parts> <finally-part>
| <try-part> <finally-part>
<try-part> ::= try <compound-statement>
<catch-parts> ::= <catch-part> <catch-parts> | <catch-part>
<catch-part> ::= catch (<type> <variable-name>)
<compound-statement>
<finally-part> ::= finally <compound-statement>

 There is an optional finally part


 No matter what happens, the finally
part is always executed at the end of the
try statement

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Using finally
file.open();
try {
workWith(file);
}
finally {
file.close();
}
 The finally part is usually used for
cleanup operations
 Whether or not there is an exception,
the file is closed

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Example
System.out.print("1");
try {
System.out.print("2");
if (true) throw new Exception();
System.out.print("3");
}
catch (Exception e) { What does this print?
System.out.print("4");
} What if we change
finally { new Exception() to
System.out.print("5"); new Throwable()?
}
System.out.println("6");

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java on the Web: Java Applets
 Clients download applets via Web browser
 Browser runs applet in a Java Virtual
Machine (JVM)


Client Interactive
Applet
web, security, and Server
client
consistency
Slow to download, inconsistent VMs
(besides, flash won this war)

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Simple Java Applet

//HelloWorld.java
import java.applet.Applet;
import java.awt.*;

public class HelloWorld extends Applet {


public void paint(Graphics g) {
g.drawString (“Hello World !”,25, 25);

}
}

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Calling an Applet

<HTML>
<TITLE>HELLO WORLD APPLET</TITLE>
<HEAD>THE HELLO WORLD APPLET</HEAD>
<APPLET CODE=“HelloWorld.class” width=500
height=500>
</APPLET>
</HTML>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Applet Execution

Using AppletViewer
Using Browser

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


Java Applets
 Java applets are programs that run on a java enabled browser. 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

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


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.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


What can an applet not do?
 An applet cannot load libraries or define native
methods.
 It cannot read or write files on the host that's executing
it.
 It cannot make network connections except to the host
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 than
windows that an application brings up.

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)


HTML Applet Tag
<HTML>
< APPLET
CODE = appletFile
WIDTH = pixels
HEIGHT = pixels
>
</APPLET>
</HTML>

Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)

You might also like