Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

Debre Tabor University

Faculty of Technology

Department of Computer Science

Course Module

For

Object Oriented Programming

Revised by: Computer Science Department


OOP | [Pick the date]

September 2012
DTU

1
Chapter One

Introduction to Object Oriented Programming


Upon the completion of this course, the students will be able to: -
o Define OOPL
o Define Java
o Explain history of java
o Compute sample java programs
Contents
Programming language paradigm Overview of OOP principles History of java
Programming Language paradigm

Question: - What is object-oriented programming language?

Types of Programming Language

Programming languages are the heart of computer science. They are the tools used to
communicate not only with computers but also with people. The challenge of
designing language features that support clear expressions, the puzzle of fitting
together, the different features to make a useful language, the challenge of
appropriately using those features for the clear expression of algorithms all these
make up part of the excitement of the study of programming languages. PL is
designed to communicate ideas about Algorithms between people and computers.
There are 4 computational models that describe most programming languages
paradigm.
Programming languages paradigm.
Imperative (Procedural languages)
Functional
Declarative
Object Oriented

Procedural Languages
Imperative Programming languages are simply Command driven or Statement
oriented languages. A program consists of a series of steps, i.e. a sequence of
statements each of which performs a calculation, retrieves input or produces output.
The execution of each statement causes the computer to change the value of one or

2
more location in its memory that is to enter a new state.
E.g. Major Procedural Languages are COBOL, FORTRAN, and Pascal
Declarative Languages

Rule based language execute by checking for the presence of a certain enabling condition
And when present executing an appropriate action. The most common rule-based
language is Prolog, also called a logic programming language because the basic enabling
conditions are certain classes of predicate logic expressions.
Object Oriented Programming
The program is a collection of objects that interact with each other by passing messages
that transform their state. Complex objects are designed as extensions of simpler objects,
inheriting properties of the simpler objects. By building concrete data objects, an object-
oriented program gains the efficiency of Imperative languages. By building classes of
functions that use a restricted set of data Objects, we built the flexibility and reliability of
the applicative model. Object modeling, classification and inheritance are fundamental
building blocks for Object oriented programming.

History of Java

Brainstorming: What is Java?

History of Java

We can use pointers to access individual characters in a string. A variable is declared


as a pointer to character & assign string constant to that variable.

First there was C. C initially became widely known as the development language of
UNIX OS. Through time 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 style and object-oriented style can be developed using it.

Java was first developed in 1991 by James Gosling at Sun Microsystems to be used
with interactive TV technology which had failed to find a market. It took 18 months
to develop the first working version. This language was initially called “Oak” but it
was renamed as “Java” in 1995. And Java is now considered as the native language
of the Internet. Java is a C/C++ based language. Better than C++ Java is a full
object-oriented language.
Assessment
1. What is OOP?

3
2. Explain the types of programming language paradigm?
3. Which one of the following is hybrid language?
A. C B. C++ C. Java D. C#
4. Write three d/t sample programs by using java statements.
5. Which type of language use dominantly in todays as world as well as in Ethiopian system
development companies? Then choice you prefer language?

Chapter 2
Basics in Java Programming
This chapter outlines the core syntax and constructs of the Java language.

Structure of java Program


Java is a pure object-oriented language, and hence everything is written within a class
block. The structure of a java program is:
[Documentation] --------- suggested
[package statement] ------ Optional
[import statements] ------ Optional
[interface statements] ------ Optional
[class definitions] ------ Optional
[main-method class] ------ Essential

main method class definition


Creating, Compiling and Running a Java Program
To create java program, you will:
• Create a source file and write in the Java program.
• Compile the source file into a bytecode file using the compiler, javac.
• Run the program contained in the bytecode file using The Java interpreter
installed on your computer.
Note:
• The file name should be the same as the name of the class containing our main
method. E.g. A main class named MyFirstClass has to be in the file called
MyFirstClass.java
• A program can contain one or more class definitions but only one public class
definition. This class is called main class because it contains the main method.
• The program can be created in any text editor.
• If a file contains multiple classes, the file name must be the class name of the
class that contains the main method.

Example:

public class MyFirstJavaProgram {

4
public static void main(String []args) {
System.out.println("Hello World");
}
}

C : > javac MyFirstJavaProgram.java


C : > java MyFirstJavaProgram

Hello World
Note: we are using the System and String class directly, because they are found in the
package java.lang in which it is automatically included in any java program.
public (access modifier) makes the item visible from outside the class. static
indicates that the main() method is a class method not an instant method. It allows
main() to be called without having to instantiate a particular instance of the class.

Lexical Components of Java Tokens


Java program = Comments + java statements + white space
Java statements are also combinations of java Token(s).
Java tokens are meaningful words and symbols of java programming language.

Java Tokens
Tokens are meaningful words and symbols used by a programming language. They are
the smaller individual units inside a program the compiler recognizes when building up
the program. There are five types of Tokens in Java: Reserved keywords, Identifiers,
Literals, operators, separators.
1. Reserved words

abstract Float public


boolean For return
Break If short
Byte Implements static
Case Import super
catch Instanceof switch
Char Int synchronized
class Interface this
continue Long throw
default Native throws
Do New transient
double Null try
Else Operator void

5
extends Package volatile
final Private while
finally protected

These reserved words are words with special meaning to the compiler. They could not
be used as constant or variable or any other variable/identifier names.
2. Identifiers
Identifiers are programmer defined tokens. They include names used to identify
classes, methods, variables, objects, packages, and interfaces. Java programming
language is case sensitive language. Example: Mathvar, mathVar, MathVar, etc…
are different identifiers/variables.
▪ Rules in naming Identifier:
The name must begin with
▪ Letters or
▪ Underscore characters ( _ ) or
▪ Any currency symbol (e.g $)
Remaining characters of the name of identifiers could be:
▪ Letters
▪ Digits
Example: legal identifiers name: age, $salary, _value, __1_value
illegal identifiers: 123abc, -salary

▪ Identifiers’ naming conventions


Class names: starts with capital letter and should be inter-capital
Variable names: start with lower case and should be inter-capital
Method names: start with lower case and should be inter-capital
Constants: often written in all capital and use underscore if you are using
more than one word.
3. Literals
Literals are values to be stored in variables. They are a sequence of characters
(digits, letters, & other characters).

