Professional Documents
Culture Documents
Course Module Oop PDF
Course Module Oop PDF
Faculty of Technology
Course Module
For
September 2012
DTU
1
Chapter One
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
History of Java
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.
Example:
4
public static void main(String []args) {
System.out.println("Hello World");
}
}
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.
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
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
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
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
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
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.
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.
To initialize characters, the characters are placed under single quotes while strings are
under double quotes.
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;
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
14
- -op Arithmetically negates op
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
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.
Value of b is : 30
Value of b is : 20
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
>> 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 {
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 {
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 {
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 {
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
22
System.out.print("\n");
}
}
}
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 {
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:
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 {
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 {
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
27
Chapter three
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
}
}
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) {
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:
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:
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
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
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
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.
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.
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
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
}
• 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.
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.
Try{
Catch(ExceptionType1 exOb ) {
41
Catch(ExceptionType2 exOb ) {
Example:
public ExcDemo() {
}
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
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.
• 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. 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.
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.
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.
• 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.
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 −
// 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 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.
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.
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/>
<%
%>
</body>
</html>
Exercises
Read and practice about JSP client request, JSP server response, JSP form processing,
File uploading and sessions?
50