4. Operators
Operators are a symbol that take one or more arguments (operands) and operates
on them to produce a result. Eg. +, *, -, /, %...
In general, there are 8-kinds of operators:
Categories of operators are as follows:
• Arithmetic operators • Increment and decrement operators
• Logical operators • Bit wise operators
• Relational operators • Special operators
• Assignment operators
• Conditional operators

6
5. Separators
Separators are symbols used to indicate where groups of codes are divided and
arranged. They define the shape and function of our code. Some of them are:
Name Symbol
Parenthesis ()
braces {}
brackets []
semicolon ;
comma , ,
period .

Java Comments
Java allows putting our comments for making clarifications to our java codes. The
compiler skips comments during compiling. These comments can be written using three
ways.
Start End Purpose
/* */ The enclosed text is treated as a comment.
// (none) The rest of the line is treated as a comment.
/** */ The enclosed text is treated as a comment by the
compiler but is used by JavaDoc to automatically
generate documentation.

Example:
/* This is a comment that will span multiple source code lines. */
// This is a comment that will span multiple source code lines.
/** This is a comment that will span multiple source code lines. */
White space
Java white spaces include: space, tab, newline. Java Statements are roughly equivalent to
sentences in natural languages. A statement is terminated using a semi colon. It forms a
complete unit of execution. Java statements are categorized as follows:

7
Java
statements

Expression Labeled Control Synchronization Guarding


statement statement statement statement statement

Selection Iteration/loop Jump


statement statement statement

If( ) While( ) break

If( )… else do…while () continue

Switch( ) for( )

Expressions
Expression is segment of a code that performs computations and return values. They are
a series of variables, operators, and method/function calls which finally evaluate to a
single value. Expressions are used to compute and to assign values to variables and to
help control the execution flow of a program. By grouping statements together with curly
braces { }, we create blocks of code.
Labeled statements
Labeled statements are any statements beginning with the key word “label”. The “label”
key word is in combination with “goto”.

Synchronization statement

Are statements used for handling issues related with multi-threading (multi
asking). Guarding statements

Guarding statements are statements used for handling errors (exceptions). The three key
words used in handling exceptions are: try, catch, and finally.

Blocks
A block is a group of zero or more statements between a pair of braces and can be used
anywhere even for a single statement. Example:

8
if ( Character.isUpperCase(aChar) ) {
System.out.println("The character " + aChar + " is upper case.");
}
else {
System.out.println("The character " + aChar + " is lower case.");
}

Constants, Variables and Data Types

Constants
Constants are fixed values (literals to be stored in variables) that do not change during the
execution of a program.
Java
constants

Numeric Non-numeric
constants constants

Integer Real Character String


constants constants constants constants
Examples of constants:
23411--- integer constant ‘A’ ---- character constants
O425 --- octal constants(begin ‘7’---- character constants
with ‘\’ ---- character constants
the letter ‘O’) “WELCOME” ---- string
0x7 ---- hexadecimal constants constatns
0A2B---- hexadecimal constants “THE-END” ---- string constatns
0.0234 ---- real constants “BYE …BYE” ---- string
0.777 ---- real constants constatns
-1.23 ---- real constants “A” ---- string constatns

Variables
Variables are identifiers that denote a storage location to store a data values. i.e. they are
names of storage locations.

Data types
All kinds of data that can be stored in computer do not take the same space and the same
operations cannot be made on them. Example let’s take the name “Alexander” and the
number “20”. The two items (data) do not take the same memory space and also
operations. Multiplication operation can be made on the number item but not on the
string item.

9
So, to handle these issues, a mechanism is devised known as “data typing” system.

Data type means “item type to be stored in memory”. They are used to identify
• amount of memory size that should be assigned to a given data/item and
• kinds of operations that could be made on the item.

Based on java programming language, data types are categorized as primitive/built-in and
derived/user defined.

Integer types
Integer datatype can hold the numbers (the number can be positive number or negative
number). In Java, there are four types of integers: byte, short, int, and long.

Floating types
It is also called as Real number and when we require accuracy then we can use it. It is
used to represent decimal numbers. There are two types of decimal numbers: float and
double.

Character data type


It is used to store single character in memory.

Boolean data type


It is used when we want to test a particular condition during the execution of the
program. There are only two values that a boolean type can hold: true and false.
Boolean type is denoted by the keyword boolean and uses only one bit of storage.

The following table shows the data-types with their memory size they take and ranges of
values they can hold.

10
Variable declaration
Variable declaration does three things:
• Tells the compiler what the variable name is.
• It specifies what type of data(value) the variable will hold.
• The place of declaration in the program decides the scope of the variable.

Syntax to declare a variable is: data-type variable_name;


Syntax to initialize a variable is: variable_name= value;
Initialization and declaration can be done at a time as: data-type variable_name= value;
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // declares and initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'

Giving values to variables is done in two ways:


• By using assignment statement: variable_name= value;
• By using readLine() function.

To initialize characters, the characters are placed under single quotes while strings are
under double quotes.

Following program shows the use of datatypes:


import java.io.DataInputStream;
class cc2
{
public static void main(String args[]) throws Exception

11
{
DataInputStream s1=new DataInputStream(System.in);
byte rollno;
int marks1,marks2,marks3;
float avg;
System.out.println("Enter roll number:");
rollno=Byte.parseByte(s1.readLine());
System.out.println("Enter marks m1, m2,m3:");
marks1=Integer.parseInt(s1.readLine());
marks2=Integer.parseInt(s1.readLine());
marks3=Integer.parseInt(s1.readLine());
avg = (marks1+marks2+marks3)/3;
System.out.println("Roll number is="+rollno);
System.out.println("Average is="+avg);
}
}

Output:
Enter roll number:
07 Roll number is=7
Enter marks m1, m2,m3: Average is=77.0
66 21 77 88

Symbolic constants
Symbolic constants are names given to numbers instead of using the numbers in
programs directly.
Example: instead of using 3.14, we may name it as PI & use the word PI instead of 3.24
in our programs.
Symbolic constants
• Should be in capital letters
• Re-assigning after declaration is illegal
• Cannot be declared inside methods
• Are declared as:
final var_type symbolic_name= value;
Eg: final float PI=3.14;

Backslash character constant:


Java supports some special character constants in which if we want to display them from
our program. These constants are given in following table.

12
Scope and life time of variables
Java variables are three types:
• Instance variables
• Class variables
• Local variables
Instance variables:
Instance variables are created when objects are instantiated. They are associated
with objects. They take different values for different object.
Class variables:
Class variables are global to a class and belong to the entire set of objects that the
class creates. Only one memory location is created for each class variable. They
are declared as “static” data members.
Local variables:
Are declared and used inside methods/functions. And their scope and life time is
inside the body of the function

A variable's scope is the region of a program within which the variable can be referred to
by its simple name. A scope also determines when the system creates and destroys
memory for the variable. A block defines a scope. Each time you create a block of code,
you are creating a new, nested scope.
Variables are created when their scope is entered, and destroyed when their scope is left.
Thus, the lifetime of a variable is confined to its scope.
Objects declared in the outer block will be visible to code within the inner block down
from the declaration. (The reverse is not true).

Type casting
Type casting/converting is changing data type of a variable from one type to another with
no any loss of information. There are two types of castings: automatic and explicit.
1. Explicit casting
• The syntax is: type var_name1= (type) var_name2;
Eg. byte n= (byte) m;
float f =3.5f; float y=x+b;
f = (float)2.9; b = (byte)y;
float x=98; int x = (int)2.7;
byte b=2;

13
• Casts that result in no-loss of information include:

double
float
Long
Char int
short
Byte

2. Automatic casting
When computer consider operand and operator and if operands are different types
then type is automatically convert in higher type.
There are two conditions for automatic casting to happen
o When assigning value of one type to a variable of another type or
o Destination is wider than the source
Eg. byte b=75;
int a=b; //automatic conversion happens from byte to int

Operators
▪ An operator performs a function on one, two, or three operands. An operator that
requires one operand is called a unary operator. The unary operators support either
prefix or postfix notation. Prefix notation means that the operator appears before its
operand. Postfix notation means that the operator appears after its operand
operator operand; //prefix notation
operand operator; //postfix notation
▪ An operator that requires two operands is a binary operator. All of the binary
operators use infix notation, which means that the operator appears between its
operands: op1 operator op2; //infix notation
▪ A ternary operator is one that requires three operands. The Java programming
language has one ternary operator ?: which is a short-hand for if-else statement. The
ternary operator is also infix; each component of the operator appears between
operands: op1 ? op2 : op3; //infix notation
▪ In addition to performing the operation, an operator returns a value. The return value
and its type depend on the operator and the type of its operands. If you add two
integers, you get an integer back. An operation is said to evaluate to its result.
▪ There are many kinds of operators:
1. Arithmetic operators

Operator Use Description


+ +op Promotes op to int if it's a byte, short, or char

14
- -op Arithmetically negates op

Operator Use Description


+ op1 + op2 Adds op1 and op2
- op1 - op2 Subtracts op2 from op1
* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% op1 % op2 Computes the remainder of dividing op1 by op2

2. Logical operators
Operator Use Returns true if
&& op1 && op1 and op2 are both true, conditionally evaluates op2
op2
|| op1 || either op1 or op2 is true, conditionally evaluates op2
op2
! ! op op is false

3. Relational operators
Operator Use Returns true if
> op1 > op2 op1 is greater than op2
>= op1 >= op2 op1 is greater than or equal to op2
< op1 < op2 op1 is less than op2
<= op1 <= op2 op1 is less than or equal to op2
== op1 == op2 op1 and op2 are equal
!= op1 != op2 op1 and op2 are not equal

4. Assignment operators

Operator Use Equivalent to


+= op1 += op2 op1 = op1 + op2
-= op1 -= op2 op1 = op1 - op2
*= op1 *= op2 op1 = op1 * op2
/= op1 /= op2 op1 = op1 / op2

15
%= op1 %= op2 op1 = op1 % op2
&= op1 &= op2 op1 = op1 & op2
|= op1 |= op2 op1 = op1 | op2
^= op1 ^= op2 op1 = op1 ^ op2
<<= op1 <<= op2 op1 = op1 << op2
>>= op1 >>= op2 op1 = op1 >> op2
>>>= op1 >>>= op2 op1 = op1 >>> op2

5. Conditional operator
The character pair?: is a conditional which is ternary operator of Java, which is used to
construct conditional expressions of the following form:
Expression1 ?Expression3 : Expression3
variable x = (expression) ? value if true : value if false
The operator?s : works as follows:
Expression1 is evaluated if it is true then Expression3 is evaluated and becomes the value
of the conditional expression. If Expression1 is false then Expression3 is evaluated and
its value becomes value of the conditional expression.

public class Test {

public static void main(String args[]){


int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

This would produce the following result:

Value of b is : 30
Value of b is : 20

6. Increment and decrement operators


Operator Use Description
++ op++ Increments op by 1; evaluates to the value of op before it
was incremented
++ ++op Increments op by 1; evaluates to the value of op after it

16
was incremented
-- op-- Decrements op by 1; evaluates to the value of op before it
was decremented
-- --op Decrements op by 1; evaluates to the value of op after it
was decremented

7. Bit-wise operators
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a =
60; and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
---------------------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

Operator Use Operation


& op1 & op2 bitwise and
| op1 | op2 bitwise or
^ op1 ^ op2 bitwise xor
~ ~op2 bitwise complement

Operator Use Operation

>> op1 >> op2 shift bits of op1 right by distance op2
<< op1 << op2 shift bits of op1 left by distance op2

Exercise
Write a java code that contains the different operators, variables, constant, datatypes,
type casting and other expressions in one program.
(Implement the program accept the data in both from keyword and assigning value)

17
Java selection statements
if, if…else, and switch…case
There are two types of decision-making statements in Java. They are:
• if statements
• switch statements
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement
will be executed. If not the first set of code after the end of the if statement (after the
closing curly brace) will be executed.
Example:
public class Test {

public static void main(String args[]){


int x = 10;

if( x < 20 ){
System.out.print("This is if statement");
}
}
}
This would produce the following result:
This is if statement
The if...else Statement:
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax:
The syntax of an if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
Example:
public class Test {
public static void main(String args[]){

18
int x = 30;

if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
This would produce the following result:
This is else statement
The if...else if...else Statement:
An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
The syntax of an if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}
Example:
public class Test {

public static void main(String args[]){


int x = 30;

if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}

19
}
}
This would produce the following result:
Value of X is 30
Nested if...else Statement:
It is always legal to nest if-else statements which means you can use one if or else if
statement inside another if or else if statement.
Syntax:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}

You can nest else if...else in the similar way as we have nested if statement.
Example:
public class Test {

public static void main(String args[]){


int x = 30;
int y = 10;

if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
This would produce the following result:
X = 30 and Y = 10
The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.
Syntax:
The syntax of enhanced for loop is:
switch(expression){
case value :
//Statements
break; //optional

20
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The following rules apply to a switch statement:
• The variable used in a switch statement can only be a byte, short, int, or char.
• You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
• The value for a case must be the same data type as the variable in the switch and it
must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.
Example:
public class Test {
public static void main(String args[]){
//char grade = args[0].charAt(0);
char grade = 'C';

switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}

21
System.out.println("Your grade is " + grade);
}
}

Compile and run above program using various command line arguments. This would
produce the following result:
$ java Test
Well done
Your grade is a C
$
Java Loops/Iteration and
Jump statements
for, while and do...while & break, continue, return
There may be a situation when we need to execute a block of code several number of
times, and is often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three
loops:
- while Loop
- do...while Loop
- for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of
times.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop
will be executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression
is tested and the result is false, the loop body will be skipped and the first statement after
the while loop will be executed.
Example:
public class Test {

public static void main(String args[]) {


int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;

22
System.out.print("\n");
}
}
}

This would produce the following result:


value of x : 10 value of x : 15
value of x : 11 value of x : 16
value of x : 12 value of x : 17
value of x : 13 value of x : 18
value of x : 14 value of x : 19

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax:
The syntax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the
loop execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the
statements in the loop execute again. This process repeats until the Boolean expression is
false.
Example:
public class Test {

public static void main(String args[]){


int x = 10;

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
This would produce the following result:
value of x : 10 value of x : 13
value of x : 11 value of x : 14
value of x : 12 value of x : 15

23
value of x : 16 value of x : 19
value of x : 17
value of x : 18
The for Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}
Here is the flow of control in a for loop:
• The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here,
as long as a semicolon appears.
• Next, the Boolean expression is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control
jumps to the next statement past the for loop.
• After the body of the for loop executes, the flow of control jumps back up to the
update statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the Boolean
expression.
• The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After
the Boolean expression is false, the for loop terminates.
Example:
public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x+1) {


System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10 value of x : 14
value of x : 11 value of x : 15
value of x : 12 value of x : 16
value of x : 13 value of x : 17
value of x : 18

24
value of x : 19
Enhanced for loop in Java:
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be
an array variable or method call that returns an array.
Example:
public class Test {

public static void main(String args[]){


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
This would produce the following result:
10,20,30,40,50,
James,Larry,Tom,Lacy,
The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used
inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the
next line of code after the block.
Syntax:
The syntax of a break is a single statement inside any loop:
break;

25
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce the following result:
10
20
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop
to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce the following result:
10

26
20
40
50

Exercise

1. Write programs that applies control structures, arrays, and string


processing.
2. Write a java program to implement for at least 100 number of student
their grade i.e. when the mark is >=90 “A”, >=70 “B” >=50 “C” >=45 “D”
otherwise give “F”. The data accept from keyword.

27
Chapter three

OBJECTS AND CLASSES

The General Form of a class


The basic element of object – oriented programming is a class. A class defines the shape
and behavior of an object and is a template for multiple objects with similar features. Any
concept represented in a program is encapsulated in a class. When an application is
written, classes of objects are defined. To create a class, a source file with the class
keyword in it followed by a legal identifier and a pair of curly braces for the body is
required. The general form of a class definition is shown here:
Class classname {
Type instance-variable1;
Type instance –variable2;
// ….
Type instance-variableN;
type methodname (Parameter-list)
{
// body of the method
}
}
The data or variables defined with in a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class
are called members of the class. In most classes, the instance variables are acted upon
and accessed by the methods defined for that class. Thus, it is methods that determine
how a class data can be used.
Variable defined within a class are called instance variables because each instance of the
class (that is, each object of the class) contains its own copy of these variables. Thus, the
data for one object is separate and unique from the data for another.
A class called Book includes all its features serving as template for the concept. Each
property is treated as an attribute of that class. For example, the book’s name, the
author’s name, number of pages it contains are its attributes.
The definition of the Book class would be
class Book {
String name;
String authorname;
int nopages;
}
Apart from defining an object’s structure, a class also defines its functional interface,
known as methods. The Book can have a method that displays the name of the book.
class Book {
String name;
String authorname;
int nopages;
String displayName() {
System.out.println (“ Name of the book is “ + name );

28
}
}
Declaring Objects
As just explained, when you create a class, you are creating a new data type. You can use
this type to declare objects of that type. However, obtaining objects of a class is a two-
step process. First, you must declare a variable of the class type. This variable does not
define an object. Instead, it is simply a variable that can refer to an object. Second, you
must acquire an actual, physical copy of the object and assign it to that variable. You can
do this using a new operator. The new operator dynamically allocates (that is, allocates at
run time) memory for an object and returns a reference to it. This reference is, more or
less, the address in memory of the object allocated by new. This reference is then stored
in the variable. Thus, in Java, all class objects must be dynamically allocated.
In the preceding sample program, a line similar to the following is used to declare an
object of type Box:
Box mybox = new Box ();
This statement combines the two steps just declared. It can be rewritten like this to show
each step more clearly
Box mybox; // declare reference to object Mybox = new Box () // allocate a Box object
The first line declares mybox as a reference to an object of type Box. After this line
executes, mybox contais the value null, which indicates that it does not yet point to an
actual object
Example of declaring objects Declaring Objects
ClassName objectName = new className ();
Example:
Circle myCircle = new Circle ();
-Referencing the object’s data: objectName.data
e.g., myCircle.radius
-Invoking the object’s method: objectName.methodName(arguments) e.g.,
myCircle.getArea()
Adding Methods into Class
class rectangle {
double width;
double length;
void area ()
{
System.out.println(width * length);
}
System.out.print("Area is ");// display area of a rectangle
}
}

Constructors and Destructors

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 () {

29
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. All objects are
created through constructors they are invoked automatically Garbage Collection.
Methods: Methods are functions that operate on instances of classes in which they are
defined. Objects can communicate with each other using methods and can call methods in
other classes. Just as there are class and instance variables, there are class and instance
methods. Instance methods apply and operate on an instance of the class while class
methods operate on the class.

Defining Methods
Method definition has four parts. They are, name of the method, type of object or
primitive type the method returns, a list of parameters and body of the method. Java
permits different methods to have the same name as long as the argument list is different.
This is called method overloading. A basic method definition resembles the one given
below:

Returntype methodname (type1 arg1, type2 arg2) {


// Body of the methods
}

The return type is the primitive type or class of the value this method returns. It should be
void if the method does not return a value at all.
The method’s parameter list is a set of variable declarations. The list is separated by
commas within the parentheses. The parameters become local variables in the body of the
method whose values are passed when the method is called.
Inside the body of the method, statements, expressions and method call can be present. If
the method has a return type, then a value must be returned using the key word return.
Calling methods
Calling method is similar to calling or referring to an instance variable. The methods are
accessed using the dot notation. The object whose method is called is on the left of the
dot, while the name of the method and its arguments are on the right.
Obj.methodname (param1, param2)
The following example indicates the usage of methods
class Area {

30
int len = 10;
int bre = 10;
void calcu ( ) {
int area = len * bre ;
System .out. println (“The area is “ + area + “ sq. cms “);
}
public static void main (String args[ ] ) {
Area a= new Area ();
a.calcu ( ) ;
}
}
Class Methods
Class methods, like class variables, are available to instance of the class and can be made
available to other classes. Class methods can be used anywhere regardless of whether an
instance of the class exists or not. Methods that operate on a particular object should be
defined as instance methods. Methods that provide some general utility but do not
directly affect an instance of the class are declared as class methods. Class method is
defined as given below:
static returntype methodname (type1 arg1, type2 arg2, .. )
{
// Body of the method
}

The static keyword indicates that it is a class method and can be accessed without
creating an object. The class methods, unlike instance method, are not allowed to use
instance variables, as these methods do not operate on an object.
Passing Argument to methods
The objects that are passed to the body of the method are passed by reference and the
basic types are passed by value. This results in the change in original value of the object
if the value is modified in the method
The following example depicts the passing of arguments to methods.
class Marg {
void calcu (int x) {
int square = x * x:
System.out.println (“ The square of “ + x + “ is “ + square ) ;
}
public static void main (String args[] ) {
Marg a=new Marg ();
a.calcu ( 15 ) ;
}
}
The output appears as shown:
The square of 15 is 225.

In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case,

31
the methods are said to be overloaded, and the process is referred to as method
overloading.
Method Overloading is one of the ways that Java implements polymorphism. If you
have never used a language that allows the overloading of methods, then the concept
may seem strange at first. But as you will see, method overloading is one of Java’s most
exciting and useful features.
When an overloaded method is invoked, Java uses the type and/or number of arguments
as its guide to determine which version of the overloaded method to actually call. While
overloaded methods may have different return types, the return type alone is insufficient
to distinguish two versions of a method. When Java encounters a call to an overloaded
method, it simply executes the version of the method whose parameters match the
arguments used in the call.
Here is a simple example that illustrates method overloading:

// Demonstrate method Overloading


class OverloadDemo {
void test ()
{
System.out.priintln (“No Parameters “);
}
// Overload test for one integer parameter.
void test (int a )
{
System.out.println (“ a : “ + a);
}
// Overload test for two integer parameters.
void test (int a, int b)
{
System.out.println (“a and b: “+a + ““+ b);
}
// Overload test for a double parameter
double test (double a)
{
System.out.println ( “ double a : “ +a);
return a*a;
}
}
class Overload {
public static void main ( String args[ ] ) {
OverloadDemo ob= new OverloadDemo( ) ;
double result ;
// call all versions of test ()
ob.test ( ) ;
ob.test (10) ;
ob.test ( 10,20 );
result = ob.test ( 123.2);

32
System.out.println ( “ Result of ob.test (123.2) : “ + result );
}
}
This program generates the following output:
No parameters
a : 10
a and b : 10 20
double a : 123.2
Result of ob.test(123.2) : 15178.24

Recursion Java supports recursion. Recursion is the process of defining something in


terms of itself. As it relates to Java programming, recursion is the attribute that allows a
method to call itself. A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number.
The factorial of a number N is the product of all the whole numbers between 1 and N.
// simple example of recursion.
class Factorial {
// this is a recursive function
int fact (int n) {

int result;
if(n==1) return 1;

result = fact(n-1) * n;
return result;

}
}
class Recursion {

public static void main (String args[])


{
Factorial f = new Factorial ();

System.out.println("Factorial of 3 is " + f. fact (3));


System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}

Recursive versions of many routines may execute a bit more slowly than the iterative
equivalent because of the added overhead of the additional function calls.
The main advantage to recursive methods is that they can be used to create clearer and
simpler versions of several algorithms than can their iterative relatives.

33
Access Control

Access control is controlling visibility of a variable or method. When a method or


variable is visible to another class, its methods can reference the method or variable.
There are four levels of visibility that are used. Each level is more restrictive than the
other and provides more protection than the one preceding it.
Public Any method or variable is visible to the class in which it is defined. If the method
or variable must be visible to all classes, then it must be declared as public. A variable or
method with public access has the widest possible visibility. Any class can use it.
Package (default) Package is indicated by the lack of any access modifier in a
declaration. It has an increased protection and narrowed visibility and is the default
protection when none has been specified.
Protected This specifier is a relationship between a class and its present and future sub
classes. The subclasses are closer to the parent class than any other class. This level gives
more protection and narrows visibility.
Private It is narrowly visible and the highest level of protection that can possibly be
obtained. Private methods and variables cannot be seen by any class other than the one in
which they are defined. They are extremely restrictive but are most commonly used. Any
representation unique to the implementation is declared private. An object’s primary job
is to encapsulate its data and limit manipulation. This is achieved by declaring data as
private.

Inheritance can be defined as the process where one object acquires the properties of
Another. With the use of inheritance, the information is made manageable in a
hierarchical order.
To inherit a class, you simply incorporate the definition of one class into another by using
extends keyword. To see how, let’s begin with a short example. The following program
creates a superclass called A and a subclass called B. Notice how the keyword extends is
used to create a subclass of A.

// A simple example of inheritance


// Create a superclass.
Public class A {
int i,j ;
void showij () {
System.out.println (“i and j : “ +i + “ “ + j );
}
}
// Create a subclass by extending class A
Public class B extends A {
int k;
void showk( ) {
System.out.println ( “ k : “ + k );
}
void sum ( ) {
System .out.println ( “ i + j + k : “ + ( i+j+ k ));
}

34
}
Public class SimpleInheritance {
public static void main (String args[ ] ) {
A superOb = new A( );
B subOb = new B ( );
// The superclass may be used by itself
superob.i = 10;
superob.j = 20;
System.out.println ( “ Contents of superOb : “);
Superob. Showij ( );
System.out.pritnln ( );
/* The subclass has access to all public members of its superclass, */
subob .i = 7;
subob. j = 8;
subob.k = 9;
System.out.println ( “Contents of subob : “ );
Subob.showij( );
Subob. showk ();
System.out.println ();
System.out.println ( “ Sum of i,j and k in subob : “ );
subob.sum( );
}
}
The output from this program is shown here:
Contents of superob:
i and j : 10 20
Contents of subob:
i and j: 7 8
k: 9
Sum of i, j and k in subob:
i+j+k : 24.
As you can see, the subclass B includes all of the members of its superclass, A. This is
why subob can access I and j and call showij(). Also, inside sum (), I and j can be referred
to directly, as if they were part of B. Even though A is a superclass for B, it is also a
completely independent.
Polymorphism
Polymorphism is the ability of an object to take on many forms. In programming
languages polymorphism is the capability of an action or method to do different things
based on the object that it is acting upon. This is the third basic principle of object-
oriented programming. The three types of polymorphism are: ad-hoc (overloading and
overriding), parametric (generics) and dynamic method binding.
Overloaded methods are methods with the same name signature but either a different
number of parameters or different types in the parameter list. For example, 'spinning' a
number may mean increase it, 'spinning' an image may mean rotate it by 90 degrees. By
defining a method for handling each type of parameter you control the desired effect.

35
Overridden methods are methods that are redefined within an inherited or subclass. They
have the same signature and the subclass definition is used. Parametric are generic typing
procedures.
Dynamic (or late) method binding is the ability of a program to resolve references to
subclass methods at runtime. For example assume that three subclasses (Cow, Dog and
Snake) have been created based on the Animal abstract class, each having their own
speak() method. Although each method reference is to an Animal (but no animal objects
exist), the program is will resolve the correct method reference at runtime.

public class AnimalReference


{
public static void main (String args[])
Animal ref // set up var for an Animal
Cow aCow = new Cow("Bossy"); // makes specific objects
Dog aDog = new Dog("Rover");
Snake aSnake = new Snake("Ernie");
// now reference each as an Animal
ref = aCow; ref.speak();
ref = aDog; ref.speak();
ref = aSnake; ref.speak();
}
Abstraction:
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one
that cannot be instantiated. All other functionality of the class still exists, and its fields,
methods, and constructors are all accessed in the same manner. You just cannot create an
instance of the abstract class. If a class is abstract and cannot be instantiated, the class
does not have much use unless it is subclass. This is typically how abstract classes come
about during the design phase. A parent class contains the common functionality of a
collection of child classes, but the parent class itself is too abstract to be used on its own.
Reading assignment writes a program to implementation of abstraction and method
abstraction.
Encapsulation is the technique of making the fields in a class private and providing
access to the fields via public methods. If a field is declared private, it cannot be
accessed by anyone outside the class, thereby hiding the fields within the class. For this
reason, encapsulation is also ref erred to as data hiding.
-Binds or encapsulates data and code that processes data.
-Provides a set of functions or methods that are accessed from other objects.
Encapsulation can be described as a protective barrier that prevents the code and data
being randomly accessed by other code defined outside the class. Access to the data and
code is tightly controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without
breaking the code of others who use our code. With this feature Encapsulation gives
maintainability, flexibility and extensibility to our code.
Example of encapsulation
publ i c class EncapTest{

36
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
publ i c Stri ng getName(){
return name;
}
publ i c Stri ng getIdNum(){
return i dNum;
}
publ i c voi d setAge( int newAge){
age = newAge;
}
publ i c voi d setName(String newName){
name = newName;
}
publ i c voi d setIdNum( String newId){
i dNum = newId;
}
}

Exercise
1) Create a class called HouseHolds that can hold information about family members in
a particular Kebele. A family member for a “Kebele System” is expressed to have
the following attributes.
1.1. House number (unique)
1.2. Parents/house-hold name (we can have more than one mother in family)
1.3. Children names (can be more than one and can also add a newly born child)
1.4. Age of children
1.5. Sex of children

NB: Create a menu-based program, that can register new house hold members of the
kebele, new family members for a particular house, display number of male or female for
the kebele, display family members from old to young or young to old. Note that the
number of children in a family can vary from family to family. The system should also
report the number of households in the kebele.

37
Chapter four
Exception Handling

• An exception is an indication of a problem that occurs during a program’s execution.


• An exception is a runtime error
• The name “exception” implies that the problem occurs infrequently—if the “rule” is
that a statement normally executes correctly, and then the “exception to the rule” is
that a problem occurs.
• When an exception occurs, the normal execution flow of the program will be
interrupted
• Exception handling enables you to create applications that can resolve (or handle)
exceptions.
• In many cases, handling an exception allows a program to continue executing as if no
problem had been encountered.
• A more severe problem could prevent a program from continuing normal execution,
instead requiring it to notify the user of the problem before terminating in a controlled
manner.
• Exceptions occur for various reasons. The user may enter an invalid input, for
example, or the program may attempt to open a file that doesn't exist, or the network
connection may hang up, or the program may attempt to access an out-of-bounds
array element.

Here is an example. The program shown below terminates abnormally if you enter a
floating-point value instead of an integer.

import java.util.Scanner;
import java.util.*;
public class ExceptionDemo {
public static void main(String args[])
{
Scanner reader=new Scanner (System. in);
System.out.println("Enter a number :");
int num= reader.nextInt();
System.out.println("The number is :" + num);
}
}

Enter a number:
12.5
If 12.5 is entered for the integer variable, the program will terminate unexpectedly by
generating the exception shown below.
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)

38
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at ExceptionDemo.main(ExceptionDemo.java:18)

• Note that several lines of information are displayed above in response to the
invalid input.
• This information, known as the stack trace, includes the name of the exception
(java.util.InputMismatchException) followed by the method call stack at the time
the exception occurred.
• The stack trace helps in debugging a program.
• Starting from the last line of the stack trace, you see that the exception was
detected in line 18 of the main method.
• Each line of the stack trace contains the class name and method
(ExceptionDemo.main) along with the file name and line number
(ExceptionDemo.java: 7).
• Moving up the stack trace, you see that the exception occurred in line 2050 in the
nextInt method of the Scanner class, the exception occurred in line 2091 in the
overloaded nextInt method of the Scanner class, the exception occurred in line
1461 in the next method of the Scanner class, the exception occurred in line 840
in the throwFor method of the Scanner class.
• The last method in the call chain actually threw an InputMismatchException.

But the following program reports an error message if 12.5 is entered for the integer
variable and the program continues normally executing after displaying the error
message.
import java.util.Scanner;
import java.util.*;
public class ExceptionDemo {
public static void main(String args[])
{
Scanner reader=new Scanner(System.in);
System.out.println("Enter a number :");
try {
int num= reader.nextInt();
System.out.println("The number is :" + num);
}
catch (InputMismatchException e)

{
System.out.println("There is type mis match :");
}
finally
{
System.out.println("This part is always done");
}
}

39
}

Exceptions and Exception Types


• A Java exception is an instance of a class derived from Throwable.
• The Throwable class is contained in the java.lang package, and subclasses of
Throwable are contained in various packages.
• Errors related to GUI components are included in the java.awt package; numeric
exceptions are included in the java.lang package because they are related to the
java.lang.Number class.
• You can create your own exception classes by extending Throwable or a subclass
of Throwable. Figure below shows some of Java's predefined exception classes.

• The exception classes can be classified into three major types: errors, exceptions, and
runtime exceptions.
• Errors are thrown by the JVM and represented in the Error class.
• Errors are not caused due to user program.
• The Error class describes internal system errors. Such errors rarely occur. If one does,
there is little you can do beyond notifying the user and trying to terminate the
program gracefully.
• Errors that result from program activity are represented by sublcasses of Exception.
• Exceptions are represented in the Exception class, which describes errors caused by
your program and by external circumstances.
• These errors can be caught and handled by your program. Examples of subclasses of
Exception.

ClassNotFoundException Attempt to use a class that does not exist. This


exception would occur, for example, if you tried to
run a nonexistent class using the java command, or if
your program was composed of, say, three class files,
only two of which could be found.
IOException Related to input/output operations, such as invalid
input, reading past the end of a file, and opening a
nonexistent file. Examples of subclasses of
IOException are InterruptedIOException,
EOFException (EOF is short for End Of File), and
FileNotFound Exception.
AWTException Exceptions in GUI components

• Runtime exceptions are represented in the RuntimeException class, which


describes programming errors, such as bad casting, accessing an out-of-bounds
array, and numeric errors. Runtime exceptions are generally thrown by the JVM.
Examples of subclasses are shown below.

ArithmeticException Dividing an integer by zero. Note that floating-

40
point arithmetic does not throw exceptions.
NullPointerException Attempt to access an object through a null
reference variable.
IndexOutOfBoundsException Index to an array is out of range.
IllegalArgumentException A method is passed an argument that is illegal or
inappropriate.

• RuntimeException, Error, and their subclasses are known as unchecked


exceptions. All other exceptions are known as checked exceptions, meaning that
the compiler forces the programmer to check and deal with them.
• In most cases, unchecked exceptions reflect programming logic errors that are not
recoverable. For example, a NullPointerException is thrown if you access an
object through a reference variable before an object is assigned to it; an
IndexOutOfBoundsException is thrown if you access an element in an array
outside the bounds of the array. These are logic errors that should be corrected in
the program.
• Unchecked exceptions can occur anywhere in a program. To avoid cumbersome
overuse of try-catch blocks, Java does not mandate that you write code to catch or
declare unchecked exceptions.
• Java exception handling is managed via 5 keywords: try,catch,throw, throws and
finally.
• Program statements that you want to monitor for exceptions are contained within
a try block.
• If an exception occurs within a try block, it is thrown. Your code can catch this
exception using catch and handle it.
• System-generated exceptions are automatically thrown by java run-time system.
• To manually throw an exception, use the keyword throw.

Using try and catch

General form of try/catch:

Try{

//block of code to monitor for errors

Catch(ExceptionType1 exOb ) {

//handler for ExceptionType1

41
Catch(ExceptionType2 exOb ) {

//handler for ExceptionType2

• ExceptionType is the type of exception that has occurred. When an exception is


thrown, it is caught by its corresponding catch statement, which then processes the
exception.
• If no exception is thrown, then a try block ends normally, and all of its catch
statements are bypassed. Executions resumes with the first statement following the
last catch.
• Catch statements are executed only if an exception is thrown.

Example:

public class ExcDemo {

public ExcDemo() {
}

public static void main(String[] args) {

int num[] = new int[4];


try{
System.out.println("Before exception is generated");

num[7]=10;
System.out.println("This will not be displayed");
}
catch(ArrayIndexOutOfBoundsException ex){
//catch the exception
System.out.println("Index-out-of bounds!");

}
System.out.println("After catch statement");
}
}
Output of the above program:
Before exception is generated
Index-out-of bounds!
After catch statement
• The cod e you want to monitor for errors is contained within a try block.
• When an exception occurs, the exception is thrown out of the try block and caught by
the catch statement.
• Control passes to the catch block, and the try block is terminated.

42
• If no exception is thrown by a try block, no catch statements will be executed and
program control resumes after the catch statement.
Example :
public class ExcDemo {
public ExcDemo() {
}
public static void main(String[] args) {
int numer[] = {4,8,16,32,64,128 };
int denom[]={ 2,0,4,4,0,8 };
for(int i=0;i<numer.length;i++){
try{
System.out.println( numer[i] + "/" + denom[i] + " is " + numer[i]/denom[i]);
}
catch(ArithmeticException ex){
//catch the exception
System.out.println("Can not divide by zero");
}
}
}
}
Using Multiple catch Statements 4/2 is 2
Example: Cannot divide by zero
public class ExcDemo { 16/4 is 4
public ExcDemo() { 32/4 is 8
} Cannot divide by zero
128/8 is 16
public static void main(String[] args) { No Matching element
int numer[] = {4,8,16,32,64,128 }; found
int denom[]={ 2,0,4,4,0,8 }; No Matching element
for(int i=0;i<numer.length;i++){ found
try{
System.out.println( numer[i] + "/" + denom[i] + " is " + numer[i]/denom[i]);
}
catch(ArithmeticException ex){
//catch the exception
System.out.println("Can not divide by zero");
}
catch(ArrayIndexOutOfBoundsException ex){
//catch the exception
System.out.println("No Matching element found");
}
}
}
}
___________________

43
Chapter five
JSP – Java Server Page

What is Java Server Pages?


Java Server Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special
JSP tags, most of which start with <% and end with %>.

A Java Server Pages component is a type of Java servlet that is designed to fulfill the
role of a user interface for a Java web application. Web developers write JSPs as text
files that combine HTML or XHTML code, XML elements, and embedded JSP actions
and commands.

Using JSP, you can collect input from users through Webpage forms, present records
from a database or another source, and create Webpages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing
control between pages, and sharing information between requests, pages etc.

Why Use JSP?


Java Server Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in
comparison with the CGI.

• Performance is significantly better because JSP allows embedding Dynamic


Elements in HTML Pages itself instead of having separate CGI files.

• JSP are always compiled before they are processed by the server unlike CGI/Perl
which requires the server to load an interpreter and the target script each time the
page is requested.

• Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP
also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI,
EJB, JAXP, etc.

• JSP pages can be used in combination with servlets that handle the business
logic, the model supported by Java servlet template engines.

44
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the most
complex and demanding.

Advantages of JSP
Following table lists out the other advantages of using JSP over other technologies −

Vs. Active Server Pages (ASP)


The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it
is portable to other operating systems and non-Microsoft Web servers.

Vs. Pure Servlets


It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.

vs. Server-Side Includes (SSI)


SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.

vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with
the web server to perform complex tasks like database access and image processing etc.

vs. Static HTML


Regular HTML, of course, cannot contain dynamic information.

What is Next?
I would take you step by step to set up your environment to start with JSP. I'm assuming
you have good hands-on with Java Programming to proceed with learning JSP.

If you are not aware of Java Programming Language, then we would recommend you go
through our Java Tutorial to understand Java Programming.

JSP - Architecture
The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes use
of Apache which has built-in JSP container to support JSP pages development.

45
A JSP container works with the Web server to provide the runtime environment and
other services a JSP needs. It knows how to understand the special elements that are part
of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web
application.

JSP Processing
The following steps explain how the web server creates the Webpage using JSP −

• As with a normal page, your browser sends an HTTP request to the web server.

• The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.

• The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and
all JSP elements are converted to Java code. This code implements the corresponding
dynamic behavior of the page.

• The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.

• A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format. The output is further
passed on to the web server by the servlet engine inside an HTTP response.

• The web server forwards the HTTP response to your browser in terms of static HTML
content.

46
• Finally, the web browser handles the dynamically-generated HTML page inside the HTTP
response exactly as if it were a static page.

All the above-mentioned steps can be seen in the following diagram −

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists
and whether the modification date on the JSP is older than the servlet. If the JSP is older
than its generated servlet, the JSP container assumes that the JSP hasn't changed and that
the generated servlet still matches the JSP's contents. This makes the process more
efficient than with the other scripting languages (such as PHP) and therefore faster.

JSP - Lifecycle
In this chapter, we will discuss the lifecycle of JSP. The key to understanding the low-
level functionality of JSP is to understand the simple life cycle they follow.

A JSP life cycle is defined as the process from its creation till the destruction. This is
similar to a servlet life cycle with an additional step which is required to compile a JSP
into servlet.

Paths Followed By JSP


The following are the paths followed by a JSP −

• Compilation

• Initialization

• Execution

• Cleanup

47
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The
four phases have been described below −

JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to
compile the page. If the page has never been compiled, or if the JSP has been modified
since it was last compiled, the JSP engine compiles the page.

The compilation process involves three steps −

• Parsing the JSP.

• Turning the JSP into a servlet.

• Compiling the servlet.

JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override
the jspInit() method −

public void jspInit(){

// Initialization code...

48
Typically, initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the
jspInit method.

JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.

Whenever a browser requests a JSP and the page has been loaded and initialized, the
JSP engine invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and


an HttpServletResponse as its parameters as follows −

void _jspService(HttpServletRequest request, HttpServletResponse response) {

// Service handling code...

The _jspService() method of a JSP is invoked on request basis. This is responsible for
generating the response for that request and this method is also responsible for
generating responses to all seven of the HTTP methods, i.e., GET, POST, DELETE,
etc.

JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed from
use by a container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jsp Destroy when you need to perform any cleanup, such as releasing database
connections or closing open files.

The jspDestroy() method has the following form −

public void jspDestroy() {

// Your cleanup code goes here.

49
Elements of JSP
The elements of JSP have been described below −

The Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or method
declarations, or expressions that are valid in the page scripting language.

Following is the syntax of Scriptlet −


<% code fragment %>

You can write the XML equivalent of the above syntax as follows −
<jsp:scriptlet>
code fragment
</jsp:scriptlet>

Any text, HTML tags, or JSP elements you write must be outside the scriptlet.
Following is the simple and first example for JSP −

<html>

<head><title>Hello World</title></head>

<body>

Hello World!<br/>

<%

out.println("Your IP address is " + request.getRemoteAddr());

%>

</body>

</html>

Exercises

Read and practice about JSP client request, JSP server response, JSP form processing,
File uploading and sessions?

50

You might also like