You are on page 1of 182

SE Sem III Comp.

/ IT
Object Oriented Programming Methodology

( OOPM )
Index
1. Java Language Features :
1-6
Java Development Kit (JDK), Features of Java, Platform independence of Java,
Java Virtual Machine (JVM). Difference between Java and other language.
2. Java Language :
7 - 24
Keywords, Data-types, Data type conversion(casting), Operators, Control statements,
Arrays, arraycopy() method, Command Line arguments, Data Input/Output.
3. OOP Concepts in Java :
25 - 46
Basic OOP terms, Working with classes and objects. Passing Parameters to methods,
Method overloading, Constructors, Static members of class, this keyword, Garbage
collection utility, finalize() method. OOD by Grady Booch.
4. Inheritance :
48- 67
Concepts and syntax, Types of inheritance, Method Overriding, keyword super,
keyword final, Abstract methods & classes, Access Modes(visibility modes),
Javas Object class, Class Relationships. Interfaces, Difference between
interfaces and Abstract classes.
5. Exception Handling:
68 - 76
What is exception, try-catch-finally blocks, throwing exceptions(throws, throw keywords).
6. User defined packages :
79- 69
What is package. Keywords, Defining and using a package.
7. java.lang package:
71 - 87
Classes : String, StringBuffer, System, Math, Wrapper classes, Character class.
8. Collections and java.util package:
88 - 95
Classes : Vector, ArrayList, LinkedList. JAR utility for bundling required files.
9. Applet and Graphics programming :
86 - 105
Running Applets, Applet life-cycle, Applet related tags, Passing Parameters to Applet,
Graphics class and applets,
10. Multithreading :
106- 114
Creating threads (Thread class, Runnable interface), thread priority,
Thread class methods, Thread synchronization, thread life-cycle.
Previous Papers.

127 - 136

Solved programs from Previous Years


June-2008 to Dec-2011 (old)

137 - 181

Prepared by, Santosh Kabir.


Mobile : 98336 29398
www.santoshkabirsir.com

OOPM ( Sem III - Comp / IT )

1. Java Language Features


Java is an Object Oriented Programming language, with syntax and keywords almost derived from C++
(basic syntax same as C). Java was first developed by James Gosling, Patrick Naughton, Chris Warth,
Ed Frank and Mike Sheridan at Sun Microsystems, Inc. in 1992. The language was initially called Oak
but was renamed to Java in 1995.
Two types of programs can be developed using Java: Applications and Applets. Applications are
programs ( that work more or less like C++ or Visual Basic programs) that execute on our computer. An
Applet is a program designed to be transmitted over the internet and executed by a Java compatible
Web-browser. Its a tiny Java program dynamically downloaded across the network.
Java applets can be transmitted over the internet and can be downloaded without a fear of getting
attacked by viruses. So Java applets are safe and secure.
Java program is compiled to give a semi-compiled portable code which can be executed on any type of
computer. ( platform independence of Java)

Java Development Kit (JDK) :


Java Software is available at Sun Microsystems Website from which it can be downloaded (free) in
different versions of JSDK ( Java System Development Kit) also called as JDK. JDK are available in
single Executable file on net. Install JDK in computer, in a system drive (commonly C ) in a folder (with
a simple name like myjava ). In later steps of installation, install Java Runtime Environment (JRE) in
some subfolder of your JDK folder. This will install a number of tools in the form of Windows executable
programs (i.e. .exe files).

JDK stands for Java Development Kit, also called as Java System
Development Kit(JSDK). It is a software made up of different utilities, using which
user can compile, debug(check for errors) and execute Java programs.
The first version (JDK 1.0) was released at the end of 1995. Then, over the last
few years it was upgraded and made more stable. The first stable version of
Java
was
JDK1.2
(
also
called
Java-2).
The latest version, when these notes were written was JDK 1.7.
Java (JDK) consists of following major parts :
Java Compiler, Java Runtime Envirnment (JRE) and Some demo Java
programs.
JRE : This mainly consists of JVM and Java API:
JVM stands for Java Virtual Machine; also called as Java interpreter. This is
used to execute Java programs.
Java consists of hundreds of in-built classes/interfaces and thousands of
methods in them. This set of classes and interfaces is called as Application
Programming Interface (API).
Demo programs : This consists of some Java programs to assist new Java
programmer to develop small program.
The classes and interfaces ( i.e. Java API) are categorized according their
use/purpose and are stored under multiple packages.
Prepared by, Santosh Kabir
2
1. Java language Features
Mobile : 98336 29398 ( www.santoshkabirsir.com )

OOPM ( Sem III - Comp / IT )

For different operating systems different versions of JDK are available. For example
for Java programming in Windows, one should use JDK for Windows, and
programming on UNIX system one should use JDK for UNIX.

The commonly used utilities of JDK are :


Java Compiler: This is a javac.exe. Used to compile Java application. It
compiles the Java files into class files i.e. Bytecode files. Like any other
compiler it checks syntax errors and displays them. If there is no error in a
program it is compiled to one or more class files.
Java Virtual Machine (JVM) : This is java.exe. Used to run a Java application.
JVM loads a specified Class file (byte-code file) into computer and step by step
interprets the instructions and executes them. This is an important part of
Java that makes the language Platform independent.
Java disassembler: This is javap.exe. Enables to convert bytecode file into
program description (actually class description).
Java Debugger : This is jdb.exe. Using this programmer can move through a
programm step by step and check errors (called as debugging).
Appletviewer :This is appletviewer.exe. Its a small Java browser. Appletviewer
enables us to run Java applets (without using Java enabled browser like IE ).
JAR : It is a Java Archive utility. This is commonly used to compress multiple
files (like Java source file, class files and other files like image, sound files)
into one JAR file i.e. we can create one .jar file using this utility.

Features of Java :
The main purpose of the development team of Java was to provide a simple but still
powerful, secure and portable programming language. Some important features of
Java language are as follows.

Object-Oriented:
Java is purely OOP language, and many of the features and syntaxes of Java are same
as C++. Since, it is a purely OOP language, we need to define at least one userdefined type (class) in a program. Simple data-types like integers, floating-point
numbers are non-objects, but for these basic types also, Java provides a group of
classes (wrapper classes)

Compiled and Interpreted:

Java language has two stages: Compiling and then Interpreting. When a Java
program is compiled it translates the source code into Bytecode instructions. Bytecodes
are not machine instructions. When a Bytecode program is run it is step by step
interpreted into machine instructions and executed.

Platform independent :

A program written in Java, is independent of the hardware and Operating System. A


compiled Java program (bytecode) can be run on any Operating System with the help of
Java Virtual Machine (JVM).

3
Mobile : 98336 29398 ( www.santoshkabirsir.com )
Prepared by, Santosh Kabir

1. Java language Features

OOPM ( Sem III - Comp / IT )


Robust and Secure :
Since Java was aimed to work on different platforms (OS and hardware) it was
designed to work reliably on variety of systems. Lots of error-checking is done by
Java compiler when a program is compiled. Since it is strictly typed language, a lot
of data-type-compatibility mistakes will be reported by Java compiler.
Also, for trapping run-time error Java provides a powerful Exception handling
mechanism. The run-time errors can be easily handled by Javas in-built Exception
handling features.
Automatic Memory Management : Java rather JVM handles the job of managing
memory used up by program objects. This achieved by Garbage collector utility of JVM)
Thus, the common reasons of program failure at run-time are avoided.
Java Applets : Run on computers without fear of getting virused. Also, since Java does
not use pointers it ensures that program does not access memory loacations
(purposely or by mistake), without proper authorization.

Multithreaded:

Multiple parts of a Java program can work at time. This feature is called as
multithreading. This multithreading feature is used to develop multi user systems
such as Server programs and multimedia programs.

Simple :

Java was designed to be simple for professional programmers to learn and use
effectively. A lot of advanced programming features such Multithreading, Exception
handling, Distributed computing are implemented in a very simple way, so that
programmers can use these feature easily.

Syntax similar to C++:

At the time of development of Java, the most popular

computer language was C++. The syntax and a lot of OOP features of Java are
inherited from C++ only. Also, some of the confusing and redundant features of C++
were left out or implemented in a simpler and cleaner manner.

Platform Independence of Java :


Platform stands for the Hardware and the Operating System requirements of a program to execute successfully.
Program written in high level languages like C++, when compiled (although compiling is not perfect process name),
generates a low-level language instruction (machine language) program (with extension .EXE). This program runs
on a particular platform on which it is developed. For example program developed and compiled on Windows can
not work on UNIX system. Thus, in this case we can say the compiled program is platform dependent.
[ The above part may not be written in Answer ]
Platform independence of a program means a program should be able to run
on any computer system. i.e. same program should run on Windows, Unix,
Mac OS systems etc.
Java compiler compiles a Java source code into a .class file that is made up of
Bytecode instructions, which are not machine instructions and cant execute
on machine directly. This is somewhat a semi-compiled file.

4
Mobile : 98336 29398 ( www.santoshkabirsir.com )
Prepared by, Santosh Kabir

1. Java language Features

OOPM ( Sem III - Comp / IT )

This bytecode program can be to be executed by the Java-runtime system,


called as Java Virtual Machine (JVM). JVM is a program that interprets the Bytecode
instructions into the machine instructions on which it is working and runs for that
machine. Thus, a Java program is platform independent i.e. programs written in Java can
be run on any System.
There are different JVMs available for different types of platforms. Thus, once
a Java program is written and compiled it gives a bytecode program which any
JVM can interpret and run. Obviously the different JVMs on different
platforms will interpret the same bytecode in different way.

Java source program


.java file

Compiling with Java compiler

Compiling a
Program

Compiled code
.class file
(Bytecode file)

JVM for
Windows
system

Code Interpreted
for Windows

Computer
with
Windows
system

JVM for
UNIX
system

Code Interpreted
for UNIX

Computer
with UNIX
system

5
Mobile : 98336 29398 ( www.santoshkabirsir.com )
Prepared by, Santosh Kabir

JVM for Sun


Solaris
system

Running a
program

Code Interpreted
for Solaris

Computer
with Solaris
system

1. Java language Features

OOPM ( Sem III - Comp / IT )

Java Virtual Machine (JVM) :


Most of the high level language programs are compiled into machine code files (called executable i.e. .EXE files).
But, programs written in Java are compiled to a class files called Byte-Code file.
[ Above part may not be written in exam ]
Java Virtual Machine is a set utilities which does a job of running a Java
program in the form of a byte-code (i.e. class file).
JVM has a compiler called as Just-In-Time (JIT) Compiler that interprets the
bytecodes, part by part as required, into machine language instructions. These
machine instructions are then passed to the actual machine (hardware and
OS) to execute. Thus, JVM virtually works likes a machine for byte-codes. The
entire bytecode program is not converted into machine language at a time
JVM also provides a Run time Environment for a running any Java program. To
run one Java program, one instance of JVM starts and the Java program runs
in that JVM. Thus, if there are multiple Java programs running in a
computer, there will multiple instances of JVM running in the computer.
Java virtual machine has a class loader subsystem: a mechanism for loading
types (classes and interfaces) given fully qualified names.
Each Java virtual machine also has an execution engine: a mechanism
responsible for executing the instructions contained in the methods of loaded
classes.
According to working JVM has following internal architecture,
Class
files

Class loader
subsystem

Runtime data Areas


( Method area, Heap area, stack, Java stacks area etc.

Execution
Engine

Native method
Interface

When a Java Virtual Machine runs a program, it needs memory to store many
things. e.g. 1. byte-codes and other information it extracts from loaded class
files, 2. Objects created in programs, 3. parameters to methods, return values,
local variables, and 4. Intermediate results of computations. The Java virtual
machine organizes the memory it needs to execute a program into several runtime data
areas.
JVM does a job of generating and throwing errors (called Exceptions) in program if
any runtime error condition occurs.

6
Mobile : 98336 29398 ( www.santoshkabirsir.com )
Prepared by, Santosh Kabir

1. Java language Features

OOPM ( Sem III - Comp / IT )


While the program is running, the Memory management is performed by
garbage Collector which is invoked by JVM.
Different types and versions of JVMs are used on different Operating Systems.
Because each OS has its own way of loading and running a program. e.g.
there exist separate JVMs for Windows, UNIX, MacOS etc. Java program can
be written on any type of computer and compiled to bytecode (class file).
The same byte code can work on UNIX machine with the help of JVM for UNIX
and on Mac machine with the JVM of Mac type. Thus, JVM provides a very
important feature to Java called as Platform Independence.

How Java differs from Other Languages :

Java compiling has two stages : compiling and interpreting. Java program is
compiled to Bytecodes and then while running it is interpreted step-by-step to
machine language.
Java is platform independent. For other languages, the entire program is
compiled (at a time ) into machine language code, which can be run on same
type of machine. Whereas Java program is compiled to machine independent
Bytecode which can be then executed on different machines by different
JVMs.
Java programs can be Console applications, Applets, Event driven GUI
programs, Applets or internat based applications. All the language donot
support all these kinds of programs.
Java does not give programmer control over memory de-allocation and hence
no destructors in Java. But, Java provides Garbage collector utility for memory
management. A few language support automatic memory management.
Also, Java does not support Multiple inheritance (with classes), friend
keyword, Pointers, Operator overloading, Header files, template classes.
Java supports Interfaces using which multiple inheritance is achieved.
===============

7
Mobile : 98336 29398 ( www.santoshkabirsir.com )
Prepared by, Santosh Kabir

1. Java language Features

OOPM ( Sem III - Comp / IT )

2. Java Language Basics


Java language derives its syntax and a lot of OOP features from C++. Hence, we can directly start
learning Java basics.
Following points should be followed for writing and running Java programs.

Its case sensitive language.

Semicolon should be written at the end of statement.

Curly braces ( { } )are used to enclose block of statements (e.g. compound statements in case
of control statements) and function statements, class definitions.

Single line comment can be written by putting two slashes ( // ) before the code to comment.
Multiple lines can be commented by using /* to begin comment and */ to end comment.

Built in Java class names start with Capital letter, and if class-name is made of multiple words
then
each
word
starts
with
e.g. StringBuffer,InputStreamReader, Integer are built-in classes.

capital

letter.

Built in Java function names (called methods) start with Lower case letter, and if it is made of
multiple words then all other words in the name will start with a Capital letter.
e.g.
parseInt( ), indexOf(), readLine() are a few built-in method names.
Since, Java is OOP language all the methods belog to some classes.

Following are the keywords of Java,

abstract
assert
boolean
break
byte
case
catch
char
class
const

continue
default
do
double
else
extends
final
finally
float
for

goto
if
implements
import
instanceof
int
interface
long
native
new

package
private
protected
public
return
short
static
strictfp
super
switch

synchronized
this
throw
throws
transient
try
void
volatile
while

Other than these keywords Java has three reserved words: true, false and null which should be used
for their intended purpose only. These words should not be used as identifiers.

Prepared by, Santosh Kabir

Mobile : 98336 29398

2. Java Basics

OOPM ( Sem III - Comp / IT )

Data-types of Java:
Java Data Types
Primitive

Non-primitive
(Object type)

Numeric
Integer type

Non- numeric
Floating-point type

Classes

char

Interfaces

boolean
byte

float

short

double

Arrays

int
long

Primitive data-types :
Java provides eight primitive data-types (refer above figure), which are non-objects.
The variables of these types occupy certain predefined amount of bytes in memory
and they are value variables.
These types of variables can hold values in certain pre-defined range. If value other
than the range (see details below) is assigned then it can generate compiler/run-time
error.

1. Integer Types :
Typename
Size(bits)
byte
8
short
16
int
32
long
64
By default integer values are

Range
-128 to 127
-32768 to 32767
-231 to 231 1
-263 to 263 -1
treated as int types.

2. Floating-point types :
Typename
float
double

size(bits)
32
64

Range
1.4 e -45 to 3.4 e +38
4.9 e -324 to 1.8 e +308

By default Java treats floating-point literals as double data-type.


e.g. value 2.5 is treated as double type data. To use the value as float type we attach
a letter f or F to the value. i.e. 2.5f is treated as float type value.
Prepared by, Santosh Kabir

Mobile : 98336 29398

2. Java Basics

OOPM ( Sem III - Comp / IT )


3. Characters:
Type name
Size in bits
Range
char
16
0 to 65535
This data-type is used in Java to hold characters. Java uses Unicode to represent
characters.

4. Boolean type:
It is a simple data-type of Java (defined as boolean), which is used to hold logical
values. It can hold only one of the two possible values: true or false.

Non-Primitive Types (Object types) :


The non-primitive types are object types.
They are reference type variables, and hold reference for an object in memory. The
size of an object is not fixed.

Type Conversion and Casting :


Java performs data type conversion if required when any expression is evaluated at
two different statges: a) when two operands of different types operate to generate
some result b) while assigning one type of value to the other type of variable.
For any type conversion the two operands must be type compatible.

Automatic type conversion:


When one type of data is assigned to the other type of variable, an automatic type
conversion will take place if both the following conditions are met,
1. The two types are compatible.
2. The destination type is larger than the source type.
This kind of conversion is called as widening conversion.
Numeric data-types are not compatible with char and Boolean. Also char and
boolean types are not compatible to each other.

Casting:
Incompatible types can be used in an expression or assigned to other type using
explicit type conversion. This is called data-type casting and the syntax used for this
casting is,
( target_type ) value;
In the example below the float value is cast to an int value.
int a;
float k=12.5f, p=2.5f;
a = (int) (k * p);
a = k*p; // error
After the last expression is evaluated variable a will hold the value, 31.

Prepared by, Santosh Kabir

Mobile : 98336 29398

10

2. Java Basics

OOPM ( Sem III - Comp / IT )


Thus, when a floating-point value is assigned to an integer type, type conversion
takes place and the fractional component of the floating-point value is lost. This type
of conversion is also called s truncation.

Type Promotion rules:


Byte and short type values are always promoted to int type when an expression involving
the two types is evaluated.
e.g.
byte b=10, c= 5;
int a;
b = b*c; // Error
Since the expression on the RHS of = evaluates to int type.
Following statements are valid
b = (byte) (b * c);
a = b * c;
Other than this when an expression evaluated,
if one of the operand is long type then, the expression value is promoted to long, if
one of the operand is float type then, the expression value is promoted to float and if
one of the operand is double type then, the expression value is promoted to double
type.

Type conversions for object types:


The classes that are not related to each other by inheritance are Not type compatible.
But, a sub-class object is compatible to super class variable. The reverse is not true.
Assume ABC is a super class of XYZ then,
If sup1 is a object variable of a super class (ABC) and sub1 is object variable of any
of its sub-class (XYZ) then,
sup1 = sub1;
is valid
but, sub1 = sup1; is invalid
.
But, again type-casting can be performed to assign super class object to sub-class.
i.e. sub1 = (XYZ) sup1;
will work

Operators in Java :
:
A lot of Java operators are same as that in C/C++: syntax and functioning.

Arithmetic operators:
These operators are used in mathematical expressions to evaluate some value.
They are as follows,
+ , - , / , *
Arithmetic
++ , -Increment , decrement
+= , -=, /=, *=, %=
Compound assignment
%
Modulus (Remainder after division)
Prepared by, Santosh Kabir

Mobile : 98336 29398

11

2. Java Basics

OOPM ( Sem III - Comp / IT )


These operators can operate only numeric type operands.
Modulus (%) operator of Java can be used with integer as well as floating-point operands.
e.g.
int a=13, b=5, c;
double x=12.7, y=2.5;
c = a % b;
y = x % y;
After the above operations variables c and y will hold the values, 3 and 0.2
respectively.
Operator + is also used to concatenate string value with string values or with other type of data.
e.g. String s1 = hello!, s2 = Good morning!, s3;
int a=5, b=6;
s3 = s1 + s2 + b;
s3 will be hello!Good morning!6
s3 = s1 + a + b;
s3 will be hello!56
s3 = val= + (a+b); s3 will be val=11

Relational operators:
These are used to determine the relation of one operand to the other. These
operators are as follows:

< , <=,

>,

>=,

== ,

!=

The outcome of the operations will be a boolean value (true or false)


Note: Not 1 or 0 as in case of C++.
e.g.
int a=10, b=5;
boolean m;
Syatem.out.println( Ans= + (a < b) );
will output, Ans=false
or the result of the expression can be stored into a Boolean variable.
e.g. m = a < y;
here, m gets value false.
Or one can write a if statement as,
if ( a < y )
{ //some statements
}
But, following is not valid in Java.
Following is valid in Java.
int found =1;
boolean found = true;

if ( found )
if ( found )
{ //some statements
{ //some statements
}
}
Operator + is also used to concatenate string value with string values or with other type of data.

e.g. String s1 = hello!, s2 = Good morning!, s3;


Prepared by, Santosh Kabir

Mobile : 98336 29398

12

2. Java Basics

OOPM ( Sem III - Comp / IT )


int a=5, b=6;
s3 = s1 + s2 + b;
s3 = s1 + a + b;
s3 = value= + (a+b);

s3 will be hello!Good morning!6


s3 will be hello!56
s3 will be value=11

Boolean Logical operators:


These operators operate on Boolean values and generate Boolean values. Operators are listed below.
& - logical AND, | - logical OR, ^ - Logical EX-OR.
&& - Short-circuit logical AND, || - Short-circuit logical OR
! Logical NOT
Also, &=, |= , ^= , ==, != are treated as Boolean logical operator.
Following table shows the effect of each logical operator:
Operands

Operation and results

A|B

A&B

A^B

!A

False

False

False

False

False

True

False

True

True

False

True

True

True

False

True

False

True

False

True

True

True

True

False

False

Short-circuit operators && and || give same result as that of & and |.

Short-circuit Logical operators:


These are Boolean operators, which function in different way than the normal
Boolean logical operators. These are short-circuit OR ( i.e || ) and Short-circuit
AND (i.e. &&)
OR operator results into true if first operand (i.e. any one operand ) is true, no matter
what the other operands are.
Similarly, the AND operator results into false if first operand (ie. Any one operand) is
false, no matter what the other operands are.
Thus, if these operators ( i.e. && or || ) are used in place of & or |, Java will not
evaluate the second operand (i.e. right-hand side operands), if the outcome of the entire
expression can be determined by the left-hand side operand.
e.g.
int a=10, b=5, c=20;

if( a >=b || ++c <= 25)

In the above logical expression, since the Left-hand side operand ( a>=b) evaluates to
true, the expression is true, irrespective of outcome of right-hand side operand,
hence Java will not evaluate that operand.
Hence, variable c will not be operated and will not change.
Whereas the normal logical operator Or ( | ) will evaluate both the operand and the
value of variable c will be incremented.
Prepared by, Santosh Kabir

Mobile : 98336 29398

13

2. Java Basics

OOPM ( Sem III - Comp / IT )


Conditional ( ? : ) operator:
The operator has a syntax as follows,
Expression1 ? Expression2 : Expression3 ;
Here, the expression1 can be any expression that evaluates to Boolean value. If the
expression1 result into true, then the expression2 is evaluated else the expression3
is evaluated. The result of the entire expression ( ? operator) is that of the expression
evaluated.
e.g.
int a=10, b=5, m=4;
m = a<=b ? a+b : b*c;
Here, the expression a <= b is evaluated. If it is true the a+b will work else b * c will
work, thus the result will be any one of the two, which will be assigned to m.
Here, m gets value 20.

Memory allocation operator (new):


The new operator is a keyword of Java, which is used to allocate memory for classobjects and arrays. The syntax of using new is as follows.
ReferenceVariable = new DataType[ number ] ; // for arrays
ReferenceVariable = new ClassName(ParameterList) ; // for class-objects
The operator allocates memory space required for the specified data-block and
returns the reference in the reference variable (on the LHS).
e.g. One can define an array of n integers as follows,
int[ ]a;
// defines a reference var. for array
a = new int[ n ];
// allocates memory for array and assigns its ref to variable a
OR ( using single statement )
int [ ] a = new int[ n ];
Object of a class, say Demo class is allocated as follows,
Demo obj = new Demo();
Or using two separate statements,
Demo obj;
obj = new Demo();

Control Statements :
All: the control structures in Java are very much same as that supported by C/C++.
:
Selection statements:
if :

The statement is used to select what part of the program should execute

according to different conditions arising in a program. It has following three general


syntaxes (which are same as that in C++):
1. if ( condition )
statement
Prepared by, Santosh Kabir

Mobile : 98336 29398

14

2. Java Basics

OOPM ( Sem III - Comp / IT )


2. if( condition )
Statement1
else
Statment2
3. if ( condition1)
Statement1
else if ( condition2)
Statement2
else if ( condition2)
Statement2

else
Statement..n
The if, if-else and if-else if statements should not have semicolons.
If multiple statements are to be written for one condition, then those statements
must be enclosed inside the curly braces.
e.g.
if ( a <=b )
{
d = a+b;
c = p*q;
}
else
a = a * 2;

switch-case:
Its a selection statement, similar to multiple if-else if. The syntax is as follows,
switch( expression )
{
case value_1 : Statements
break;
case value_2 : Sataments
break;

case value_n : Statemets


break;
default : Statements
}
The expression must be integer type i.e. it can be byte, short, int, long or char. Also,
each of the values specified in case statements must be type-compatible with the
expression. The case values must be unique literals (constants). Variables not
allowed. Its working is as follows,
An expression is evaluated. Then the value of the expression is compared with literal
values in the case statement (from top to the end of switch-case block). If a match is
Prepared by, Santosh Kabir

Mobile : 98336 29398

15

2. Java Basics

OOPM ( Sem III - Comp / IT )


found then, the code sequence in that case statement is executed (if break statement
is present).
The break statement is used with the case statement to quit out of the switch-case
statement. The break statement is optional. If it is not present in a case statement,
then program will continue to the case statement.
The default statement is also optional. If all the cases are false then default
statement is executed.
We can write one case statement with multiple values,
e.g. case 10: case 20 : cout<< Hello !;
break;
switch-case statement works more efficiently than an equivalent if-else statement.
This is because, Java compiler keeps the jump table ready for different case values (since they are constants,
compiler can decide the jumps compile-time). When switch-case statement works, according to the expression
value the jump is taken for execution of that case statement.

Iteration statements: (Looping statements):


These statements make some part of program repeat for multiple time till some
condition is true. The statements are while, for, do-while. (same as those in C++).

while:

The looping statement is used to repeat a block of statements till some condition is
true. The condition should be a Boolean expression.
while ( condition)
statements
e.g. see the following code,
int a =1;
while ( a < 5)
{
System.out.println(Hello.. + a );
a += 2;
}
System.out.println(a = + a );
The code above will generate following output,
Hello..1
Hello..3
a=5

do-while statement:
do-while is similar to a while statement. But it can be used in the situations where
the statement in the loop must be executed at least once. Syntax of the statement is
as follows.
Prepared by, Santosh Kabir

Mobile : 98336 29398

16

2. Java Basics

OOPM ( Sem III - Comp / IT )


do
{
statements
} while( condition );
From the above syntax it is clear that he condition is checked at the end, and hence
the statement pat will work at least once.
while loop repeats till the condition is true. If the condition is false at the beginning,
then the statement will not work at all.

for statement:
This is a looping statement with following syntax,
for ( initialization ; condition ; iteration )
Statements
The statements part will be repeated till the condition is true.
e.g.
int a;
for( a=5; a >= 2 ; a -= 2)
System.out.println(Hello.. + a );
System.out.println(a = + a );
Output of above code will be,
Hello..5
Hello..3
a=1
Note: if any variable is declared inside the block of any control statement, its scope is
restricted to the loop block and cant be used outside the loop. Also, variable
declared in the for statements first line will have scope inside the loop only.

for with multiple variables (comma operator):


We can use comma operator
int m, n;
// Multiple variables can't be declared in for

for( m=1, n=5; m <= 3; m++, n-=2 )


System.out.println("m = " + m + ", n = " + n );
System.out.println("m = " + m + ", n = " + n );
Output of the above code will be,
m = 1, n = 5
m = 2, n = 3
m = 3, n = 1
m = 4, n = -1
In Java comma operator is a separator that applies only to the for loop.

Prepared by, Santosh Kabir

Mobile : 98336 29398

17

2. Java Basics

OOPM ( Sem III - Comp / IT )


break as goto statement: (Labeled break)
break statement can be used in any looping statement (while, do-while and for) to terminate the loop,

in which it appears.
e.g.

for( i=1; i<=50; i++)


{
System.out.print(..i= + i );
if( i % 7 == 0 ) break;
}
System.out.print( Loop finished );

In the above example the for loop is written to repeat (by default) for 50 iterations. The break statement
will work if variable i is divisible by 7. Thus, when i becomes 7, loop terminates.
The output of the above program will be.
..i=1 ..i=2 ..i=3 ..i=4 ..i=5 ..i=6 ..i=7Loop finished
Also it can be used in nested loops as a civilized form of a goto statement. If there are multiple loops
nested one inside the other, the break statements can be used to exit out of a particular loop (or block).
This is done by first putting a label at the start of the block. Then use this label as a target of break
statement. Now, when a program executes and the break statement is encountered, the program

execution will resume at the end of the labeled block. Labeled break is written using following
syntax,

break label;
Consider following example,

for(int i=2; i<=3; i++)


{
System.out.println("Outer loop");
xy: for(int j=22; j<=25; j++) // for with label
{
System.out.println("In inner loop :" + i + "," +j);
for(int k=11; k<=13; k++)
{
System.out.println("In innermost loop :" + k);
if(i+k >= 14) break xy; //breakes loop with j variable i.e. xy label
}
System.out.println("Innermost loop finished");
}
System.out.println("Inner loop finished :");
}
System.out.println("outer loop finished");
In the above example jump label xy: is written for the block of inner for statement. If the break
statement occurs the program control is transferred to the end of block with label xy. Output of the
program will be as follows,
Outer loop
In inner loop :2,22
Prepared by, Santosh Kabir

Mobile : 98336 29398

18

2. Java Basics

OOPM ( Sem III - Comp / IT )


In innermost loop :11
In innermost loop :12
Inner loop finished :
Outer loop
In inner loop :3,22
In innermost loop :11
Inner loop finished :
outer loop finished
In the program segment, consider the label is written before the curly brace of an inner for loop (loop of
j variable). If break encounters, the control is transferred at the end of that loop.
The common use of labeled break statement is to exit the nested for loop. e.g. if the label was written
for an outermost loop, then if the break is encountered the program execution will resume from
statement next to outermost loop.

continue:
The statement is used inside looping statements like while, do-while, and for to skip some part of the
block and continue from the top of the loop. In case of for the control is transferred to the variable
upgrading part (third part of for statement). After this control goes to condition checking part and if
condition is true loop continues. In case of while statement, the control is transferred to first line of while
(i.e. condition checking)
Consider example discussed in the topic before this,

for(int i=2; i<=3; i++)


{
System.out.println("Outer loop");
xy:for(int j=22; j<=25; j++)
{
System.out.println("In inner loop :" + i + "," +j);
for(int k=11; k<=13; k++)
{
System.out.println("In innermost loop :" + k);
if(i+k >= 14) continue xy;
}
System.out.println("Innermost loop finished");
}
System.out.println("Inner loop finished :");
}
System.out.println("outer loop finished");
The output of the above statements will be,
Outer loop
In inner loop :2,22
In innermost loop :11
In innermost loop :12
Prepared by, Santosh Kabir

Mobile : 98336 29398

19

2. Java Basics

OOPM ( Sem III - Comp / IT )


In inner loop :2,23
In innermost loop :11
In innermost loop :12
In inner loop :2,24
In innermost loop :11
In innermost loop :12
In inner loop :2,25
In innermost loop :11
In innermost loop :12
Inner loop finished :
Outer loop
In inner loop :3,22
In innermost loop :11
In inner loop :3,23
In innermost loop :11
In inner loop :3,24
In innermost loop :11
In inner loop :3,25
In innermost loop :11
Inner loop finished :
outer loop finished

Arrays :
:
:
element
in an array can be accessed by its index. Array index starts from 0 i.e. index of a first element

An array is a collection of same type of variables, that is referred by a common name. Individual
in array is 0 (zero).

One-Dimensional Array:
One dimensional array is a list of same type of variables. To create an array Java uses keyword new.

type [ ] Name;
Name = new type[ number ];
[ keyword new is discussed earlier ]
e.g. an array of 5 int type variables, is created as follows,

int [ ] m;
// variable name to refer an array of int type variables
m = new int[ 5 ] ;
// allocate memory for 5 int variables and put reference of an array in
variable m.
Above two lines can be combined as follows,

int [ ]m = new int[5];

All array elements are by default initialized as follows:


1. Zero: for array of basic numeric types (i.e. float, int etc), .
2. false: for array of Boolean variables
3. null: for array of object types (strings, class objects etc.)
Prepared by, Santosh Kabir
20

Mobile : 98336 29398

2. Java Basics

OOPM ( Sem III - Comp / IT )


Array can be initialized when it is declared.

e.g.

int b[ ] = { 5, 4, 10, -12 , 35, 25 };

here b works as an array of six int elements.

In any case array size cant be mentioned in array variable declaration.


Also, an array size must be integer.
i.e. int a[5] or float b = new float[45.5]; // will generate compile error
One can re-allocate memory for an array using same array variable.
e.g.

int[ ]m = new int[5];


// some statements
m = new int[20]; // memory re-allocated for 20 int again.
A new array with 20 ints will be allocated, old array will be lost (garbage collected).

System.arraycopy( ) :
The method copies entire array or part of an array to another array of same type.
It is present is in Javas built-in class System.
Applicable for One Dimensional arrays only.
The syntax of the method is as follows,
static
void
arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
Copies an array from the specified source array, beginning at the specified
position, to the specified position of the destination array.
Here, src is a source array from which elements will be copied to the dest i.e.
destination array.
The number of components copied is equal to the length argument. The components
at positions srcPos through srcPos+length-1 in the source array are copied into
positions destPos through destPos+length-1, respectively, of the destination array.
e.g.
int [ ]a = { 10, 20, 30, 40, 50 };
int [ ]b = { 1, 2 ,3 ,4 ,5 , 6 , 7 };
System.arraycopy(a, 1, b, 2, 3);
for(int i=0; i<5; i++)
{
System.out.print(b[ i ] + .. );
}
Contents of destination array b will change, and the for loop will output,
1 .. 2 .. 20 .. 30 .. 40 .. 6 .. 7
The method generates run-time error (exception) in following cases,
If any of the array is not initialized.
If the two array are of different types.
If while copying the element out of the array limit is accessed.
If any of the int argument e.g. length is negative.

Prepared by, Santosh Kabir

Mobile : 98336 29398

21

2. Java Basics

OOPM ( Sem III - Comp / IT )


Two-Dimensional Arrays :
In Java, multidimensional array is an array of arrays. Thus, the two dimensional array is actually an
array of multiple one-dimensional arrays. General declaration of two dimensional array is done as given
by following syntax,

Type [ ][ ]Name = new Type[rows] [columns];


e.g. float [ ][ ]f = new float[3][5];
Allocates a two dimensional array of 15 float variables. i.e. it consists of 3 rows, each of 5 elements.
Actually, it is an array of 3 arrays, each of 5 float elements.
The full dark lines show a 3 x 5 array.
0

Column numbers

0
Row
numbers

f
2

Each element in the array is accessed using its row and column numbers. e.g. in the above example
the shaded element has name f[2][1].
Two dimensional array elements can be initialized while declaring an array as follows.

int[ ][ ]a = { { 3,4,5,6 }, { 2, 4, 6, 8}, { 1, 3, 5, 7 } };


Above declaration allocates a 2-dimensional int array of 3 rows and 4 columns.

All the dimensions for all types of arrays can be specified dynamically.

In Java, accessing array element out of array limit is an Exception i.e. run-time error.
Program shows error and terminates if not handled properly.

Command Line Arguments :


Command line arguments are the values that are passed to Java program from command
prompt while running the Java program.
In Java the main() method must be defined with following syntax.
public static void main( String [ ] args )
{
// Statements
}
The method has String array as its parameter.
These string values are passed to program (i.e. main) by JVM when a Java program
is run from Command prompt. These are nothing but the values that are entered
while running a Java program from the command prompt. These values can be used
in a program as user input.
For example, a class file MyClass is run from command prompt as follows,
Prepared by, Santosh Kabir

Mobile : 98336 29398

22

2. Java Basics

OOPM ( Sem III - Comp / IT )


> java Myclass My Rollno is 45
Here, the full command written to run a Java program is called command line, and
the extra strings that are specified after the class file name are called as command
line values. Here, there are four string values:
1) My , 2) Rollno 3) is 4) 45
These multiple values must be separated by spaces at at command line while
entering. A main() method receives these values in a string array (here args)
specified in the method definition. Thus, the length of args array will be four.
Thus, the array args will hold these values as shown below, and can be accessed by
main() if required.
My
Rollno
is
45
args array
args[0] args[1] args[2]
args[3]
[ Write following with example if question is more than 6 marks ]
Following program adds the two integers input from command line and shows the sum of the numbers,

class CmdLine
{
public static void main(String[ ]args)
{
int a,b,c , len;
len = args.length; // get length of args array.
if( len> 0)
{
a = Integer.parseInt( args[0] );
b = Integer.parseInt( args[1] );
c = a + b;
System.out.println( "Sum = " + c );
}
}
}
Run the program with two command line values (integers) as given in the following example.
java CmdLine 20 30
output will be , Sum = 50

Using a name args for the argument array is a convention. Programmer can specify any name of
his choice.

Data Input / Output:


Outputting data (On display) :
Function print() or println() are be used to output text data to the console (monitor). print function
outputs data and cursor stops on the same line. println() function displays data and the cursor goes to
beginning of the next line for output. One can also use combination of characters (called escape
sequences) for formatting or controlling the output.
\n new line
\r Carriage return (beginning of same line)
Prepared by, Santosh Kabir

Mobile : 98336 29398

23

2. Java Basics

OOPM ( Sem III - Comp / IT )


\b Backspace
Also to output multiple values from different variables one can use a string concatenation operator ( + ).
Consider following statements and their outputs.

System.out.print("first output..");
System.out.println("second output..");
System.out.print("third output..");
System.out.print("Fourth output\n");
System.out.print("ABCD\bEFGH");
System.out.println();
System.out.println("GOOD MORNING\rpqrst");
double d1 = 12.345678;
int a= 10, b=30;
System.out.print("a=" + a +" .. d1=" + d1 + "\n");
System.out.print("S. Kabir sir- 9833629398\n");
System.out.println("Bye");
Outputs are as follows,
first output..second output..
third output..Fourth output
ABCEFGH
pqrstMORNING
a=10 .. d1=12.345678

S. Kabir sir- 9833629398


Bye

Inputting data from user (from keyboard) :


Data input can be done from command line as discussed in previous topic.
Java program can input data from console using built in classes like

DataInputStream or

BufferedReader. To use the classes one has to write an import command as shown in the program
below,

import java.io.*;
class Test
{
public static void main(String[ ]args) throws IOException
{
//DataInputStream inp = new DataInputStream(System.in);
// OR
BufferedReader inp = new BufferedReader( new InputStreamReader(System.in ));
System.out.println("Enter no , name, Avg marks");
int no = Integer.parseInt(inp.readLine());
String name = inp.readLine();
float avg = Float.parseFloat(inp.readLine());
System.out.println("no=" + no + " , name=" + name + " , Avg marks= "+ avg);
}
}
Prepared by, Santosh Kabir

Mobile : 98336 29398

24

2. Java Basics

OOPM ( Sem III - Comp / IT )


Input using Scanner class methods:
A Scanner class from java.util package provides methods to read different type of values input streams.
We can use it to input (i.e. read ) values from console input device (i.e. from keyboard). See the
following example:

import java.util.*;
class Test
{
public static void main(String[ ]args)
{
Scanner inp = new Scanner( System.in );
System.out.println("Enter no , name, Avg marks");
int no = inp.nextInt();
String name = inp.nextLine();
float avg = inp.nextFloat();
System.out.println("no=" + no + " , name=" + name + " , Avg marks= "+ avg);
}
}
=============

Sem IV - IT

Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]

( Learn to design and develop small Internet based programs )

Regular batches at Andheri, Thane, Dadar.

By Santosh Kabir sir.


Mobile : 98336 29398
Visit : www.santoshkabirsir.com for batch schedule and other info.

Prepared by, Santosh Kabir

Mobile : 98336 29398

25

2. Java Basics

OOPM ( Sem III Comp / IT )

3. OOP Concepts in Java


Overview of Object Oriented Programming:
OOP allows programmer to put data and the functions, operating on the data,
together in a single unit called Class. The instances of the classes (also called
objects) can be used in a program and the functions of the class can be called. The
data that the object uses is usually kept inaccessible from outside the program
outside the class. New classes can be derived from existing classes that can have
additional features.
( Class is similar to structures in C in case of syntax and working, with lots of
additional features and rules )

Basic Concepts of OOP :


(different paradigms used in OOP)
1. Class:
It is a user defined data-type, that holds multiple data-members (variables, objects
etc) and functions. It defines abstract characteristics of any entity such as its
attributes, properties (data members) and behaviours (functions).
Classes are means of separating data and programming code for particular entity
from other entity in the program. Thus, classes provide modularity in the objectoriented program.
Class describes the Properties and Behaviours (i.e. data and functions) of a real life
entity which can be a thing , person, Process etc. in general called as Object.
e.g. Dog is type of leaving thing with Properties like Name, Age, Colour, Weight etc.
and it can exibit some functions like Running, Barking, Sleeping etc.

2. Objects:
An object is an instance of a class i.e. a variable of type class. Thus, class is a type
and the object is an entity in program that works like the type.
e.g. Dog is a class. A particular Dog say name= Moti is an Object of type Dog. e.g. it
can have properties like name=Moti, Colour= Brown, Age= 3Years etc.
This is data about an object Moti. The set current values for any Object is called
State of an Object.
In programming: Objects interact i.e. communicate with each other by passing
messages using methods.

3. Methods (functions) :
Methods represent abilities of an object. These functions are defined and used with
same syntax as normal functions (discussed earlier chapters). A class Dog has
functions as discussed above. An entity of type class Dog will exhibit these
behaviours.

4. Message passing :
In OOP, the program consists of objects and these objects can perform their
functions if any other object requests. Objects communicate with each other by
Prepared by, Santosh Kabir.
26
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


passing messages. A sender object gives a request to an object the object processes
the request and produces some result. Messages are the functions (methods).
e.g. An object Raj of Person class can send message to object Moti for Running.

5. Data Abstraction:
Data abstraction stands for presenting information about the code (class in C++/
Java) without presenting details of implementation.
The member function names, their purpose and how to use them (i.e. call them) are
known to user (main() programmer) but exactly how function processes data and
works with other parts of class is not known to user of the function.
e.g. ChangingGear for a car object is known, but how really gear changes and for
that how the different parts of Car (object) work is unknown to driver i.e. user.
Data abstraction also provides programmer a feature of creating user defined data
types and increase the power of the programming language.

6. Encapsulation:
This is one of the important principles of Object-oriented Programming (OOP).
Encapsulation is the mechanism that binds together code (program segments) and
the data it manipulates, and keeps both safe from outside interference and misuse.
Thus it provides a protective wrapper that prevents the code and data from being
arbitrarily accessed by other code defined outside the wrapper.
In C++/Java we define class that consists of Data and Functions: the functions
commonly work with the data (i.e. data members) of the class. Thus, the class
provides a wrapper that encloses the data and the functionality defined for a
particular program unit. To avoid the misuse of the data we usually define the datamembers as private data members. The functions defined in the class provide
interface to access the data-members. The class-user (programmer) has to work with
the object of the class to call the functions. The program can consist of multiple welldefined classes that can work independently or they can work with each other using
a mechanism called message passing.

7. Polymorphism:
The word is a Greek word meaning One name many forms. Polymorphism in
C++/Java stands for one name (interface) providing multiple different actions. The
specific action will be decided by the exact nature of situation.
Programmer can define three functions to sort integer values, float values and string
values with same name but with different types of parameters. OOP compiler (here
Java compiler) will treat these three functions as three different functions and
invokes a particular function according to situation i.e. type of parameters. Called as
function Polymorphism. It is a Compile-time polymorphism.
( In Java compile time polymorphism is possible for final methods only )
It is also possible that the program, while run-time, can decide which function to
call, according to the actual object created.
In Java all the methods are called using Run-time polymorphism except for final methods. This
is also called as Dynamic method dispatch.
Even the multiple classes can have functions with same name. Thus, from the
objects of different classes, functions with the same name can be called. This is also
a type of polymorphism. Function calls are called as messages to the objects. This
Prepared by, Santosh Kabir.
27
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


ability of different objects to respond, each in its own way, to identical messages is
called polymorphism.
Note : ( A Short note on only Polymorphism is also a possible question)
In that case give short program examples of all the points covered. Draw following figure,
Polymorphism

Compile time poly.


( final methods )

Runtime Poly.
( all non-final methods )

8. Inheritance:
Its a mechanism that allows a class to inherit properties and functionalities from
another class. Here, the new class that inherits properties is called as a Sub class and
the old class is called as Super class. Inheritance enables programmer to reuse the
code of classes multiple times. A sub-class can add more functionality and/or
modify functionality of super class.
class A
x() and y() functions

class B ( derived class of A )


p() and q() functions

In above example class B has its own functions p() and q() and two more functions
x() and y() inherited from class A.

Working with Classes & Objects (Use of new ):


Defining a class :
Syntax :
We define class using Java keyword class and enclose the dat and methods for the
class in curly braces as follows,
class ClassName
{
Data Members
Imp : Class defines a data-type

( as structures in C )
Methods

}
e.g.
class Demo
{
int a;
// data memebr
void f( ) // method
{
System.out.println(this is method f);
}
}
Prepared by, Santosh Kabir.
28
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


In above example Demo is a class i.e. a Data type. To work with members of class we
need to create variable of the Demo type. ( variable of class type that holds members
of the classis called object of the class)

Object Creation :
Creating a class object stands for allocating a memory for the class instance. This is commonly done by
use of keyword new. The keyword allocates memory required for the class object and returns the
reference of the allocated memory.
This reference is nothing but the memory location where the data-block is created in memory.
The syntax for creating an object using new keyword is as follows,

Method 1 :
ClassName refVar ;
refVar = new ClassName( parameters ) ;
Here, refVar is a called as reference variable for an object of type class ClassName. First statement
declares only a reference variable, memory of object not allocated by this statement. The next

statement creates an (un-named) object of class ClassName and puts its reference in the
variable refVar. Now further access to the object is done by this reference variable. (This reference
variable name is treated as object name.)
Parameters part is not compulsory. The parameters are used to invoke a particular constructor of a
class. If parameters not mentioned a default constructor is works if it exists.

Method 2 :
We can combine the above two statements for object creation as follows,

ClassName refVar = new ClassName( parameters ) ;


Here, declaration of a reference variable and object creation is done in the same statement. new
creates an object and puts its reference in the refVar.
Consider example of a Demo class that has one int data-member and a method f(). i.e.there are
two members of the class.
The variable aa defined in the class body are the instance variables of the class.

A new copy of these variables is created whenever a new object of the class is created. These
variables are accessible in all the methods of the class.

Accessing members of a class :


Memebrs of a class are accessed using object name as follows,
ObjectName.MemberName
In this case variable a declared in the class is accessible to all the methods of the class.
Also, since it is present in the object of the class, its life-time is till the object exists in memory.
The variables declared in the body of methods are called as Local variables of the methods, and these
variables have scope and access only inside the methods in which they are declared. method are
called local variables of those methods. Local variables are accessible only inside the method in which
they are declared and they are cleaned from memory when method terminates (i.e. returns).

Multiple methods of the same class can have local variables with same name.
If an instance variable (any variable declared in class) and the local variables have same name then a

method, by default accesses a local variable.


Prepared by, Santosh Kabir.
29
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


By default all the members are accessible outside the class in the same package (or i.e. programs in
the same folder). (Packages are discussed in details in later chapters)
The following class can be added to the same program with main() method.

class Test
{
public static void main(String[ ] args)
{
int x=5, y=2;
Demo n = new Demo(); // object creation
n.a = x;
n.f();
n.a += y;
System.out.println("value=" + n.a );
}
}

Using members of Demo class

The main() method creates objects of a class and invokes methods on it.

Parameter Passing :
Passing Parameters by Value:

The parameters of primitive data-type are passed to methods by Value in Java.


That is, the values of the parameters (variables) are passed from the calling
method to the called method. Here, Java copies the value of an argument into
the formal parameter of the subroutine (method). Formal parameters are the
new variables created in the method and have no relation with the calling
method variables.
Therefore, changes made to the parameter of the method have no effect on the
argument. i.e. any modifications made in the values of the method variables
by the method, will not be reflected in the variables of the invoking method.
Consider a following method that has two integers as paramters. i.e. parameters will
be passed by values.
void swap(int x, int y)
{
int t = x;
x = y;
y = t;
System.out.println("In swap :x=" + x + "..y=" + y);
}
If the above method is called from some other method as follows,
void pqr()
{
int a =10; b=7;
System.out.println("before swap :a=" + a + "..b=" + b);
swap( a, b ); //paramters passed by value
System.out.println("after swap :a=" + a + "..b=" + b);
}
Prepared by, Santosh Kabir.
30
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


The output will be,
before swap :a=10 ..b=7
In swap :x=7 ..y=10
after swap :a=10 ..b=7
In above example, the values of actual parameters, a and b are passed to formal
parameters x, y of the swap() method. x and y are the new variables of swap() method
and they have no relation with a and b. The changes made by the swap() method in
x, y are not reflected in a and b, after method call.

Passing Parameter by Reference:

The object data-types and arrays are passed by Reference in Java.


When an object variable is passed as parameter to a method, the reference stored
in the argument is passed from calling method into the parameter of the method.
Hence, the parameter in the method refers to the object in the calling method.
Thus, any operation performed on the method parameter by the method
statements will be done on the object in the calling method, also if any changes
are made , they will be done on the original object in the calling method.
Consider following example,
class ABC
{
int a=12, b=5;
void display()
{
System.out.println(a= + a + b= + b);
}
}
Assume a method that has ABC class object as parameter. The method swaps values
in the object passed as parameter,
void swap( ABC r ) // r refers to object y of xy() method
{
int t = r.a;
r.a = r.b;
r.b = t;
System.out.println("In swap :a + r.a + b= + r.b);
}
If the above method is called in a following way then,
void xy()
{
ABC y = new ABC();
// in the object a=12 and b is 5
System.out.println("before swap :);
y.display();
swap( y );
//parameter passed by reference, since y is reference var.
System.out.println("after swap :);
y.display();
}
Prepared by, Santosh Kabir.
31
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


Output will be,
Before swap:
A=12 b= 5
In swap :a=5 .. b=12
After swap :
A=5 .. b=12
In above example when a method swap() is called, the reference in y variable passed
into method variable r. Thus, r refers to the same object created by xy().

Method Overloading:

Java class can consist of multiple methods with the same name but different
type of parameters or different number of parameters. Such methods are
called Overloaded methods. This feature of Java is called as Method
overloading.
This is a feature of OOP called Polymorphism. This, allows defining multiple
methods with same name in the same scope (here, same class). But the
methods are differentiated by their parameters.
Overloaded Methods can have any combination of data-types, but each
combination should be unique. This unique definition of each method is also
called Signature of a method.
e.g. int add(int a, int b) , float add(float a, float b), long add( long a, int b), and
int add(int a, int b, int c) are all treated as different methods. These
definitions are called Signatures.
A Java class cant have methods with same name and signatures.
e.g. In the following example class Test consiststs of two methods with name add(),
one of them with two int parameters and another with two float parameters.
class Test
{
void add(int a, int b)
{
int r = a+b;
System.out.println("add with ints: sum=" + r );
}
void add(float a, float b)
{
float r = a+b;
System.out.println("add with floats: sum=" + r);
}
}
The methods can be called from main() as follows,
class A
{
public static void main(String[ ]args)
{
Prepared by, Santosh Kabir.
32
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


long m=10, n=20;
float x=1.5f, y =2.5f;
Test a = new Test();
a.add( 10, 20);
a.add( x, y);
a.add( m, n);

calls add() with int param.


calls add() with float param
calls add() with float param

}
}
Output:
add with ints: sum =30
add with floats: sum =4.0
add with floats: sum = 30.0
Since Java is a strictly typed language while calling overloaded method, proper care
must be taken by a programmer to call right method at write place.
When an overloaded method is called, Java looks for a match between the
arguments used to call the method and the method parameters.
However, this match may not be exact. If exact match is not found then Java
can use its automatic type conversions and invoke a particular method with
the compatible parameters. In above case since a method with long type
parameters is not present a method with float parameters is called.
If there is no method present with exact or compatible types of parameters
then Java will generate a compiler error.
The methods are Not differentiated with their return types.
If a super class and sub class have same named methods with different
parameters, then in the object of sub class again overloading takes place since
the method in super class is inherited into sub class, and they have same
name but different parameters.
Advantage : Since methods for similar purpose are defined with same name, user of
the class do not need to remember multiple method names.
e.g. In Java there are multiple versions of println() (i.e. it is overloaded) for displaying String, int, Object
etc. Programmer need to know only one method name prinltn.

Constructor :
In Java program whenever class object is created, the variables defined in class (data-members i.e.
properties) are initialized to their default initial values, if not explicitly initialized. Constructor of a class is
a method of the class whose main task is to initialize properties of a class to some user defined

value or some required values programmatically.

Constructor is a method of class with the same name as class-name.


It is invoked automatically whenever object of class is created with a memory
allocation operator new
Initializing class data-members is commonly done using constructor method.

Prepared by, Santosh Kabir.


33
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )

Constructors should Not have return type, i.e. constructor never return value.
Since a constructor is a method, it can have parameters and can be overloaded
like a normal method of a class.
A constructor without parameter is called as Default constructor.
A constructor with parameters is called as Parameterized constructor.
Defining multiple constructors for a class is called Constructor overloading.
A particular constructor of a class is invoked by mentioning arguments of
required types, when objects of a class are created.
Only one constructor of a class is invoked at a time when object of the class is
created.
If constructors (one or more) are defined for a class, then object of the class
must be created using one of the constructors, else compiler error occurs.

Example,
class MyClass
{
int a, b;
MyClass( ) // default constructor
{
System.out.println("Def. constr");
}
MyClass(int x, int y)
// parameterized constructor
{
System.out.println("Two param. constr");
a=x; b=y;
}
void showValues( ) // Methods
{
System.out.println("a=" +a +"..b=" + b);
}
void setValues(int x, int y)
{
a = x; b=y;
}
}
class ConstrTest
{
public static void main(String[ ]args)
{
MyClass m = new MyClass( );
m.showValues( );
MyClass n = new MyClass(10, 20);
n.showValues( );
n.setValues(35, 50);
n.showValues( );
//MyClass m = new MyClass( 10 );
}
}

// default constr. invoked


//parameterized constr. invoked

//Error : no such constr.

Prepared by, Santosh Kabir.


34
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


Output:
Def. constr
a=0..b=0
Two param. constr
a=10..b=20
a=35..b=50

Static members of a class :

A method or a data-member of a class can be defined with a keyword, static.


Static member (method/data-member) is accessible outside the class, without
creating an object of a class. (Provided its access mode permits the access)
To access these static members one can use just a class-name as follows,
ClassName.MemebrName -- for data-member
ClassName.MethodName( Argumens ) -- for methods

Static method:

A static method can access Only other static members of the (current) class.
i.e. it can only operate on the static data-members or call static methods in
the same class.
Using an object it can access any member of the same or different class.
They cannot refer to this or super keywords.

Static data-members:

Static data-members of a class are created in memory when the class is


accessed for the first time. They are created even before first object of a class
is created.
Also, there is only one copy of these variables created, which is referred by all
the objects of the class. Thus, these variables are shared between multiple objects
of the class.
Local variables of methods Can Not be declared static.
To initialize these variables to some required values, commonly a static block
is used. (next sub-topic)
Static variables of a class are called Class Variables.

(Non-static members are called Instance Members. As used in some examples in previous topics )

Static blocks:
A class can consist of a static block that encloses some statements using a keyword
static. The syntax is as follows,
static
{
// some statements.
}
The static block executes when class is accessed for the first time.
The block works automatically before any other method or even a constructor
is called. For further access to the class the block never works.
It is used to initialize static variables of the class if required.
Prepared by, Santosh Kabir.
35
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )

There can be multiple static blocks in a class, they execute from top to bottom
(only once and before any other method of the class works).

Even though static methods cant directly access non-static members of the class,
non-static methods can access static members directly.
[ Give example if question is asked for more than 6 marks ]
class Test
{
static int A; // static i.e. class variable
int b;
// non-static i.e. Instance variable
static
//static block
{
System.out.println("Static block : of Test");
}
Test()
{
A++;
b+=a;
System.out.println("Test constr.");
}
static void xy() // static method
{
A+=10;
//b+=2; //error: non-static var. not accessible through static
System.out.println("in xy A=" + A);
}
void show() //non-static method can access static members
{
System.out.println("show of Test: A=" +A + "..b=" + b);
}
}
class StaticUse
{
public static void main(String[]args)
{
Test.A = 10;........................................................... 1
Test y = new Test(); ............................................. 2
y.show(); ................................................................ 3
Test z = new Test(); .............................................. 4
z.show(); ................................................................ 5
Test.xy(); ............................................................... 6
z.show(); ................................................................ 7
System.out.println(A=+ Test.A ); ...................... 8
}
}

Prepared by, Santosh Kabir.


36
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


Output:
Static block : of Test
Test constr.
show of Test: a=11..b=11
Test constr.
show of Test :a=12 b=12
in xy A=22
show of Test: a=12..b=22
A=22

The this keyword :


In some cases it is required that the method of a class has to refer to the object on
which it is invoked. To allow operation with the current object, Java defines a
keyword this.
this is a keyword of Java. It works like a reference variable for a current object in
which it is used.
It is used to refer to data-members and methods of the object in specific
cases. ( but it cant access local variables of memthods)
The keyword is only available inside the body of the non-static methods and
constructors.
Some times it is used to specifically mention that your program has to access
current object.
Consider following example,
class Demo
{
int y ;
Demo ( int x, int y )
{
this.y = x + y;
}
void showValues()
{
System.out.println("y=" + y );
System.out.println("Sum="+ this.add(5) ); //use of this not required here
// System.out.println("Sum=" + add(5) );
//same as above
}
int add(int a)
{
int r = y+ a; // OR int r =this.y + a;
return r;
}
}
Then the statements,
Demo n = new Demo ( 3, 4 );
Prepared by, Santosh Kabir.
37
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


n.showValues();
will display,
y=7
sum=12
Since, the name of one of the the parameters (i.e. y) and the variable names in the
class are same, we mention this keyword to specify that the variables to be
assigned are from current object.
The statement, this.y = y;
Stands for assign value of the local variable y of the method, to the variable y in the
current object (i.e. variable in the class). Although this is available in every method,
Local variables of method cannot be referred using this.
Every object that is created has its own this in it, which can be used to refer to that
object from the method invoked on it. In the above example add() is called from
current object using this keyword. Although use of this is redundant here, since
any method of a class calls other method from current object by default.

Garbage Collection utility : ( Garbage Collector in Java)


In Java programs, memory for objects (and arrays, since arrays are objects) is allocated using new
operator. Reference variables are used to hold the reference of the object created in this manner. Java
provides new keyword for memory allocation but no statement (like free() in C or delete in C++) to

release unwanted objects from memory.


Java provides a built-in mechanism for memory management. This is called
as Garbage collection.
For removing objects from memory (when not needed), Java has a mechanism
to de-allocate the memory automatically. i.e. programmer need not write special
code to release the memory occupied by the un-used objects.
This is done by Garbage Collector utility which is part of JVM.
When there is no reference left for an object, that object is assumed to be no
longer needed. The object becomes a candidate for garbage collection. The
memory occupied by the object can be reclaimed. i.e. Whenever any object
doesnt have any reference left, the memory for the object is released by JVM i.e. the
object is cleaned from memory. This mechanism by which Java deallocates
memory automatically is called as Garbage collection.
There are three situations where object will not have any reference left. In the
first case, if the object goes out of scope. This will commonly occur when a
method that creates an object returns, the reference variable for the object is
cleaned and object will not have any reference, and it will be garbage
collected. Second if a reference variable referring an object, is assigned a
reference for some other object, it will be left with no reference and will be
garbage collected. The third case is, if a reference variable of an object is set to
null, the object will be garbage collected.
Following program demonstrate when an object will be left without any reference,

Prepared by, Santosh Kabir.


38
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


class Test
{
// some data-members and methods
}
class A
{
static void method1()
{
Test m = new Test();
// some statements
m = null;
// var. m is set to null value, object can be garbage collected

// some statements
}
public static void main(String[] args)
{
Test x = new Test();
Test y = new Test();
// x refers to the object referred by y, the object referred by x has no reference left, thus that
//object will be garbage collected.

x = y;
//... some statements
y = null; // reference in y is set to null but the object is still referred by var. x
// var. x and y go out of scope, when the main returns, objects will be destroyed

}
}
Garbage collection occurs sporadically (if at all) during program execution. Different JVM
(Java Run-time Environments) can take different approach for garbage collection.
Java provides a method gc() that is in System class. Programmer can invoke this
method as System.gc() to run garbage collector utility.

The finalize( ) Method:


User can add (i.e. define) this method in his class for finalization task to be
performed before memory for the object is de-allocated.
An object is removed from memory when it is no more needed by the program.
Sometimes, it is needed that an object has to perform some specific actions when it
is removed (i.e. garbage collected).
For example, an object can be holding some external resources like a file handle or network
connections. Here it must be made sure that these resources must be released (or closed) before the
object is destroyed.

To handle such situations Java provides a mechanism called finalization. By using


finalization, one can define specific actions that will occur when an object is just
about to be reclaimed by the garbage collector.
To add the finalization code to a class, we can define the finalize() method.
The Java run-time calls that method whenever it is about recycle an object of the
class (with its garbage collection utility). In finalize() method one has to write the
code that will take actions to release the resources used by the object.
Prepared by, Santosh Kabir.
39
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


The method is defined in a class in the following way,
protected void finalize()
{
// some statements
}
finalize() is called just prior to garbage collection. Since one can not predict or make
sure when a garbage collection will take place in the life-time of a program,
programmer can not rely on finalize() method to perform finalization task.
Programmer can invoke a method gc() on System class, to suggest the Java run-time
to try an clean any unused objects left in the memory and free the memory for reuse.
The finalize() methods of corresponding objects are invoked.
The method is called as follows,
System.gc();
[ If any of the two topics (garbage collection/finalize() ) is asked for more than 6 marks write answers for
both together ].

Prepared by, Santosh Kabir.


40
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )

The Booch Method for OOD :


Booch method was published in 1991 by Grady Booch, is a widely used method in
Software Engineering field for object-oriented analysis and design.
It is an Object-oriented Software development method used to analyse, model and
document system requirements.
Successful project should satisfy all the requirements of a customer. For this
purpose a good design, creativity and innovation is required. The Booch method
supports this.
The method uses some robust Notations that are used in all the phases : from
Analysis to Design. The notations are used for classes, association, aggregation,
Containment indicators, adornments etc.
The Booch method includes six types of diagrams such as class diagrams, object
diagrams, state transition diagrams, module diagrams, process diagrams and
interaction diagrams.
The Booch method notation

Figure 1. A class diagram notation.

Figure 2. A object diagram notation.


The dynamic nature of an application can be illustrated by state transition and
interaction diagrams.

Prepared by, Santosh Kabir.


41
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )

Figure 3. An interaction diagram.


There are several Booch diagrams that are very similar to diagrams in UML. These
Booch diagrams are state transition and interaction diagrams. The State transition
diagram corresponds to UML's statechart diagram and the interaction diagram
corresponds to UML's sequence diagram.
More information

Supports Iterative and Incremental approach :


Its assumed that all the requirements are not known to developers at the beginning
of life-cycle of project. Changes and risks are anticipated in every phrase of
development and the highest risks are tackled first. The result of this type of lifecycle is less risk and minimum cost.
The control for the iterative life-cycle is described by Booch using a Macro and Micro
process.

Details :

Macro-Process :
It is a high level process describing the activities of development team as a whole. It
approaches the developing process from managers point of view.
( Refer the figure given below )
Phase 1: The outcome of the first phase is to establish core requirements of the
system.
Phase 2: Capturing and understanding complete and consistent set of system
requirements is done here. The phase finds out what are the parts of problems but
not how to solve them. All the things are thought from user point of view and not
developers point of view.
Phase 3: Physical and logical architecture of software is constructed in this phase.
Phase 4: Here the executable releases of the system developed. Micro process is
applied to each release of the system for refinement. This is the longest phase in the
life cycle of project development. E.g. if entire project development lif cycle is one
year then this phase may take eight to nine months.
Prepared by, Santosh Kabir.
42
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


Phase 5: This is a maintenance phase where main activity is managing the post
delivery evolution of the system.
Conceptualization

Analysis

Design
Maintenance

Evolution

Micro-process:
This a low level process that represents the technical activities of the technical team.
The phases in the process are shown below.
The first step is Identifying classes and Objects. The classes to developed for the
software are identified and documented.
In the second phase class semantics are refined. The attributes and operations are
planned. Documentation is updated to include additional information obtained
during this phase.
The relationships between the classes is identified in the next phase. e.g. has a,
uses etc. relations between classes are identified.
In the next phase the data-types for attributes, signature of operations is added to
classes. The algorithms for the operations is decided.
In each phase of micro process, new classes may be added or existing classes may
be modified to mature the architecture of current release.
Identifying classes
and Objects

Identifying class and


Object Semantics

Specify class and


object interfaces and
implementation

Identifying class and


Object Relationships

Prepared by, Santosh Kabir.


43
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )

Quality of OO Design ( Quality of Abstraction ) :


It is desirable that a
1. System should be built with minimum number of unchangeable parts
2. Those parts should be as general as possible.
3. All the parts should be held in some uniform framework ( in case of OOP and
Java its in the form of classes and objects)
OO design is a iterative and incremental process. All the parts of the system can not
be designed smoothly at the beginning. To try and design more better design which
will as close as correct and final design we following merits are suggested :
1. Coupling
2. Cohesion
3. sufficiency
4. Completeness
5. Primitiveness

Coupling :
It is a measure of strength of association between different modules ( or classes).
Stronger the coupling makes system complicated. This is because, strongly coupled
classes are harder to understand, difficult to change or correct by it self.
Loosely coupled classes (modules) are expected.
-----If class A interacts with class B only through it API ( methods) i.e. interface, then the
classes are loosely coupled. In this case if any algorithm of method ( i.e. noninterface part ) is changed in class A, the class B wont break (stop functioning).
Types : (from strongest to loose coupling)
Content coupling : If one references contents of the other
Common coupling : Both the classes use some common global data.
Control coupling : Passing data (or flags) from one module to the other so that one
can controls sequence of processing steps in another module.
Data Coupling : Uses parameters to pass data between to routines.
Even though coupling is undesirable, Inheritance tightly couples classes for
reusability. It also exploits commonality between abstraction.

Cohesion :
It is a measure of degree of connectivity between different elements of same module (
i.e. class ). i.e. how different elements of a module fit together.
It is expected that a module implements a single entity or concept. All the elements
of the modules contribute to the implementation.
Different levels of cohesion are possible,
The most desirable is Functional cohesion. In this all the elements of the module
contribute towards one, well bundled behaviour. e.g. a class Account should have all
elements working for Account only and nothing else.
The worst is Coincidental cohesion, in which entirely unrelated elements are put
together into one module.
The other types of cohesions are Logical, Procedural, Sequential, Communicational
etc.
Prepared by, Santosh Kabir.
44
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


Sufficiency :
A class or module is sufficient if it captures enough characteristics of the abstraction
that will permit meaningful and efficient interaction. E.g. while building a class for
List one has have operations to add and remove elements from the List.

Completeness :
A module or a class is complete if it considers all the meaningful characteristics of
the abstraction. Usually a complete module is general enough to be useful for any
client.

Primitiveness :
The operations in the class must be primitive. i.e. the operations should operate with
state of the class ( data members). E.g. Add operation of List class can add one item
to the list implementation in the class. But, operation that adds n items to the list is
non primitive because it can be implemented by using a more primitive operation
Add. i.e. if a method can be written in terms of the other then it is not primitive.
Primitive classes are small, easy to understand, less coupling between other
methods. They are very easily re-usable.

Meta-class :
In object-oriented programming, a metaclass is a class whose instances are classes.
Just as an ordinary class defines the behavior of certain objects, a metaclass defines
the behavior of certain classes and their instances.
Thus, Meta-class is a class of a class. Hence, instance of a Meta-class is a class. The
languages such CLOS, SmallTalk support Metaclasses.
In SmallTalk the meta-class is used to define variables that are shared between all
the instances of the class and to initialize the class variables.
C++, Java language do not support meta-classes directly. But, one can use the
features such as constructor and destructors(in C++) for this purpose. Also, static
methods and variables can be used to share data between all the instances of the
class.

State of an Object :
State of an object represents cumulative results of its behaviour.
e.g. a telephone when installed is in idle state. When some picks-up receiver and
dials a number it is in calling state etc.
At any given point in time, the state of an object encompasses all of its (usually
static)
properties, together with the current (usually dynamic) values of each of these
properties. By properties, we mean the totality of the object's attributes and
relationships with other objects.
e.g. an object of Account class will be in initialized state with some values of
attributes e.g. Name=John, Amount=10000, email=john@xyz.com, Address=10,Abc
street, NY. Now it is ready to operate. Suppose a deposit of 2500 is done in the
Prepared by, Santosh Kabir.
45
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )


account object and the address of the account holder is modified to 12,PQR street,
NY. State of the account object is changed. The current collection values for the
account object is its current state.

Operations :
Operation denotes a service that a class offers to the client. i.e. a method that is
offered by a class to class user.
There are three main operations as follows:
Selector : The operation that accesses the state of an object without modifying it. i.e.
the operations that reads value of data but does not change it. E.g. a method that
returns value of a private variable in an object.

Modifier : Its an operation that changes state of an object. E.g. a method that
operates on data in object and modifies the data.

Iterator : An operation that allows to access all parts of an object in some formatted
order. E.g. an operation that goes through all the items in the collection for a List
class.
=============

-----0000-----

Sem IV - IT

Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]

( Learn to design and develop small Internet based programs )

Regular batches at Andheri, Thane.

By Santosh Kabir sir.


Mobile : 98336 29398
Visit : www.santoshkabirsir.com for batch schedule and other info.
Prepared by, Santosh Kabir.
46
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

3. OOP Concepts in Java

OOPM ( Sem III Comp / IT )

4. Inheritance

Its a feture of OOP by virtue of which an object can aquire (inherit) some or
all the members of another object ( or a class).
Inheritance is one of the important features of OOP, by which we can define a
new class using pre-existing class, and the new class works like extension of
old (i.e. pre-existing) class.
Thus, it provides re-usability of a code.
The new class has its own features plus the features inherited form the preexisting class. This process is called inheritance or extending class.
In Java a new class is defined using following general syntax,
class Class1 extends Class2
{
// Member definitions and declarations
}
As the above syntax specifies the keyword extends is used to define a new
class from pre-existing class. Here, the Class1 is called as Sub-class of
Class2. Also, Class2 is called as Super-class of the Class1.
Whenever a class (say B) extends any other class (say A) all the members of
class A (except for private members and constructors ) are inherited into the
this new class B and they are accessible in this sub-class B, as if they are
members of the B class.

e.g.
class A
{
int x=5, y=10;
void show()
{
System.out.println("In show x=" +x + "..y="+y);
}
}
class B extends A
{
int m=15;
int add()
{
int r = m + x + y;
//data-members of super-class can be used
return r;
}
void abc()
{
show();
// method from super-class ClassA can be called
System.out.println("In abc m=" +m);
}
}
Prepared by, Santosh Kabir.
47
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


Class A consists of two data members and a method show(). Class B is a sub-class of
Class A, hence it inherits properties and methods of its super-class. Class B can
access all the members of its base class as if they are present in its own definition.
Now, when we are working with these classes, we need not work with Class A since it is extended by
Class B. One can just create object of class B and use features of both the classes.
Here, the members (public, protected and default type) of a class are inherited into its subclass with the
same access control. e.g. a protected member of a class is accessible to the subclass and is inherited
as a protected member.

The class A is independent class, if we work with A only, then Class B features are
not available. i.e. super class is indepenedent of its sub-class.
Following code with main() shows the working of inheritance.
class Inhrt1
{
public static void main(String[ ] args)
{
B obj1 = new B();
obj1.show();
int a = obj1.add();
System.out.println("a=" +a );
obj1.abc();
}
}
Output:
In show x=5..y=10
a=30
In show x=5..y=10
In abc m=15
Static method defined in sub-class cannot access non-static method from super-class.
i.e. following method if defined in ClassB, will generate compiler error,

static void aa()


{
//show() ; // Error not accessible
}
This, is because the members of super-class are inherited into sub-class, and are treated as its own
members. And according to rules, a static method cannot access non-static members of the same class
directly.

Prepared by, Prof. Santosh Kabir.


48
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )

Types of Inheritances (using classes)


Depending upon the way classes and their sub-classes are related to each other, there are three
different types of inheritances possible in Java using classes.

Inheritance is a feature of OOP, using which one object can inherit some or all
members of other object. The class that inherits members of other class is
called as Sub-class. And the class from which members are inherited is called
as Super-class.
While defining a sub class, a keyword extends is used to mention the super
class name, as shown in following syntax,
class class_name extends other_class_name
{ // class members
}
Except for private members all the members (i.e. public, protected, and
default access) of super class are inherited into sub class with same access
mode, and they can be then treated as members of sub-class also.
Depending upon the way classes and their sub-classes are related to each other,
there are three different types of inheritances possible in Java using classes.

1) Single inheritance:
When a class is derived from single super class, it is called as single inheritance.
e.g.
class A
{
class B extends A
private in b;
{
A
void x()
int m;
{ // some statements
void pq()
}
{ // some statements
B
public void y()
}
{ // some statements
}
}
}
In above example, class B is a sub-class of class A, and it inherits methods
x() and y() from class A. Thus, the object of class B, will have data-members m and
methods x(), y() and pq().
Data member b of class A will not be inherited into B since it is private.
If in both the classes there are methods with same signature then class B
methods (with same signatures) will override those methods from A.

2) Multilevel Inheritance:

In this there are multiple levels of inheritance. e.g. one class C is derived from
class B, and in turn the class B is derived from class A.
Class A is immediate super-class of B and indirect super-class of C. But yet,
here, A is treated as super-class of both classes B and C. Also, class C is
treated as sub-class of B and A.

Prepared by, Prof. Santosh Kabir.


49
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


e.g. We can define a new class from class B (of previous example),
class C extends B
A
{
// some members
}

Here, C is direct sub-class of B. All members of class B ( i.e. its own members,
and members inherited from class A) will be inherited into class C.
Again, if class C has any method with same signature as that in A or B, it will
override same method from A and B.

3) Hierarchical inheritance :
In this type, there is one super-class at the top of hierarchy. From this class multiple
sub-classes are defined. Again from each of these sub-classes one or more subclasses can be defined to form a hierarchy of classes.
A class hierarchy can be as shown below.

The top class (here class A) , is called as super-class of all the classes in the
hierarchy. B is super class of X and Y. Also, it is sub class of A and so on.
Every, class has single direct super class.
This type also follows the working of single and multilevel inheritance for
inheriting the members and method overriding.

Super-class and Sub-class Relationship:


A sub-class is always of type its super-class. Actually, all the sub-classes are of type super-class. In
above examples, Class B is of type Class A or simply we say that Class B is a Class A.

A Reference variable of a super-class can refer to the object of any sub-class. i.e. (refer to
previous example) we can write following for Class A and Class B.

A r;
r = new B();
Or r = new B(25, 35);
Prepared by, Prof. Santosh Kabir.
50
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


The first statement declares a reference variable r for object of type Class A. The second statement is
valid, since the Class B is of type Class A, the reference variable for type Class A can refer to object of
its sub-class objects.
Here, the reference variable decides what members can be accessed, and not the object that it refers
to. That is, when a reference to a subclass object is assigned to a superclass reference variable, you
will have access only to those parts of the object defined by the superclass. ( discussed in later topics in
details )

Method Overriding :
: When a method in a sub-class has same name and type-signature as that in
:
super-class then the method in the subclass is said to override the method in
the superclass.
When an such a method is called from within an object of a subclass, it will always refer
to the version of that method defined by the subclass. The version of the method
defined by the superclass will be hidden.
The feature is used to define new version of method in a sub-class.
See the following example in which class A and its sub-class B have same method
name and type signature.
class A
{
void xy( )
{
System.out.println("A .. xy");
}
void ab( int a )
{
System.out.println("A .. ab method a=" + a);
}
}
class B extends A
{
void ab( int b ) // overrides ab( ) of A
{
System.out.println("B .. ab method b=" + b);
}
}
class Test
{
public static void main(String[ ]args)
{
B a = new B( );
a.xy( );
a.ab(10);
}
}
Method with name ab() is re-defined in the sub-class, hence when the method is
invoked from B object its own method works.
Prepared by, Prof. Santosh Kabir.
51
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


Output:
A .. xy
B .. ab method b=10
Overriding occurs only if the two methods have same name and same signature
(same parameters and return type). If they are not, then the two methods work like
overloaded methods.
e.g. If a class B (or class A) consists of following method, then this will achieve
method overloading and Not overriding.
void ab(int a, int b)
{
// some statements
}
If only return types of two methods are different neither Overriding nor
Overloading will work and its a compiler error.
We can call overridden method of a super class from sub-class method using
keyword super. In above example method ab() of sub-class B can be defined
as follows,
void ab(int b)
{
System.out.println("B .. ab method b=" + b);
super.ab( b+5 ); //invokes ab() of super class A
}
Dynamic method dispatch : All the method calls in Java (except final methods)
are late bound. i.e. from which class (i.e. object) method should be called is
postponed till run-time. Java compiler doesnt decide from which object a
method will be invoked.
In above example, if object is created using super-class reference variable,
A r = new B( ); // Object of sub-class and ref. var. for super class
Then the method calls,
r.ab(10);
r.xy( );
are decided at run-time.
1. if object of A class was created, ab() of A will work
2. if object of B class is created, ab() of B will work

Keyword super :
1. As a suer class object :

The keyword works as a reference variable for the super class object of the current
class.
It is used to refer to the members (i.e. methods and data-members) of a superclass with following syntax,
super.member
for data member and
super.MethodName(arguments)
for method.
Static methods Can Not use super to access super class members.
Using super keyword one Can access static members of super-class.

Prepared by, Prof. Santosh Kabir.


52
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


2. As super class constructor :

The keyword can be used to invoke a particular constructor of super class from the
constructors of this class.
Syntax:
super( parameters );
If super(parameters) is not used, the default constructor of super class is
invoked.
Call to super class constructor (if mentioned) must be the first statement in the
sub-class constructor. Other wise its a compiler error.

e.g.
class A
{
A( ) // default constructor
{
System.out.println("A .. Default");
}
A(int p) // parameterized constructor
{
System.out.println("A .. paramtr.");
}
void ab(int a)
{
System.out.println("A .. ab method a=" + a);
}
}
class B extends A
{
B() // default constructor
{
super( 10 ); . . . [a]
System.out.println("B .. Default");
}
void ab(int b)
{
System.out.println("B .. ab method b=" + b);
super.ab( b+ 5);
}
}
Consider following statements
B r = new B();
r.ab(10 );
The two statements will generate following output,
A .. paramtr
B .. default
B .. ab method b = 10
A .. ab method a = 15
If statement [a] was not present then, the default constructor of A will work.
Prepared by, Prof. Santosh Kabir.
53
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


Keyword final :
1) final variables (defining constants) :

A variable ( static or non-static ) in a class can be declared with a keyword


final. Final varibale must be initialized to some value where it is declared.
Once a variable is declared final, its value cant be changed further in a program.
An attempt to change value of the variable generates compiler error.
General syntax is:
[ AccessMode ] [ static ] final type name = value;
Here, access is any of the four possible in Java. Variable can be static or non-static.
e.g. public final double Pi = 3.14;
Now the variable Pi can be accessed in a program like a normal variable, only its
value cannot be changed. We can use it evaluate area of circle,
a = Pi * r * r;

2) final methods:
A method declared with a final keyword in a class, cannot be overridden further

in any sub-class. Thus, when the keyword is attached to a method, we are


declaring that its a final version of the method, and no subclass can make a
new version of it (i.e. override it).
The general syntax is,
[AccessMode] [static] final Return_Type Method_Name( parameters )
{
// statements
}
hus, using final we are preventing overriding. Normally, Java resolves calls to the
methods dynamically, at runtime. Since, a final method cannot be overridden a
call to final method is resolved compile-time. This is called as Ealy Binding.
The method declared final can override a method in its super-class.

3) final classes:

Sometimes it is required that the class should not be inherited into other
class. To prevent further inheritance of any class, a class can be declared
final.
The class itself may be sub-class of another class.
Syntax:
final class ClassName
{
// Members
}
Thus, final class Can Not have a sub-class. Obviously, the methods in the final
class will be automatically treated as final methods.
An abstract class cannot be declared final.

Prepared by, Prof. Santosh Kabir.


54
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )

Abstract Methods & Abstract Classes :


These classes are used to declare certain type of behaviour (class methods), without providing the actual
implementation for the behaviour. The class usually declares the methods to be implemented by its sub-classes.

Abstract method:

A method is declared as abstract by attaching a keyword abstract before the


method declaration, as shown in following syntax,
[AccessMode] abstract return_type name (argument_list) ;
Abstract methods are only declared i.e. they dont have method body.
If a class has at least one abstract method declaration then the class must be
defined as an abstract class.
The methods declared abstract in a class must be defined in the sub-class ( if the
sub-class should be a concrete class )
Abstract method can Not be final or private.

Abstract class:
These classes are used to declare certain type of behaviour (class methods), without providing the actual
implementation for the behaviour. The class usually declares the methods to be implemented by its sub-classes.
Abstract class just provides a base to define new classes which will have same
methods, implemented by the sub-classes in their own way.
A class is defined as an abstract class, using a keyword abstract in front of
class keyword in class definition.
The class can consists of data members, constructors, normal methods and
abstract methods as shown below,
abstract class Class_name
{
// data members
// abstract method declarations
// other methods & constructors

Object of an abstract class cannot be created. (i.e. Abstract class cant be


instantiated). But we can declare an object variable for the class.
All the abstract methods in an abstract class must be re-defined in its sub-class.
If not defined the sub-class must be declared as abstract.
Abstract class cannot be instantiated explicitly ( object cannot be created
using new ) but its object may be created though its subclass object implicitly,
and even the constructor will be invoked.
Following example program defines an abstract (super) class Base. The class defines
abstract methods. A class Sub is inherited from it and it defines (implements) all the
abstract methods of Base class.

Prepared by, Prof. Santosh Kabir.


55
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


abstract class Base
{
Base( )
{
System.out.println("in base-constr");
}
// if declared public here, must be public in sub-class

abstract void abc( int a );


public abstract void pqr ( );
void show( ) //non-abstract or concrete method
{
System.out.println("in base-show");
}
}
class Sub extends Base
{
// all the abstract methods in the Base class must be overridden here

Sub( )
{
System.out.println("in sub-constr");
}
void abc(int a)
{
System.out.println("in sub- abc");
}
// Since public in super class, must be public in sub-class

public void pqr()


{
System.out.println("in sub- pqr");
}
}
class AbstrsctTest
{
public static void main(String [ ]args)
{
//Base s = new Base(); // Base is abstract class can't be instantiated
Base r = new Sub();
// or Sub r = new Sub();
r.abc(10);
r.show();
r.pqr();
}
}
Output:
in base-constr
in sub-constr
in sub-abc
in base-show
in sub- pqr
Prepared by, Prof. Santosh Kabir.
56
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )

Access Specifiers (Visibility Modes /

Access Control )

Classes encapsulate the data-members and methods defined inside them. According general conventions of OOP,
the implementations of the methods and the data-members should remain hidden inside the class body, by default.
The class programmer can control the access to the members of the class. The users of the class can access only
those members which the class-programmers allows.
There are four levels of access control in Java, one of them is default (also called as
friendly access.) Java defines three keywords to specify the access control for the
members of the class as well as for the class it-self. These are: private, protected
and public.
One of these keywords can be written before any member declaration or definition.
e.g
class SomeClass
{
private int sum;
public void x()
{
}
.. //other members
}
In above example the data-member sum, of the class SomeClass is declared as
private member of the class and the method as public member. Following points
discuss the use and working of these keywords.

private :

Private members of a class are accessible only inside the class. i.e. these
members can be accessed only by the other members of the same class.
Classes cannot be private, but inner classes can be declared private.
Private members are not accessible out of the class anywhere as well as not
accessible to the sub-classes i.e. private members of class are not inherited
into sub-classes.
Usually the data-members of a class are kept private. Some times, methods
are declared private, if these methods are to be used inside the class only, and
not to be accessed by outsiders.
Obviously, if private, they will not be accessible outside the current package.

protected :

Protected members of a class are accessible inside the body of a class, or to


any of its sub-class.
Also, Protected members of a class are accessible in the classes in the same
package, through object of that class. For other classes they behave like
private members of the class.
A protected member of a class is inherited into the sub-class with the same
access control hence, for a sub-class of a sub-class the member is accessible.
Normal class cannot be declared protected, but inner class can be protected.

Prepared by, Prof. Santosh Kabir.


57
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


public :

public members of a class are accessible inside the class, as well as anywhere
outside the class also.
These members of a class accessible to any part of a program, but through
object of class.
If member is public and static it can be accesses by any part of a program by
using class name directly.
Public members are accessible to the sub-classes lying anywhere in the
program i.e. inside the same package or outside the package.
If class or a class member is declared public it can be used outside the
package also.
A class is declared public to make it accessible outside the current package.

Default access:

When members of a class are defined without any access specifier, they are
given a default access. Such members are partly public i.e. they are accessible
to the other parts of the program (through objects) which are in the same
package.
Also, they are inherited into sub-classes with same default access and are
accessible in the subclasses.
If a class is defined without any access specifier i.e. with default access, the
class is accessible to the classes in the current package.

Object class :

Object class and toString() method:


Java consists of thousands of built-in classes distributed over hundreds of packages
and sub-packages.
Object is a super-class of all the built in classes of Java.
The class is defined in a package java.lang.
Java classes like System, Integer, Vector, Font, Date etc are subclasses of
Object class. Some of them are direct subclasses and some are subclasses of
some other subclasses of Object.
e.g. Integer is a subclass of Number class, which is a subclass of Object
class. Thus, Integer class is subclass of Object, rather indirect sub-class of
Object.
Any new class defined by Java programmer in a program also becomes a direct or
indirect subclass of Object class.
i.e. if a class is defined without extending any class then it becomes a direct subclass of Object
and if a new class is defined by extending some existing class then it becomes a indirect
subclass of an Object through that pre-existing class.

According to inheritance rules of OOP, all the (non-private) members of a class


are accessible to all its subclases at whatever place the subclasses lye below
the superclass in a class hierarchy.

Prepared by, Prof. Santosh Kabir.


58
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


The class defines around 10 methods, which are inherited into all the classes in
Java API classes.
e.g. it has method equals() to compare two objects variables have same reference.
Method hashCode(), to get hash code (int) of the invoking object.
One of the methods of Object class is a toString().
It is commonly overridden by most of the Java classes. The method is used to return
String representation of the object contents.
Its syntax is as follows,
public String toString() // returns String
{
}
The method is invoked automatically when an object of a class is displayed.
e.g.
class ABC
{
int n1, n2;
public String toString()
{
String s = Values : n1= + n1 + .. n2= + n2 );
}
}
Consider following statements,
ABC r = new ABC();
r.n1 = 15;
r.n2 = 30;
System.out.println(Object r = + r ); . [A]
In above program statement A, invokes toString from r ( i.e. toString() of class ABC ).,
hence the output will be,
Object r = Values : n1=15 .. n2=30
[ If only toString() is asked describe Object class in short & write above notes ]

Class Relationships :
: or more Java classes present
Two

in the same application program can be related


with each other with some kind of relation. The types of Relation are :
1. Inheritance
2. Association
3. Aggregation
4. Composition

Inheritance :
The two classes are defined separately.
One class (i.e. sub-class) inherits some/all members of other class (i.e. super class).
Prepared by, Prof. Santosh Kabir.
59
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


Super class object do not depend on sub-class, but sub-class object depends on
super class.
Object of super-class is created and used by the system automatically.
The life-time of super class object will be same as that of sub-class object.
The relation is also called as IS A relation.
Manager of a firm is an Employee of the firm. Thus, Manager class and Employee
class can be related with inheritance.
Employee
empID
empName

Manager
DeptID
CarNo

Association :
The two classes are defined separately with no relation.
Both the class objects can be existing at a time.
One class Uses some members of the other class.
The two class objects do not depend on each other.
They can exist without each other.
Life-time of one class object do not depend on the other.
e.g. Teacher and Student class.
Teachaer teaches Student. One or more teachaers teach one or more students.
But, none of the class owns other class and both the class objects have their lifcycle.
Both objects can be created or deleted independently.
teaches

Student

Teacher
joins

Agregation :
One class Has object of another class.
i.e. one object owns another object.
But, the objects can exits independent of each other and have their own lifecycle.
Parent object (owner) holds one or more objects of other classes.
Child class cant have multiple parent objects (owners).
e.g.
class Car and class Engine can work independently or a Car can hold Engine object.
In following example class Car holds Engine object which is created separately and
its life cycle wont depend of Car object.
Prepared by, Prof. Santosh Kabir.
60
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


class Car
{
Engine obj;
setEngine( Engine r )
{
Obj = r;
}
.
}

Composition :
Its a specialization of Aggregation.
One class is Owns of the other class object.
Lifecycle of the contained object depends on the container.
Commonly the owner (container) class has a private reference to the child class
object and user of the container class can be completely unaware of the child class.
Lifcycle of child class is dependent on owner class object.
The relationship is also called as Life-Death relationship.
e.g.
Class Car can be privately owning the Engine class. The methods of Car class will
access some/all members of Engine.
In the following example constructor of Car creates private object of Engine.
class Car
{
private Engine obj;
Car ( )
{
Obj = new Engine();
}
.
}
As the Car object will be be created engine object will also start its lifcycle and it will
end with the life cycle of Car object.

Prepared by, Prof. Santosh Kabir.


61
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )

Interfaces :
Interfaces are used to just declare what a class should do and not how it does it. That is interfaces declare the
methods which that type of classes (i.e. its sub-classes) must have, how to implement those methods is left to the
classes.
Interfaces are declared with a keyword interface.
Interfaces are syntactically similar to classes, but cannot have instance
variables i.e. non-static variables, and their methods are declared without any body.
The methods in interface must be declared either public without access any
access specifier.
Methods of interfaces are only declared, using syntax,
[AccessMode] return_type method_name1( parameters ) ;
All the variables declared in interface behave as final and static, hence must be
initialized.
Interface can Not have any constructor.
General syntax of interface definition is as follows,
access_Specifier interface interface_name
{
final type1 var1 = value1;
final type2 var2 = value2;

type Method_Name1( parameters ) ;


type Method_Name2( parameters ) ;

Implementing and extending interface:


An interface can be implemented by a class using a keyword implements.
[AccessMode]class SomeClass [extends OtherClass]
implements interface1, interface2
{
// Overridden methods from base interfaces (must be public)
// other members of Class
}
Here, the AccessMode must be either public or not-defined. extends should be
mentioned (if required) before implements.
Class CAN implement multiple interfaces. If a class implements multiple
interfaces then the interface names are separated with a comma. Multiple
inheritance is thus achieved using interfaces.
All the methods declared in all the base interfaces, must be defined in the
current class. This is called implementing the methods.
Also, all the methods that are implemented (from interface) in the class must be defined
as public.

Prepared by, Prof. Santosh Kabir.


62
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


interface Shape
{
void set ( int d1, int d2 );
void show ();
double area();
}
Interface, Shape declares three methods. If a class implements Shape
interfaces, it has to override these three methods using public access
specifier.
If any method from interfaces is not required in a class, it must be defined
empty.
Additional methods can be defined in the class with required access mode.
e.g. if a class implementing a Shape interfaces do not require show(), it can be kept
empty as follows,
public void show( )
{
}
Interface name can be used as a superclass name to declare reference
variable, which can hold reference of any class object that implements this
interface.
e.g. class Rectangle implements Shape
{
e.g.

// must implement (define) all the methods from Shape ( as public )


// Additional members of this class

e.g

Partial implementation:
If a class Does Not implement all the methods from base interface then this is
called as partial implementation, and the sub-class must be declared as an
abstract class, else compiler error will be generated for the class definition.
Interface can extend other interface,
interface I1
interface I2 extends I1
{
{
void x();
void z();
void y();
// methods x() and y() are now part of this interface
}
}

A class implementing I2 must define (i.e. implement) all the methods of base
interface I2 i.e. x(), y() and z().

Prepared by, Prof. Santosh Kabir.


63
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM ( Sem III Comp / IT )


Compare Abstract class and Interface :
1
2

Abstract Classes
Defined using keywords abstract class.
It may contain normal data-members,
Methods and constructors. Also,
declarations for Abstract methods.
Can not be explicitly instantiated. But
its object is created by Java (implicitly)
when sub-class object is created.
Only abstract methods must be
redefined in sub-class.

5 One class can extend from one abstract


class.
6 Purpose is to provide base for defining
new classes with similar behaviours
and similar type.
e.g. Employee can be defined as
abstract class. And extending classes
can be Manager, Typist, Accountant
which are of type Employee.

Interfaces
Defined with keyword interface
Consists of only two type of members:
Method declarations , final static
variables
Can not be instantiated by any means.

All the methods declared in interface


must be redefined in implementing
class, and that too using public mode.
On class can implement multiple
interfaces.
Purpose is to provide only structure
and rules for implementing classes.
e.g. Movable can be an interface and
implementing classes can be Person
and Vehicle.

----0000----

Sem IV - IT

Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]

( Learn to design and develop small Internet based programs )

Regular batches at Andheri, Thane.

By Santosh Kabir sir.


Mobile : 98336 29398
Visit : www.santoshkabirsir.com for batch schedule and other info.

Prepared by, Prof. Santosh Kabir.


64
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

4. Inheritance

OOPM [ Comp / IT ]

Subjects Conducted by Santosh Kabir.


Semester Branch
FE Sem I

Subject
--

S.P.A.
FE Sem II

[ Structured Programming Approach ]


Programming with C.. Very important subject for Comp/IT students
and
for those who are interested in making career in I.T.

DSAA
[ Data Structures and Algo. Analysis ]
Lots of programming with Arrays, Pointers and structures.
SE Sem III [IT]

OOPM
[ Object Oriented Programming Methodology ]
Learn Object Oriented Prog with Java, with features like Exception
handling, Applets and Multithreading

DS
SE Sem III
[Comp]

[ Data Structures ]
Lots of programming with Arrays, Pointers and structures.

OOPM
(OOP with Java)

W.P.
SE Sem IV [IT]

SE Sem VI [IT]

[ Web Programming ]
(HTML, JavaScript,C#, ASP.Net,ADO.Net, PHP, JSP etc)
Want to develop your Web Site (Yahoo, facebook ..!)..
Learn the subject seriously
If you are learning with me ... hw abt dvlping mini fb
PMRC
(Old syllabus)

Regular and Vacation batches are taken at Andheri , Dadar, Thane, Dombivli.
( Demo. of programs on Projector )

Mobile : 98336 29398. Visit : www.santoshkabirsir.com

Prepared by, Prof. Santosh Kabir.


65
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

5. Exception Handling

OOPM [ Comp / IT ]

5. Exception Handling
What is exception:

Some

Exception is a run-time error. Such types of errors occur when some abnormal
conditions arise in some part of a program while it is running.
These errors can occur because of : (Causes of exceptions)
Sudden hardware failures used by the program, or use of invalid or restricted
resources by the program.
Errors can also occur while program execution because of in-correct (or
invalid) data input done by user. The other reason of run-time error is because
of mismatched data types.
Run-time error can occur because some error prone statements like
statement accessing array element outside the array limit.
Java uses Object-oriented approach for Exception handling. Exception in Java is
an object of some class that describes the error-condition that has occurred in some part
of a program.
There are lots of classes defined as exception classes in Java. When a runtime error occurs the object of a corresponding class is created and thrown
(i.e. generated) in the method that caused an error. This is done by Java runtime system.
If an exception is thrown, but not properly handled (i.e. not caught) in the
program, Java Run-time system shows the error message and program
terminates.
There is base class named Throwable in Java. All the exceptions are the subclasses of this class. Immediately below Throwable, there are two subclasses :
Exception and Error.
of the built-in Java exception classes shown in the following chart.
Object
Throwable
Exception

Error
(Not for FE / not discussed)

RuntimeException
IOException
SQLException
NoSuchMethodException
ClassNotFoundException

NumberFormatException
IndexOutOfBoundsException
ArithmeticException
NullPointerException

Array IndexOutOfBoundsException
StringIndexOutOfBoundsException
Prepared by, Prof. Santosh Kabir.
66
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

5. Exception Handling

OOPM [ Comp / IT ]

e.g. A NumberFormatException will be thrown if invalid value is assigned to


numeric data e.g. floating point value or String value assigned to integer type.
An Array IndexOutOfBoundsException will be thrown if some statement accesses an
array element outside the array limit.
NullPointerException is thrown if an object variable is not initialized to some object
and its members are accessed.
Java programmer can define his own class as an exception class and write a
code to throw it and handle it.
The class Error defines the exceptions which are not normally handled by user
programs. These errors occur because of some abnormal conditions arising in Javarun-time system. (Out of the FE syllabus).
See reference section for description of sum of the exceptions.

Uncaught Exceptions:
Lets try and understand what happens if an exception is raised in a program and it is not handled or
caught. Consider a following a program that divides one integer by the other and outputs the answer of
division. The two values are input from command line arguments, converted into int values and then
division is done.

class Expt
{
public static void main(String [ ]args)
{
int a, b, c;
a = Integer.parseInt(args[0]);
System.out.println("First integer accepted");
b = Integer.parseInt(args[1]);
System.out.println("Second integer accepted");
c = a/ b;
System.out.println("After div c = " + c);
System.out.println("Some other statements ...");
}
}
If while running a program valid values (e.g. 10 and 5) are entered from command line, then the
program will perform division, output is displayed and program terminates without any error.
The program can generate exception because of following runtime conditions,
If two values are not input at command line, then accessing args array elements will generate array
index error (ArrayIndexOutOfBoundsException). If any of the values is not an int value then
NumberFormatException will be generated.
Once an exception is generated in a program at a particular statement, the program terminates at that
statement and the error message describing the exception is displayed by Java run-time system.
If above program is run as follows,
java Expt 10 xy
The program will generate following output.
First integer accepted
Exception in thread "main" java.lang.NumberFormatException: For input string: "xy"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
Prepared by, Prof. Santosh Kabir.
67
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

5. Exception Handling

OOPM [ Comp / IT ]
at java.lang.Integer.parseInt(Unknown Source)
at Expt.main(Expt.java:8)
[ Students are not supposed to remember exact error statements, but must remember what type of
exception can occur at what statement ]
The program successfully reads first int value, but while reading second value, parseInt() method
generates an exception. Program terminates at that statement and an error description is displayed.
The error description consists of name of an exception (class name), the value for which error was
generated and the line number with method name.
Thus, whenever any un-handled (uncaught) exception is raised in a program, the program exits from
the statement that generated exception.

Handling Exceptions (try catch finally blocks ):

Exception is a run-time error. Such types of errors occur when some abnormal
conditions arise in some part of a program while it is running. If not handled
properly program terminates without any confirmation from user. This can
result into loss of data or some resource will fail to work temporarily or
permanently. (need of exception handling)
For every exception occurring in a program there is some corresponding Java
class or user defined exception class.
For handling the exceptions occurring in a program, Java provides a special
block of statements, called try-catch-finally block. try, catch and finally are
the keywords in Java.
The syntax for exception handling block is as follows.
try
{
// program segment that can generate (i.e. throw) exceptions
}
catch ( exception_type1 obj1 )
{
// Statements to handle (or describe) the exception
}
catch ( exception_type2 obj2 )
{
// Statements to handle (or describe) the exception
}
catch ( exception_type3 obj3 )
{
// Statements to handle (or describe) the exception
}
some catch blocks
finally
{
// Statements which must work (whatever way try-catch works)
}

Prepared by, Prof. Santosh Kabir.


68
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

5. Exception Handling

OOPM [ Comp / IT ]

The program segment that can generate one or more type of exceptions is
enclosed in a try block.
The catch statement is used to catch the exception and handle it. The
Exception_type represents any exception class name. Commonly the
statements in catch block will either take action to take care of error condition
or describe the error occurred to the user of the program.
finally block is used to execute some critical or compulsory statements that
must work whether exception occurs or no.

Working of try-catch-finally blocks:

If any statement in a try block generates an exception, the exception object is


generated and it can be caught by one of the catch blocks that matches the
exception type (in a variable obj1, obj2, obj2), and the statements in that
catch block will work. Other catch blocks are skipped.
If finally block exists it will work. Thus, the program will not terminate
automatically because of exception.
If there is no exception generated in the try block while program is running,
then try block will work completelty. None of the catch blocks will work. The
program will execute finally after try block and will jump to the end of trycatch-finally statement and program continues to work.
If exception is generated and couldnt be handled by any of the catch blocks,
then the exception remains uncaught. In this case try block stops at error
statement and finally block works (if exists). Then, Java runtime system
displays the error message and program terminates.
Try block must follow either one or more catch blocks or a finally block.
Only try or catch or finally can not be defined.
One can nest a try-catch-finally block in other try or catch or finally block.
They can contain any Java statements like input/output, variable
declarations, loops, method calls. Also, try-catch-finally can be part of any
method, or block of statements like loops etc.
If exception occurs in other part of the program (not in try-catch-finally) then
it will remain un-handled and program will terminate after displaying error.
This time default error handler in Java runtime system works.

[ Write and explain example if mentioned ]


Consider an example with try-catch-finally block as follows. The program reads two
integer values from command line and displays result of division of first number by
second.
class TryCatch1
{
public static void main(String []args)
{
int a, b, c;
try
{
a = Integer.parseInt(args[0]);
System.out.println("First integer accepted");
b = Integer.parseInt(args[1]);
Prepared by, Prof. Santosh Kabir.
69
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

5. Exception Handling

OOPM [ Comp / IT ]
System.out.println("Second integer accepted");
c = a/ b;
System.out.println("After div c = " + c);
}
catch(Exception ex)
{
System.out.println("Error in program : ");
}
finally
{
System.out.println("* This is finally block *");
}
System.out.println("...Some statements in the program ...");
}
}
Consider three different ways of running a program from command prompt,
1. > java TryCatch1 10 5
Program works without exception.
o/p
First integer accepted
Second integer accepted
After div c = 2
* This is finally block *
...Some statements in the program ...
2. > java TryCatch1 10 abcd
Program generates exception because data-type mismatch. Exception is
handled and program jumps to catch then finally and terminates normally.
o/p

First integer accepted


Error in program :
* This is finally block *
...Some statements in the program ...
3. If exception occurs that is not handled program will display error message,
execute finally and terminate.

[ In above explaination outputs may not be mentioned in exam answer, but explain three cases of
working of try-catch-finally ]

Displaying description of an Exception :


A Throwable class has a toString() method that returns a string containing description of an exception.
One can display the exception description in brief by displaying the exception object it-self. This is
possible because Java calls a toString() method when an object is displayed. In above example catch
block displays error description by displaying Exception object named ex in a println() statements.
Or a message part of exception can also be displayed invoking a getMessage( ) from exception object.
The method returns a Stirng that holds description i.e. message part of the exception. E.g. following
statement can be written in a catch block.

e.g. System.out.println( ex.getMessage() );


OR System.out.println( ex );
Prepared by, Prof. Santosh Kabir.
70
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

5. Exception Handling

OOPM [ Comp / IT ]
Using Multiple catch statements: (Catching multiple exceptions )

In most of the cases it is possible that program statements can throw multiple
types of exceptions. To handle such type of situation, one can specify two or
more catch blocks with a single try block, as shown below,
try
{
// some statemenets ( which can generate different exceptions)
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Array index error");
}
catch(NumberFormatException ex)
{
System.out.println("Invalid inputs");
}
catch(ArithmeticException ex)
{
System.out.println("Divide by zero error");
}
catch(Exception ex)
{
System.out.println("Error : " + ex);
}

When exception is thrown by a statement in try block, each catch block is


inspected in order ( top to last), and the first one whose type matches that of
the exception, is executed.
Once any catch block is executed all the other catch blocks are bypassed. The
program will then continue after the try-catch block.
e.g. if any statement in try assigns a string value to numeric variable,
NumberFormatException will occur, program will show error Invalid inputs and
jump out of try-catch block.
When multiple catch blocks are used with single try block, care must be taken
that catch block for subclass appear before any of their super-classes catch block. e.g.
the above example handles four different exceptions. One of them is Exception
itself, which is super class of all the exception classes and must appear at the
end in multiple catch statements.
If an exception occurs and none of the catch statement is able to catch it (i.e.
if exception is of type other than that are handled by catch statements), then
the exception remains uncaught and the program terminates because of that
exception.

finally block:
For handling exceptions in a program we commonly use try-catch block. If any exception is generated
in try block, the rest of the statements in the try block are skipped and the program jumps to catch block
and executes the statement in the catch block Then, the program continues its execution after catch
block. Thus, either try block fully works if there is no exception, other-wise try works partly and program
Prepared by, Prof. Santosh Kabir.
71
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

5. Exception Handling

OOPM [ Comp / IT ]
control is transferred to catch block.
In a program sometime it is required that some statements should always execute whether exception is
generated or not. The finally block is used with try-catch block in such conditions. The code written in

finally always executes whether exception occurs or not.


Consider that a method we are writing is supposed open some kind of resource (file or network
connection). Now, assume that the method opens the resource when it starts execution and closes
them while retuning to calling block. In this case whether exception occurs or not the resource must be
closed before retuning. In such situations the program segment that must execute is enclosed in a
finally block.
Overall try-catch-finally have syntax as follows,

try
{
// program segment that can generate exceptions
}
catch ( exception_type obj )
{
// Statements to handle (or describe) the exception
}
finally
{
//the code that must execute.
}

Throwing an Exception ( Explain Keywords throw, throws):


throw :

To throw (i.e. generate) an exception in a program Java provides a keyword


throw, and its general form is as follows,
throw Throwable_Object_name ;
Here Throwable_Object_name must be an object of type Throwable or object of
any sub-class of Throwable.
Common use of throw is demonstrated with general form below,
Type MethodName( Paramters )
{

try
{

throw Throwable_object ;

}
catch( Exception obj )
{
}
}
If a throw statement is encountered in a program, the program execution
stops after the statement has finished, any program statements after that are
not executed.
Prepared by, Prof. Santosh Kabir.
72
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

5. Exception Handling

OOPM [ Comp / IT ]

If there exists a try-catch block that encloses the statement, then the catch
block is inspected for the match.
If no matching catch is found, then the default exception handler will halt the
program and display the error description.
finally block will work if present.

throws:

If a method is capable of causing one or more exceptions that it does not handle, the
method must be defined by using throws clause.
This is required to guard the users of this method against the exceptions
caused by the method. This is done by including a throws clause in the
methods declaration.
Exception handling should be done at that part of the orogram where this
method is used ( i.e. called).
A throws clause lists the type of exceptions that the method might throw. This
rule is applicable for the all the exception types, except those of type Error or
RuntimeException or any of their subclasses.
A general form of declaring a method with throws keyword is as follows,
Type MethodName( parameters ) throws Exception1, Exception2,
{
Statements
}
Here the Exception1, Exception2.. is a list of the exceptions that the
method can throw.

Throws clause doesnt do exception handling.


====000====

Sem IV - IT

Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]

( Learn to design and develop small Internet based programs )

Regular batches at Andheri, Thane.

By Santosh Kabir sir.


Mobile : 98336 29398
Visit : www.santoshkabirsir.com for batch schedule and other info.
Prepared by, Prof. Santosh Kabir.
73
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

5. Exception Handling

OOPM ( Sem III Comp / IT )

6. User Defined Packages


Package is a collection of one or more classes and interfaces.
Java software consists of hundreds of built-in classes and interfaces with lots methods in them which
are used by Java programmer in their program.

The classes for similar purpose are put together in the form packages . e.g. java.io package has all
the classes that deal with input/output from user, from files.
While developing large real-life software, lots of classes are designed and developed which are then
bundled together to work like one application program. User i.e. programmer can define new packages
and the classes for similar purpose can be put together in one package.

Packages (What are packages) :

Packages are collection of classes and interfaces.


Package is like a folder and the classes/interfaces in it are like files in it. To
access a particular file we need to open the folder. Similarly to access a class
from a package we need to access the package (i.e. import the package).
Classes/interfaces can be stored under different packages according their
purpose and use. These packages hold classes and interfaces in bytecode form.
These classes can then be accessed by importing the package in our program
using import statement.
Java API has hundreds of built-in classes for different purposes. These
classes are not stored by Java at one place, but they are scattered over
multiple packages according to their use. Java API has a root package called
java and this package has different sub-packages for grouping different
classes.
e.g. Java API has a group of classes to handle input/output of data. All these
classes are stored under a package java.io. ( pakage.sub_package)
Package java.lang is called as a default package of Java. i.e. the package is
automatically imported in every Java program (even if not mentioned by
programmer). The classes like System, String, Integer and lots exception
classes are part of java.lang package.

What are advantages of Packages.


Classes are grouped according to their purpose and use.
Programmer can import only required classes from required packages. Because of
this Java compilers overhead of searching for the class names in entire set of Java
classes is reduced.
Multiple classes with same name and similar purpose can be defined in separate
packages.

Prepared by, Prof. Santosh Kabir.


74
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

6. Packages

OOPM ( Sem III Comp / IT )


package and import statements :
[ if only this is asked mention only first three points for Packages topic and then add following ]

package :

package is a keyword and the statement package is written as follows in a


Java program,
package package_name ;
// import statements
// define classes and interfaces in the file

The package statement states that the classes and interfaces defined in this
file should be included in the given package_name.
This statement (if present ) must be the first statement in a Java file. Below that
classes and interfaces are defined.

import :

The statement is commonly written at the beginning of a Java program, with


following syntax,
import package.* ; // to import all the classes from a specified package
Or import package.ClassName ; // to import only specified class from the package
If sub-package is to be mentioned then
import package.sub_package.* ;
//to import all the classes from sub-package.
Thus the statement is be used to import one or all classes from a package.
Import statement only imports classes from given package. The sub-packages
or classes in the sub-packages are not imported.
Import command only makes the specified classes/interfaces accessible to the
current program.
A program with import statement having * will compile slower than that with
only specific class name. But this does not have any effect on runtime.
If a class Demo is present in a package abc then it can be used in a Java
program in two different ways,
1. Import package :
import abc.*;
// or import abc.Demo;
Then, one can use following statement to use the class
Demo y = new Demo(); // creating object of Demo in a method or class
2. Using full class name :
The other way is by specifying full class name (import statement not required.)
some class and method definition
abc.Demo y = new abc.Demo( ); //creating object of Demo in a method or class

Prepared by, Santosh Kabir.


75
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

6. Packagess

OOPM ( Sem III Comp / IT )

Defining and Using Packages :


User defined Package /
With example demonstrate creating and using package:

Java programmer can create one or more packages and store


classes/interfaces in them. And use them in other Java programs by
importing them as required.

Example : Define a package with name geometry and include a class Circle in it.
Also, demonstrate using this class in other Java program by importing package.

Defining a Package :
Step 1. Write a new Java program with name Circle.java and define a public class
Circle in it with required members. To include the class in a geometry package we
write a package statement at the top.
package geometry ;
public class Circle
{
double radius;
public Circle( double r ) // constructor
{ radius = r;
}
public double area()
{ return 3.142 * radius * radius;
}
}
The class must be public and its constructor and methods must be public to provide access to the
program outside the package.
Step 2. Compile the program. The compiler will create a new package (rather a
folder) with name geometry (if it is not present) and put the compiled Circle class
into the package.

Using a package :
Step 3. Now write a new Java program outside the package (outside geometry folder)
and import the Circle class in it.
import geometry.* ; // or import geometry.Circle;
class A
{
public static void main(String[ ]args)
{
Circle c = new Circle( 10.0 ); // using Circle class of geometry package
System.out.println( Area = + c.area() );
}
}
Prepared by, Santosh Kabir.
76
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

6. Packagess

OOPM ( Sem III Comp / IT )


The import statement import all (or specified) classes from a package. The compiled
classes are imported (not the source code)
Also, we can use Circle class as follows (without importing package),
Geometry.Circle c = new geometry.Circle( 10.0 );
Note: If large package (i.e. a package with lots of classes) is imported using * notation as explained
above, the compilation time will increase. Its better to write multiple import statements and import only
required classes from a package. Whatever way classes are imported from packages, it has no effect
on the run-time performance of your program.
Refer to Reference Section for more information.

----0000----

Sem IV - IT

Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]

( Learn to design and develop small Internet based programs )

Regular batches at Andheri, Thane.

By Santosh Kabir sir.


Mobile : 98336 29398
Visit : www.santoshkabirsir.com for batch schedule and other info.

Prepared by, Santosh Kabir.


77
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

6. Packagess

OOPM ( Sem III Comp / IT )

7. java.lang Package

java.lang is the commonly used package of Java. The classes, interfaces and
exceptions defined in this package are used in almost all Java programs.
Its a default package of Java. It means, this package is automatically
imported in all Java Programs (whatever type of program it may) and hence
import command is not required for this package.
The package consists of classes like String, System, Math; Exceptions like
NumberFormatException, NullPointerException belong to this package.
Most of the classes have static methods and hence can be used without
creating object the classes.

String class :
In general most of the programming languages treat String as collection of one or more characters
stored under one variable name. In Java, string are commonly handled using String class of Java.
Thus, in Java strings are objects of type String.
Note: In Java string is not a char array. Also, strings in Java dont use any special character ( like null
character in C/C++) at the end of a string.

Strings in Java:
Any data enclosed in a double quotation symbols( ) is a string in Java.
Also, strings are represented by Java class String.
e.g.
String s = Hello Java;
Here, an object is created that holds string Hello Java and the reference variable s
refers to it.
Strings in Java are immutable i.e. once a String object is created, the contents of string
i.e. characters in the string, CANT be modified. Every time an attempt is made to
alter a string, a new String object is created that holds modified string, but the
contents of the original string will not be modified.
e.g. ( Explain why string are immutable )
Consider a string as given in above example,
If now we assign a new value to the string variable as follows,
s = Java is OOP;
the contents of string object are NOT modified, but a NEW String object is created
with string Java is OOP and the reference variable s refers to it. The old object will
be lost i.e. garbage collected.

Explain String class :

Every string value in Java is an object of predefined Java class String.


The class is included in Javas default package java.lang.

Prepared by, Santosh Kabir.


78
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

7. java.lang package

OOPM ( Sem III Comp / IT )

The String class has a lot of methods to work with string data e.g. Comparing
two strings, reading character at a required index in the string, Converting all
letters in a string to upper/lower case etc.
Since every string value represent a String object, following statement is valid,
s = Abc 12 xy.toUpperCase( );
And will generate a new string, s = ABC 12 XY
Constructors: String class object can be created in following ways,
1) Assigning a string value to String type of variable,
String s = Hello Java;
2) From an existing string object,
String s1 = Hello Java;
String s2 = new String ( s1 ); // s2 is created from s1
3) Using char array,
char m[ ] ={ A, B , C, D , E , F };
String s = new String( m ); // s holds a string ABCDEF
Another constructor creates String object using sub-array i.e. part of the array of
chars. The constructor has general syntax as follows,
public String(char[ ] value, int offset, int count);
Allocates a new String that contains characters from a sub-array of the character
array argument. The offset specifies the index of the first character of the subarray
and the count specifies the length of the subarray. The contents of the subarray are
copied into new string.
e.g.
String s = new String( m, 2, 3 ) ;
Will create a string object using 3 array elements starting from index 2 i.e. using
characters m[2] to m[4].
Thus, s holds a string CDE
String object can be allocated using StringBuffer object also.

Some methods :
Consider String objects,
S1 = ABC PQ AB , S2 = ABD XY, S3 = HELLO
1) char [ ] toCharArray() : Method returns an array of characters stored in a string
with the same length as that of string.
char b[ ] = S2.toCharArray(); will result into following
b array will hold 6 characters A B D X Y
2) boolean equals( String s) : If current string has same contents as in s then
returns true else false. It is case sensitive.
e.g. S1.equals( S2 ); will return false
S3.euals( HELLO ); will return true
3) int indexOf( String s) : Returns an index of first occurrence of s in current string.
If s is not found in current string, returns -1. It is case sensitive.
S1.indexOf(BC); will return 1
S1.indexOf(bc); will return -1
Prepared by, Santosh Kabir.
79
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

7. java.lang package

OOPM ( Sem III Comp / IT )


There are different overloads for this method.
4) String substring( int f , int e) : Returns a string containing characters of current
string from index f to e-1. Current string not affected.
S1.substring( 1, 5 ); will return string BC P

The String class methods that are used to alter string do not alter the original string
contents but they return a new string object, which consist of an altered
characters.

e.g. String s = Hello;


String class has a method toUpperCase() that converts all the characters in a current string to
uppercase letters.
e.g.

String s2 = s.toUpperCase( );

toUpperCase() method returns an object of String with modified characters, but the
original string s will not be altered. Thus, after this statement string s will hold
original characters i.e. Hello and s2 holds HELLO.
Almost all the string methods are case sensitive.
e.g. s3.indexOf( e ); will return -1 to indicate letter e is not found in s3.
The method that deal with the index of characters, generate
IndexOutOfBoundsException if an index outside the string length is accessed.
e.g. s2.charAt( 10) ; will generate above exception.
(If question is Explain strings in Java then do not mention topic Constructors and methods in String )
( If question is Explain String class or String methods then write complete answer. Do not write explainantion of
how string are immutable. )

StringBuffer class :
String in Java is fixed length immutable character sequence, i.e. contents of string cant change and characters
cant be added or removed from existing string objects.
StringBuffer is a peer class of String and it provides a lot of functionality for
strings. In contrast to String, StringBuffer represents growable and writeable
character sequence.
The characters (i.e. string) stored by StringBuffer can be changed by inserting
characters and substrings in the middle or appending to the end. StringBuffer
will automatically grow to make room for such additions and often has more
characters pre-allocated than are actually needed, to allow room for growth.
In simple words StringBuffer allocates more space for characters than
currently required, so that if characters or strings are appended to the
existing contents, re-allocation of memory is not required.
The class has one very important feature: capacity. Capacity is the size (i.e.
length) of internal buffer used by StringBuffer object to hold string characters.
The other term used regarding size of StringBuffer object is length which is
length of the string (number of characters ) currently stored in the
StringBuffer object.
As the characters are added or removed the length is changed every-time, but
the capacity will change only when number of characters exceed the buffer
Prepared by, Santosh Kabir.
80
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

7. java.lang package

OOPM ( Sem III Comp / IT )

capacity. Thus capacity refers to the size of memory allocated to hold the
string.
e.g. say a StringBuffer object holds a string of length 7 and the buffer
capacity is 20. As we add characters, the length will increase but the capacity
( i.e. internal buffer length) remains same until 21 st character is added. As the
21st character is added string length becomes 21 and capacity is doubled to
current length i.e. it becomes (21 x 2 = 42 ). Now, the object can hold up to 42
characters without resizing, but when a 43rd character is added to the object
the capacity will increase to 86 and so on.
Constructors:
StringBuffer( ) Default constructor. Creates buffer with capacity 16.

StringBuffer(String str) : Constructor with one String argument. Creates an


object that holds contents of string str and reserves room for 16 more
characters. The initial capacity of buffer = length of string + 16
e.g. String str = Hello;
StringBuffer bfr = new StringBuffer( str );
Will create a buffer with capacity 21 ( 5+16).
StringBuffer(int n) : Constructor with one int argument. Creates a
StringBuffer with initial capacity explicitly set by parameter i.e. n

Some Methods :
Assume StringBuffer objects sb1 = Hello, sb2 = ABCD PQ with current
capacity as 10.
Methods length() and capacity() return current length and capacity of a
StringBuffer object. Hence, for sb1.length() returns 5 and sb1.cpacity() returns
10.
void setCharAt( int i, char ch ) : Sets the character at index i to ch.
To work with a string in the object the index should be part of string i.e. it
should be 0 to length() -1.
Sb1.setCharAt( 1, A ); will result into string HAllo
StringBuffer insert( int idx, data_type val ) : The insert( ) method inserts one string
into another. It is overloaded to accept values of all the simple types, plus
Strings and Objects.
Sb1.insert( 1, 2.5); will change string to H2.5ello
Almost all the methods are case sensitive.
e.g. sb1.indexOf( E ); will return -1 to indicate letter E is not found in s3.
The method that deal with the index of characters, generate
IndexOutOfBoundsException if an index outside the string length is accessed.
e.g. sb1.setCharAt( 10, M ); will generate above exception.

Prepared by, Santosh Kabir.


81
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

7. java.lang package

OOPM ( Sem III Comp / IT )

System class :
It is a sub-class of Object class and is defined as a final class in a java.lang package.
The class holds a collection of public static methods and variables. (Static members of class are
accessible outside the class without creating object of a class using notation
ClassName. MemberName
ClassName.MemberName(param)

for methods.

Fields:
in : (static InputStream in) : its an object of type InputStream. It typically corresponds to the input
device such as keyboard.
out ( static OutputStream in ): Represents an output stream that is always open to send data to
standard output device such as display.

Some Methods:
static void arraycopy (object src, int srcStart, object dest, int destStart,
int length) : Copies entire or part of one array to the other array. (see topic Arrays in chapter 2)
1. static Console console ( ): Returns Console class objects that represent console (typically
keyboard of display device) for the computer. (only JDK1.6)
2. static void exit ( int exitCode ) : Halts execution of current program and returns back to calling
process (usually Operating System). ExitCode =0 indicates normal termination. e.g

System.exit(0);
3. static void gc ( ) : Runs garbage collector. It instructs JVM to recycle the unused objects, so as
to make the memory free for reuse.

Math class :
The class Math contains methods for performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions.
It is a sub-class of Object class and is defined as a final class in a java.lang package.
Methods in the class are static. The methods have one ore more argument and return some value.
Most of the methods have arguments of type double and return double type of value.
It defines two constant fields (i.e. final static variable) E and PI whose values are approximately 2.72
and 3.14 respectively.
Some methods :
Since the methods are static they are generally invoked using following syntax:

Variable = Math.MethodName( arguments );


int abs(int v) : Return absolute value of argument v. It is overloaded for long, float, and double also.
Methods sin(), cos, tan() return corresponding values for the angle specified as an argument. The
methods have double argument and return value. Angle should be radians.
e.g. double y = Math.sin( x) ; will return sine of angle x into variable y.
double sqrt( double a ) : Returns square of argument a.
double pow( double x, double n) : return power x

double log( double a) : Returns natural log (base e) of argument a.


Prepared by, Santosh Kabir.
82
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

7. java.lang package

OOPM ( Sem III Comp / IT )

Type Wrapper classes :


Java provides primitive data types int, float, boolean etc which are not classes. i.e. these types represent nonobject types. When these type of variables are created (declared) they occupy certain amount of memory. These
variables hold the value assigned to them and not the reference for any object. Any operations performed with
these types of variables are faster than operations performed on any objects.
For the primitive types like int, char, double etc Java provides built-in classes
called as Wrapper classes. This, classes are used to represent a primitive data
type in corresponding object type. e.g. for int type we have wrapper class
Integer.
We can wrap the primitive values into corresponding object type as follows,
int a = 15;
Integer r = new Integer ( a );
In above example, int type value is wrapped into object type.
The type wrapper classes (for numeric types) are subclasses of built in
abstract class Number. The type wrapper classes ( also called Wrapper classes)
and their corresponding primitive types are shown in the table below,
Wrapper class
Byte
Short
Integer
Long
Float
Double
Character
Boolean

Primitive data type


byte
short
int
long
float
double
char
Boolean

Most of the methods in these classes are static methods, hence we can invoke
the methods directly for our data, without creating object.
Using these classes one can convert a primitive type value to object type,
object type to corresponding primitive types or numeric objects to string type
etc.
Also, these classes have methods to get binary, octal equivalent of a given
value, as shown in following example,

class WrapperDemo
{
public static void main(String[]args)
{
int a=15;
float f;
String s1, s2= 34.5;
Integer objI = new Integer( a ); // primitive to obj.
Prepared by, Santosh Kabir.
83
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

7. java.lang package

OOPM ( Sem III Comp / IT )


s1 = objI.toString();
// object to string
System.out.println("s1=" + s1);
Float objF = Float.valueOf(s2); // string to obj.
f = objF.floatValue();
// object to primitive type
System.out.println("objF=" + f );
System.out.println("objI=" + objI); //String value of object displayed
s1 = Integer.toBinaryString( 13 ); //getting binary value for int
System.out.println("Binary string for 13 = " + s1);
}
}
Output:
s1=15
objF=34.5
objI=15
Binary string for 13 = 1101
The primitive types are value types and not the objects. A lot of Java classes
have methods which work with object data-types and not primitive types (e.g.
Vector class). To use such classes we need to convert primitive types to object
types using wrapper classes.
[ For a Qn Applications of Wrapper class, mention above points. Dont give example ]

Note : Some of the wrapper classes are explained in class reference section.

Character class :
It is one of the wrapper classes and is defined in java.lang package.
The character class wraps a value of a primitive datatype char in an object. An object of type
Character contains single field whose type is char.
In addition the class provides several methods for determining a characters category (lower/upper case
letter, digit etc.) and for converting characters from lower-case to upper-case and vice versa.
Character information is based on the Unicode standard.
Constructor of the class has one char argument, and it stores the char value into the Character object.
e.g. Character obj1 = new Character( m );
or char n= T ;

Character obj2 = new Character( n );


Following topic covers some of the commonly used methods of the class.
Since the methods static, they are commonly invoked using following syntax,
Variable = Character.methodname( arguments );
e.g. lets assume we have two Character objects with name obj1 and obj2 as follows,

char ch1 = m, ch2= 4;


Character obj1 = new Character( ch1 );
Character obj2 = new Character( ch2 );
static boolean isUpperCase( char ch ) Returns true if the character value passed as parameter
is an upper case letter.
isUpperCase method works sa,e way.
Prepared by, Santosh Kabir.
84
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

7. java.lang package

OOPM ( Sem III Comp / IT )


static boolean isLetter( char ch ) Returns true if the character value passed as parameter is a
letter else returns false.

static boolean isWhitespace( char ch ) Returns true if the character value passed as parameter
is a white-space (space, new-line, tab etc) else returns false.

static char toLowerCase( char ch ) : Returns lower-case letter for the char variable passed as
parameter, if and only if the character is an upper-case letter else same character value of the
parameter is returned.

[ Explain character class of Java : write above answer ]


Some more methods are as follows,
int charValue() : Returns char value of the current object.

static boolean isLowerCase( char ch ) Returns true if the character value passed as parameter
is an lower case letter.

static boolean isDigit( char ch ) Returns true if the character value passed as parameter is a
digit else returns false.

static boolean isLetterOrDigit( char ch ) Returns true if the character value passed as
parameter is a letter or a digit else returns false.

static boolean isSpaceChar( char ch ) Returns true if the character value passed as parameter
is a Unicode space character else returns false.

static char toUpperCase( char ch ) : Returns upper-case letter for the char variable passed as
parameter, if and only if the character is an lower-case letter else same character value of the
parameter is returned.

static String toString( char ch ) : Returns the string representation for the char variable passed as
parameter.
Consider following program to understand some of the above methods,

class CharacterTest
{
public static void main(String[]args)
{
char ch1 = 'm', ch2= '4';
Character obj1 = new Character( ch1 );
Character obj2 = new Character( ch2 );
System.out.println("Char value=" + obj1.charValue() );
System.out.println("is uppercase="+Character.isUpperCase(ch1) );
System.out.println("is lowercase="+Character.isLowerCase(ch1) );
System.out.println("is digit=" + Character.isDigit(ch2) );
System.out.println("is letter or a digit=" + Character.isLetterOrDigit(ch2) );
System.out.println("uppercase of m="+Character.toUpperCase(ch1));
Prepared by, Santosh Kabir.
85
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

7. java.lang package

OOPM ( Sem III Comp / IT )


System.out.println("uppercase of 4="+Character.toLowerCase(ch2));
System.out.println("same =" + (obj1.compareTo(obj2) == 0 ? "Yes" : "No" ) );
}
}
Output will be as follows,
Char value=m
is uppercase=false
is lowercase=true
is digit=true
is letter or a digit=true
uppercase of m=M
uppercase of 4=4
same=No

----0000----

Sem IV - IT

Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]

( Learn to design and develop small Internet based programs )

Regular batches at Andheri, Thane.

By Santosh Kabir sir.


Mobile : 98336 29398
Visit : www.santoshkabirsir.com for batch schedule and other info.

Prepared by, Santosh Kabir.


86
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

7. java.lang package

OOPM ( Sem III Comp / IT )

8. Collections and java.util


Introduction
This is one of the largest packages of Java. The package consists of large amount of utility classes to
handle date and time, to handle collection of objects or simple data-types, class to generate random
numbers etc.

Short note on java.util package :


The package consists of lots of utility classes and interfaces.
The major part of the packages is collection framework : This is a set of classes and
interfaces that can be used by Java programmer to work with collection of data (i.e.
objects).
e.g. Vector class works like a growable array and the class consists of lots methods
to access the objects stored in the collection. The class Hashtable can be used to
hold collection of objects in a key-value pair. Here required object can be accessed
using the key.
The other classes can be used for time and date management in Java programs. The
classes Date and Calendar can be used for this purpose. Using these classes
program can read current system date and time. Date and time difference can be
evaluated using the methods in the classes.
A Random class can be used to generate a series of random numbers. The random
numbers can be integers of floating-point values.
A class StringTokenizer can be used to break a string into multiple tokens (e.g. into
multiple words).
We will discuss type of classes called as collection classes i.e. Vector, ArrayList and LinkedList.

Collection Classes:
Collection is a group of multiple elements (Objects or simple data-types) put under one name. Java
provides lots of collection classes that let you group elements in various ways. e.g. some collections
allow duplicate elements and some dont. Also some collections make ordered list of elements and
some make an unordered list. These collections provide you, a means of storing large amounts of
elements together and provide methods to perform some basic operations like removing elements,
adding element in the group of elements etc.
Before we study the classes Vector and Hashtable lets take an overview of the base interfaces on
which these classes are built.

Interface Collection:
[This part is not for Exams. ]
Its a root interface of all the collection classes. Lots of collection classes implement this interface.
Obviously, an interface doesnt define methods but only declare them. The classes which implement
this interface implement the methods. It has methods such as add( ) to add object into collection,
Prepared by, Santosh Kabir.
87
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

8. Collections and java.util

OOPM ( Sem III Comp / IT )


addAll( ) to add all the objects of a Collection to the current Collection, remove( ) to delete a given
object from current Collection.

Interface List:
[This part is not for Exams ]
The interface extends a Collection interface. Its an ordered collection (also known as a sequence). The
interface provides methods to insert an element at a required position. So the user has precise control
over where in the list each element is inserted. The user can access elements by their integer index
(position in the list), and search for elements in the list. List can hold duplicate values. In addition to the
methods defined by Collection, List defines some of its own.

Interface Enumeration :
We can use methods of Enumeration to loop over elements in class such as Vector. An object that
implements the Enumeration interface generates a series of elements, one at a time. The methods of
Enumeration are as follows.

boolean hasMoreElements() :
Tests if this enumeration contains more elements. Returns true if this enumeration object contains at
least one more element to provide; false otherwise.

Object nextElement( ):
The method returns the next object in the enumeration as a generic Object reference. That is, each call
to nexstElement( ) obtains the next object in the enumeration. The calling routine must cast that object
into the object type held in the enumeration.

[ See Vector class and its example for understanding this topic ]

Vector class :

Java has a group of built-in classes in java.util package. These group of


classes are called as collection classes. These classes are used to hold
collection of same or different type of objects. The classes provide methods to
handle the objects in the collection efficiently and easily. One of these classes
is a Vector class. The class is a sub-class of class AbstractList and it
implements a List interface.
The Vector class works like a dynamic (growable) array of objects. i.e. it works like
an array of objects whose length can increase or decrease during runtime.
Like an array, it contains components that can be accessed using an integer
index.
Vector can be created without mentioning any initial size. As elements are added to
a vector, the size of the vector increases. Also, as the elements are removed
from a vector the size of vector reduces. Vector can hold collection of any type of
objects. Also, a vector at a time can hold elements of different types.
Vectors in Java implement features called as Capacity, Capacity increment and
Size. Capacity of a vector is maximum number of elements that can be added
to vector without new memory allocation (i.e. without resizing the vector).
Capacity increment stands for the increment in the capacity of a vector once

Prepared by, Santosh Kabir.


88
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

8.Collections & java.util

OOPM ( Sem III Comp / IT )

the vector is filled up to its capacity. Size of a vector is the number of


elements currently stored in a vector.
Size of a vector can be less than or same as Capacity of the vector.
e.g. suppose a vector is created with initial capacity 10 and capacity
increment as 5. Java pre-allocates memory for 10 elements, and vector is still
empty i.e. size of vector is zero. As elements are added, the size of vector
increments, but capacity remains 10. Once 11th element is added the capacity
becomes 15 (because increment is set as 5) and the size of vector is 11. This,
mechanism saves an extra effort and time required for the Java runtime
environment for memory allocation for every element.

Constructors :
Vector( ) : Creates an empty vector so that its internal data array has size 10
Vector (int capacity) :Creates an empty vector with the specified initial capacity
Vector(int capacity, int incr) : Creates an empty vector with the specified initial
capacity and capacity increment.
Vector(Collection c) : Constructs a vector containing the elements of the specified
collection. Throws NullPointerException if the specified collection is null.
[ Students need not mention exact syntax for constructors, but can only explain how vector objects can
be created in simple words. This applies for all Java classes we study ]

Some methods :
Vector has methods to add element at the end i.e. add(Object obj) or at specific index
i.e. addElement(int I, Object obj).
We can check whether vector is empty by a method isEmpty() that returns true if
vector is empty.
We can remove an element by using removeElementAt( int index) or we can empty
the entire vector by removeAll() methods.
We can get the collection of elements in vector as an Enumeration object using
method elements().

Compare arrays and Vector:

Array must be defined with some size that indicates how many elements the
array can hold. Vector size is not specified when vector is created.
The size of array can not be changed once defined. Vector can be defined with
any initial size and it increments as elements are added to vector.
Vector can grow in size as required. Array length is fixed. If array limit is
exceeded it generates an exception.
Vector implements Capacity and Capacity increment which is not present in
arrays.
Array can hold one type of elements only, but vector can hold any type of
collection.
Since Vector is a class defined in Java, it has many methods to process the
vector elements. But array (even though treated as object) doesnt have
methods to process array elements.
Syntax difference :

Prepared by, Santosh Kabir.


89
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

8.Collections & java.util

OOPM ( Sem III Comp / IT )


Creating vector object,
Vector v = new Vector ( );
//this is one of the ways. This creates empty vector with capacity 10

Creating int array of size 25,


int a[ ] = new int[ 25 ];
[ If difference/comparison is asked, mention initial two points in Vector description also ]
[ If question is explain Vector : Constructors and methods not required ]
[ If question is explain Vector class : Constructors and methods should be mentioned. Comparison with
array not to be written ]

ArrayList : (class)

Its a Collection class, belonging to java.util package.


The class implements built-in List interface and extends AbstractList.
The class supports dynamic array of Objects and grow in size as needed.
Every ArrayList has a capacity which is the size of the underlying array. The
capacity grows as more and more elements are added to ArrayList.
The capacity is always as large as size of the list.
Constructors :
ArrayList() : Creates an empty list with capacity 10.
ArrayList( Collection c ) : Creates a list with elements taken from specified
collection. The initial capacity of the ArrayList is 10% more than of the size of the
given collection.
ArrayList( int cap ) : Crates an empty list with specified initial capacity.
Some Methods :
add() : One of add() methods is to add element at the end of list and the other is to
add element at a specific index in the list.
clear() : method removes all the element from list.
addAll() : the method is used to add a given collection into the list.
toArray() : The method returns array of objects contained in the list.
The methods which use index as parameters throw exception if index is out of the
bounds of current list elements i.e. If index >= size.
Demo program for working with ArrayList :
import java.util.*;
class Demo
{
public static void main(String[ ]args)
{
int c=0, s=0, i;
ArrayList list = new ArrayList();
System.out.println("size=" + list.size() );
for(i=3; i<=7; i++ )
Prepared by, Santosh Kabir.
90
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

8.Collections & java.util

OOPM ( Sem III Comp / IT )


list.add(i);
System.out.println("Size=" + list.size() );
System.out.println("Elements=" + list );
list.add(2, 25);
list.remove(4);
System.out.println("Size=" + list.size() );
System.out.println("Elements=" + list );

Output :
size=0
Size=5
Elements=[3, 4, 5, 6, 7]
Size=5
Elements=[3, 4, 25, 5, 7]
Size=5

list.set(1, 30);
System.out.println("Size=" + list.size() );
System.out.println("Elements=" + list );

Elements=[3, 30, 25, 5, 7]


Size=3
Elements=[3, 30, 5]
List elements in array:

list.remove(2);
list.remove(3);
System.out.println("Size=" + list.size() );
System.out.println("Elements=" + list );

3
30
5

System.out.println("List elements in array:" );


Object[ ] a = list.toArray();
for(i=0; i<a.length; i++ )
System.out.println( a[i] );
}
}

LinkedList :

( class )

The class implements List and Queue interfaces and extends


AbstractSequentialList class. The class belongs to java.util package.
It provides a Linked list data structure.
The class provides methods adding and removing elements from beginning anf
end of the list. using these functions the list can be easily used as Stack (lifo
list), Queue(fifo list) or Double-ended queue.

Constructors:
LinkedList() : Creates an empty linked list.
LinkedList( Collection c) : Creates a linked list with the elements of specified
collection.
Methods:
add() : Methods to add element at the end of list or at specified index.
addFirst(), addLast() : Methods to element at the beginning and at the end of the list
respectively.
getFirst() , getLast() : Methods return element at the beginning and at the end of the
list respectively. Element returned is an Object type.

Demo Program for LinkedList class :


Prepared by, Santosh Kabir.
91
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

8.Collections & java.util

OOPM ( Sem III Comp / IT )


import java.util.*;
class Demo
{
public static void main(String[ ]args)
{
int c=0, s=0, i;
LinkedList list = new LinkedList();
System.out.println("size=" + list.size() );
for(i=3; i<=7; i++ )
{
list.add(i);
}
System.out.println("First=" + list.getFirst());
System.out.println("Last=" + list.getLast());
System.out.println("Size=" + list.size() );
System.out.println("List=" + list );

Output :
size=0
First=3

list.add(2, 25);
list.remove(4);
list.addFirst(10);
System.out.println("Size=" + list.size() );
System.out.println("List=" + list );

Last=7

list.set(1, 30);
System.out.println("Size=" + list.size() );
System.out.println("List=" + list );

Lists=[10, 30, 4, 25, 5, 7]

list.remove(2);
list.remove(3);
System.out.println("Size=" + list.size() );
System.out.println("List=" + list );

10

Size=5
List=[3, 4, 5, 6, 7]
Size=6
List=[10, 3, 4, 25, 5, 7]
Size=6
Size=4
List=[10, 30, 25, 7]
List elements in array:
30
25
7

System.out.println("List elements in array:" );


Object[ ] a = list.toArray();
for(i=0; i<a.length; i++ )
System.out.println( a[i] );
}
}

Prepared by, Santosh Kabir.


92
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

8.Collections & java.util

OOPM ( Sem III Comp / IT )


JAR utility (JAR files):

JAR stands for Java Archives.


It is file compression utility provided by Java.

When one or more files are to transported from one place to the other, safety and convenience of
carrying the files are important issues. It is usually expected that the files should be compressed into a
single file (called archive) before transferring on net or manually and decompressing at the place where
it is needed.
When Java application is developed, it can involve defining multiple classes for different parts of the
applications. These classes will form multiple class files. Also, the application can include use of
images, icons and other data in files.
The utility is used by running an executable file named jar.exe (or only jar) from command prompt.

One can use JAR utility to compress the multiple files (in Java application)
and even un-compress (extract file from) the compressed files.
JAR utility is part of JSDK, and it is installed into bin folder of JDK folder
when JSDK is installed.
The utility has multiple options to compress and extract files. The general
syntax is as follows,
jar options filenames
The filenames can specify the files to compress (file to put into Java archive) or file to
extract.
Using JAR utility one can :
Compress mulitple files into one .jar file,
Uncompress jar file into multiple original files,
Add some files to existing jar file,
View the list of the names of the compressed file present in one jar file.
[ If question is asked for more than 6 marks write following examples ]
The options are different letters which indicate what and how to do. The options are described below,

Option

Description

A new archive is to be created.

First element in the file list is the name of the archive that is to be created
or accessed. If option f is mentioned then JAR utility treats the first name
in the filenames as the name of the Java archive to operate.

Update existing JAR file

The archive contents to be tabulated.

Extract files form archive. The name of file to extract is specified as first
file name and that is indicated by option f

The utility is explained with common options below,


Suppose we have some files like a.class, b.class, c.class, p.gif in some folder, then the JAR utility can
be used as follows,
1) Creating new JAR file with three files a.class, b.class, p.gif :

Jar cf xy.jar a.class b.class p.gif


The above command will create a new JAR file with name xy.jar, by compressing files a.class,
b.class and p.gif (from current folder). The options c specifies create new Java Archive. Option f
specifies that the first name (here xy.jar) in the filename list is the JAR file to operate (here create new).
Prepared by, Santosh Kabir.
93
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

8.Collections & java.util

OOPM ( Sem III Comp / IT )

2) Tabulating archive contents:

Jar tf xy.jar
Here t specifies tabulate contents, and f specifies that the first name is the archive file whose
contents are to be tabulated. The output will be similar to the output shown below:
META-INF/
META-INF/MANIFEST.MF
a.class
b.class
p.gif
3) Updating Jar file:

Jar uf xy.jar c.class


Adds a new file c.class to the existing Jar file.
4) Extracting files from JAR file:

Jar xf xy.jar
Extracts all the files from the specified archive file. The extracted files are placed
in the current directory.

-----0000-----

Sem IV - IT

Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]

( Learn to design and develop small Internet based programs )

Regular batches at Andheri, Thane.

By Santosh Kabir sir.


Mobile : 98336 29398
Visit : www.santoshkabirsir.com for batch schedule and other info.

Prepared by, Santosh Kabir.


94
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

8.Collections & java.util

OOPM ( Sem III Comp / IT )

9. Applet and Graphics Programming


Java programs can be broadly classified into two types: Applications and Applets.

Compare Java applications and Applets :


1. Java applications run completely using JVM. Thus, they can run from
command line or through any Java IDE.
Applets run on internet Browsers only with the help of JVM in brower. HTML tag
<Applet> is used to load and run applet on a Web page.
2. Java applications use main() method as entry point and JVM invokes the
method when Java application starts.
Java applets entry point is init() method. And the method is called by Brower.
3. Java applications start with main() and normally terminate as main() ends
and programmer needs to invoke particular methods.
Java applets may start with init(), paint(), or start() methods and these
methods are called by Browser at certain stages when applet is running.
4. Java application can use complete Java API ( i.e. all the built in classes and
interfaces) and hence variety of applications are possible. e.g. Console
applications, GUI based applications, Web applications etc.
Where as Applets can use limited set of Java API and are particulary used to
interact with web page user.

Writing and Running a simple Applet:


To write an applet program, we need to use an Applet class defined in java.applet
package. Actually a program (rather a class) that has to work as an applet must be a
sub-class of Applet class.
Also the class must be declared public. Obviously, the applet class-name and the
Java file name in which it is defined must be same.
Write a Java program to display some message as follows. The program uses
(overrides) paint() method of Applet class. Lets assume the program name is
App1.java and it is saved in a folder d:\MyApp. The program just outputs a simple
hello message.
import java.awt.*;
import java.applet.*;
public class App1 extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello Applets ..!", 25, 25);
}
}
Compile a program. This will create a class file Ap1.class in the same folder.
Prepared by, Prof. Santosh Kabir.
95
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

9.Applet & Graphics

OOPM ( Sem III Comp / IT )


Now type HTML file with following lines and save in the same folder, say name is
H1.html.
<html><head><title>First applet</title></head>
Case sensitive
<body bgcolor= yellow>
<h3>Browser with Applet </h3>
<applet code=App1.class width=50 height=30> </applet>
</body>
</html>
The tag <applet ...> defines, which applet to execute in this web page, and what
should be the size of an Applet window.
Double-click on the file h1.html to open it. A browser window will open with
background color yellow. In the body of browser, other than html information we can
see a small rectangle (called applet window) with the message Hello Applets ..!

OR One can start a browser (Microsofts I.E or Netscape Navigator) and open an HTML file H1.html
from File menu of the browser.

Other way of testing (i.e. running) an applet is using Appletviewer.


Java (i.e. JDK) provides a browser named Appletviewer (i.e. a program appletviewer.exe) which is
installed in a computer when you install any JDK. It is installed in the same bin folder where Java
compiler (javac.exe) and Java virtual machine (java.exe) exists. This program is a Java browser used
only for running and testing Java applets.

You can test the above applet by running it in Appletviewer. Run a following
command from command prompt ( from your folder e.g d:\MyApp).
d:\MyApp> appletviewer h1.html
Prepared by, Santosh Kabir.
96
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

10 . Applet & Graphics

OOPM ( Sem III Comp / IT )


The appletviewer runs the specified html file and shows the applet contained in it.
But, appletviewer display only the applet not the rest of HTML contents.
The applet window appears as follows.

Applet menu

Applet Window

Applet body
Status bar
Third and common way of running and testing an applet is writing <applet .. > tag
inside the Java applet program at the top in the form of Java comment as follows,
import java.awt.*;
import java.applet.*;
/* <applet code=App1.class width=50 height=30>
</applet> */
Java applet program here

The above applet program can be tested as follows,


appletviewer App1.java
Here, the appletviewer reads the <applet .. > tag information from the Java program
and runs the applet class file specified in the code attribute. The above applet tag can
be written anywhere in a Java program.

Applet Life-Cycle :

All the Java applets that we write consist of main class that inherits from
Applet class. Thus, every applet program inherits some default behaviours
from Applet class. The methods such as init() , start(), stop(), destroy(), paint()
exist in Applet class which define certain behaviour of every applet program.
These methods are invoked by a Browser at different stages when applet runs. If all or
any of these methods are defined in our applet class then (according
inheritance rules) the methods from our class will work else the methods from
Applet class will work.
The full execution cycle ( from running an applet till terminating ) is called
lifecycle of an Applet.
An applet goes through following stages:
1. Initialization
2. Running applet
Prepared by, Santosh Kabir.
97
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

10 . Applet & Graphics

OOPM ( Sem III Comp / IT )


3. Stopping applet i.e. idle state
4. Terminating i.e. destroying an applet
1. Applet enters initialization stage when it is loaded from applet tag in a
browser. Browser (or appletviewer) calls a init() method at this stage. Creating and
initializing any global objects which are required throughout the execution of
applet, can be done here. Defining font and colour settings, reading applet
parameters can be done here. init() works only once i.e. when applet is loaded
into browser.
2. Applet goes into running stage after initialization stage. At this stage a start()
method is called by browser. If a web page consisting of an applet is re-visited
then also start() works. Thus, start() method can work multiple times in the
Applet life-cycle. In case of appletviewer applet goes into start or run stage if
the appletviewer window is minimized and maximized again.
3. Applet goes into idle stage when it is stopped. This occurs when you live the webpage consisting of the applet. If you come back to the page again then the
applet goes into start() stage.
4. When a browser window is closed the applet contained in it gets unloaded from
memory. This is also called as destroying an applet. This stage occurs once in
applet lifecycle. If applet has created any resources like threads or any objects,
they can be closed or made null here.
There is one more stage called display or applet painting. This occurs whenever the
applet window is displayed or modified. Here, the paint() method is called by the
browser. Actually, the method works whenever repainting (i.e redrawing) of an applet
is done. This can occur because following,
After applet is started.
If the applet window is covered by other window and then uncovered, the applet
requires repainting. At this stage paint() method works.
If the applet window is resized, applet window has to be repainted.
The life-cycle of an applet is summarized in the following diagram.

Applet class
loaded

Running
stage

start()

init()
stop()

paint()

Display

start()

Applet run from browser

Idle stage

destroy()
Terminated
(applet object
unloaded )

Prepared by, Santosh Kabir.


98
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

10 . Applet & Graphics

OOPM ( Sem III Comp / IT )


Attributes and other tags related to Applet tag:
We use applet tag in an HTML files to specify the applet class and its related
information. The general syntax of Applet tag is as follows:
<APPLET
[ CODEBASE=BASE_URL_OF_APPLET_CLASS ]
CODE=APPLET_CLASS_NAME.class
[ ALT = ALTERNATE_TEXT ]
WIDTH=PIXELS
HEIGHT=PIXELS >
[ <PARAM NAME=PARAMETER_NAME1 VALUE=VALUE1> ]
[ <PARAM NAME=PARAMETER_NAME1 VALUE=VALUE1> ]

[ <PARAM NAME=PARAMETER_NAMEn VALUE=VALUEn> ]


</APPLET>
Code : Specifies the applet class file name. This is case sensitive and must be
mentioned. Only class file name may be mentioned (without extension .class)
Codebase (optional): Specifies the URL of the directory in which the applet class file
resides. If the HTML file (i.e. web page from which applet is loaded) and the applet
class file are in the same directory, then this attribute can be ignored.
Alt (optional) : This is some text regarding the applet. If current browser cant display
the applet then at the place of the applet, this text is displayed. This is specifically
for non-Java browsers.
Width : Specifies the initial width of the applet window (in pixels). Must be
mentioned.
Height : Specifies the initial height of the applet window (in pixels). Must be
mentioned.
Param (Tag): Its a HTML tag which can be enclosed within Applet tag to specify the
user defined parameters to be passed to the applet. The tag specifies parameter
name and its value. e.g. parameter name can be ImgName and value can be test.gif.
(details in next topic )

Passing Parameters to Applets :


We can pass user-defined parameters to an applet using a <param> tag. (see previous
topic). The tag specifies the name of the parameter and its value to be passed to
applet program. The param tag is used with applet tag using following syntax,
<APPLET attributes >
<PARAM NAME=PARAMETER_NAME VALUE= V >
</APPLET>
Here, Parameter_name and V are any user defined name and value.
One can mention multiple parameters with multiple <param> tags
e.g. parameter can be specified as follows,
<param name=backcolour value=yellow>
<param name=length value=25>
Prepared by, Santosh Kabir.
99
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

10 . Applet & Graphics

OOPM ( Sem III Comp / IT )


The parameters passed from an HTML file can be read in applet program using a
method getParameter(), one at time. The method has following general syntax,
String getParameter( String name );
The method returns the value of the specified parameter. It is clear from the above
syntax that the method returns the String value of a parameter (specified as String).
e.g. the above parameter value can be read as follows
String clr = getParameter( backcolor );
The value returned will be yellow.
If you need to read the numeric valued parameters then a conversion method can be used from a
corresponding type-wrapper class.
e.g. to read a second parameter in int type, following statement can be used,

int len = Integer.parseInt( getParameter( length ) );


Usually, the parameters passed from an HTML file are read in init() method of applet.
import java.applet.*;
import java.awt.*;
/*
<applet code=AppReadParams width=400 height=100>
<param name=img value=test.gif>
<param name=fsize value=16>
<param name=msg value= Hello Friends ! >
</applet>
*/
public class AppReadParams extends Applet
{
int size;
String m;
Font f;
public void init( )
{
size = Integer.parseInt( getParameter("fsize") );
m = getParameter( "msg");
f = new Font(Arial , Font.BOLD, size );
}
public void paint(Graphics g)
{
g.setFont( f );
g.drawString( m , 20, 50);
g.setColor(Color.blue);
}
}

This HTML code can be


written in a separate HTML
file.

See reference section to read more about Applet class.

Prepared by, Santosh Kabir.


100
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

10 . Applet & Graphics

OOPM ( Sem III Comp / IT )

Graphics Programming

(Using Graphics class ):

We can draw lines, different shapes of different colours and sizes on applet window. Also, we can
display text of different font and colours on the applet.
To draw these objects on applet we need to use simple co-ordinate system made up of X and Y axis.
The top-left corner of applet window is treated as origin ( X=0 and Y=0). In case of appletviewer, the
drawable area of applet is the area between the applet menu and status bar. This drawbale area of
applet is called Canvas.
java.awt package has a class Graphics (we have used in previous example program) that provides a lot
of methods to draw simple lines to complicated arcs and polygons.

Graphics class:
The class has lots of methods to draw different types of geometrical shapes on the applet window. The
shapes can be drawn with only outline (i.e. edge-only) or can be filled with some colour. All the shapes
are drawn with default color i.e. black. But programmer can set the colour of his choice for each shape.
Also, image can be loaded and displayed with different sizes. All the Graphics methods should specify
the co-ordinates, with the reference of which the shape is drawn. As discussed earlier the top-left
corner of applets drawable area is treated as origin (i.e. x=0 , y=0). The x and y coordinates increment
on right and bottom side of the applet window, as shown example below
Appletviewer
Origin

(0, 0)

Applet
(50, 50)

x-axis

(50, 100)
y-axis
(250, 250)

Applet Started

Following are some of the graphics methods,

Text:
public abstract void drawString(String str, int x, int y)
Draws the text given by the string str at the specified coordinate (x,y), using current
font and colour.

Line :
public void drawLine( int x1, int y1, int x2, int y2 ) :
Draws a line between coordinates (x1, y1) and (x2, y2) in current colour.
Prepared by, Santosh Kabir.
101
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

10 . Applet & Graphics

OOPM ( Sem III Comp / IT )


Rectangle:
public void drawRect( int topleftX, int topleftY, int width, int height)

The method specifies the coordinates for top-left corner and the length and width for
the rectangle. Draws a rectangle (outlined) with a current colour.
public void fillRect( int topleftX, int topleftY, int width, int height)

The method specifies the coordinates for top-left corner and the length and width for
the rectangle. Draws a filled rectangle with current colour.
There are similar methods for different shapes with similar description. These are
described in brief below.

Ellipse and Circle :


Methods to draw an oval shape with outline-only and filled with color are as follows.
public void drawOval( int topleftX, int topleftY, int width, int height);
public void fillOval( int topleftX, int topleftY, int width, int height);
For drawing a circle or ellipse we specify the dimensions for the rectangle that
bounds the required shape.
e.g. drawOval( 50 ,100, 150, 100);
Will draw an ellipse enclosed by a rectangle whose specifications are given by
parameters as follows,
50, 100

100

150

If the width and height of the bounding rectangle is same then the shape drawn will be
a circle.

Arc:
Arcs can be drawn using following methods:
public void drawArc( int topx, int topy, int width, int length, int stAngle, int sweepAngle)
public void fillArc( int topx, int topy, int width, int length, int stAngle, int sweepAngle)
The arc is bounded by the rectangle whose upper left corner is specified by topx and
topy and whose width and height are specified by width and height parameters. The
arc is drawn from stAngle through the angular distance specified by sweepAngle. The
arc is drawn counter-clock wise if sweepAngle is positive value. Both the angles are
in degrees. The positive x-axis side is treated as angle 00.
Following statement will draw an arc starting at an angle 30 0 and the arc angle will
be 1200.
Prepared by, Santosh Kabir.
102
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

10 . Applet & Graphics

OOPM ( Sem III Comp / IT )


drawArc(150, 250, 150, 70, 30, 120);
Arc

150, 250
1200
00

70

150

Polygon:
Polygon of n sides can be drawn by specifying x and y coordinates for its n corners.
The coordinates for the polygon are stored in two arrays of int: one array for x and
the other for y coordinates for respective pints.
General syntax of the method is as follows,
public void drawPolygon( int xPt[ ], int yPt[ ], int n )
Here, xPt is an array of x-co-ordinates of corners and yPt is y-coordinates of corners
of polygon to be draw. Polygon is draw from point ( xPt[0],yPt[0] ) up to
( xPt[n-1], yPt[n-1] ) as last corner.
If the first and last co-ordinates given in arrays are not same then, polygon is
automatically closed joining first and last point. Where n<= size of both arrays. If n is
greater than size of any array then run-time exception will occur.
e.g.

int [ ] xPt = { 50, 150, 250 200, 70 };


int [ ] yPt = { 100, 50, 175, 250, 150 };
drawPolygon( xPt, yPt, 5 );
Here, polygon is drawn strting from coordinates (50, 100) and end on (70, 150) and
joining these two points and closing the polygon.
Following example demonstrates working some these methods.
/* <applet code=AppTest.class height=500 width=500> </applet>
import java.awt.*;
import java.applet.Applet ;
import java.util.*;
public class AppTest extends Applet
{
public void paint(Graphics g)
{
g.drawString( "Graphics with Applets !" , 150,25);
g.drawLine(50,50,200,100); // x1,y1, x2,y2
g.drawRect(50, 150, 100,70); // x,y,w,h
g.fillRect(200,150,70,30);
g.setColor( Color.red);
g.drawArc(50,250,150,70, 30, 200); // x,y,w,h, stAngle, angle
g.drawOval(50,350, 150,50);
g.drawOval(250,350, 100,100);
Prepared by, Santosh Kabir.
103
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

*/

10 . Applet & Graphics

OOPM ( Sem III Comp / IT )


g.setColor( Color.blue);
int []xpt = { 250, 275, 325, 370 };
int []ypt = { 50, 100, 125, 140 };
g.drawPolygon( xpt, ypt, 4);
//g.fillPolygon( xpt, ypt, 4);
g.drawRoundRect(300,150, 150,100,20,20);
g.setColor(Color.green);
g.draw3DRect(250, 270, 100,70, true); // x,y,w,h, raised
showStatus( new Date().toString()) ; // display date in status bar
}
}
Following figure shows the applet window for the above program,

----0000---Prepared by, Santosh Kabir.


104
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

10 . Applet & Graphics

OOPM ( Sem III Comp / IT )

10. Multithreading
Java provides support for writing Multithreaded programs. A multithreaded program consists of

multiple parts of the same program running concurrently (i.e. simultaneously). Here each part of
the program working simultaneously is called a thread, and each thread can work independently. Also
each thread can be performing different task.
e.g. it is possible that a Java program will start and ask for a name of a file to be sent on the network.
Once filename is input, a program goes further for next task. The file sending can be done in the
background using a separate thread and the program will still be doing some different task
simultaneously. It is possible that the program is performing some user input/output and the thread that
is sending file on network has finished its task in the background.
Obviously, a computer i.e. CPU of computer cant perform multiple tasks simultaneously. This is
achieved by sharing a CPU time between these multiple tasks (say A and B). CPU works with task A for
some time (some milli/micro seconds), and then switches to B. CPU does some part of the B in the task
and returns to the first task A and continues from where it had stopped A. This sharig of CPU time
between multiple tasks is called as time-slicing. But, the CPU works at very high speed (e.g. some
hundreds of Mega Hertz) and the switching between the multiple tasks is done in a very small interval
of time. Multiple tasks appear to be going on simultaneously. The user feels like multiple tasks are
performed simultaneously.
Thus it is very clear that multithreading enables you to write very efficient programs that make
maximum use of CPU, because the idle time can be kept to minimum.
Whenever a Java program starts there is one thread that starts working that is a main thread. The
main program that executes from JVM, is the main thread. The main thread should perform following
two tasks in multithreaded programs.
The thread should start multiple threads ( called as child threads ) when required.
The main thread should be the last thread to finish i.e. when main thread is finished program should
terminate. There should not be any thread working when main thread finishes.

Creating a Thread :
For creating a multithreaded program Java provides a class Thread and an interface
Runnable. Using one of or both of these, a new thread can be created using two
different methods.

Extending a Thread class:


The class that has to start a new thread can extend a Thread class of Java. The
Thread class implements Runnable interface and overrides run() method of the
interface. But the run() method of the Thread class is empty method. Other than
run() method the class has several other methods, that can be used for controlling
the working of a thread.
The class that extends Thread overrides a run() method. The code written in run() works as a code
for new thread.
Prepared by, Prof. Santosh Kabir.
105
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

11. Multithreading

OOPM ( Sem III Comp / IT )


The run() method is invoked by start() method of a Thread class and the start()
method class makes arrangements (memory, CPU time etc) and starts a new path of
execution. This is also called as spawning a new thread.
The start() method calls run() on the same object and the run() methods runs like a
separate thread.
The thread (task) terminate when the run() method returns.
class NewThread extends Thread
{
// Some other members
public void run()
{
// Some statements
}
}
In above examples class NewThread works as a new thread class. To start a new
thread, one has to create object of the class and call start() method on it.
e.g.
NewThread th = new NewThread();
th.start(); // this calls run method from NewThread class

Implementing a Runnable interface:


The interface is defined in a package java.lang. The interface has only one method
run(), which is declared as,
public void run( );
The class that has to start a new thread can implement the Runnable interface. The
class is now treated as a thread class.
Obviously, the run() method must be implemented in the class. This run method
works as a new thread.
To start the thread the class has to call a start() method of the Thread class. When a
start method is called the Java virtual machine calls run method on the current
thread class.
The start() method starts a new thread of execution.
e.g.
class NewThread implements Runnable
{
public void run()
{
// Some statements
}
}
In the above example class NewThread works as a thread class, since it implements
a Runnable interface. The run() method is implemented in the class. Now, to run a
new thread, we have to call start() method on the class object that has run()
implemented in it. The object of the Thread class is created, using a constructor that
takes object of a class that implements run(). It is done as follows,
Prepared by, Prof. Santosh Kabir.
106
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

11. Multithreading

OOPM ( Sem III Comp / IT )


NewThread th = new NewThread();
Thread t = new Thread( th ); // th is object from which has run()
t.start(); // Invokes run() on th object i.e. NewThread class
Here, start() calls run() on the object th, which has run() in it.
The, other way to run a thread is to create object of the Thread class in one of the
methods of the class.
NewThread( )
{
Thread t = new Thread( this );
// Some statements
t.start(); // invokes run() on current class object
}
The constructor of the class creates a Thread class object and registers the current
class object (this) with Thread class. Then, the start() method of Thread class is
called. The start() method in-turn calls run() method on the current class object.

Thread Priority :

Thread priority is an int value ranging from 1 to 10 (in the current JDK version).
The priority value 10 is treated as highest priority.
Every thread that is working through Java program is assigned a default
priority of 5. Thus, by default all the threads work with same priority.
Thread priorities decides how Java scheduler will schedule the working of multiple
threads, also the time allotted for a thread to work in each time-slice. The CPU time
allotted for a higher priority thread in each time-slice will be longer than that
for the lower priority thread.
Note: The thread with higher priority does not execute faster than the one with lower priority. Also, if there is a
single thread and is assigned a high priority it wont work faster than normal.
Priority for a thread can be set using a setPriority() method of Thread. The
method has general syntax as follows,
void setPriority( int p )
e.g.
Thread t = new Thread( th );
t.setPriority( 6 );
priority of a thread can be read by using getPriority().
int getPriority( )
Java defines three thread priority constants. They are as follows,
MIN_PRIORITY = 1
MAX_PRIORITY = 10
NORM_PRIORITY = 5
Using above constants one can set priority as follows,
t.setPriority( Thread.NORM_PRIORITY + 2 );
The above statement sets the priority 7 for the thread t.
Priority doesnt define how fast or slow a thread will execute. If a same job is
given to two threads having different priorities, the thread with higher priority
will finish its job first. It is because more attention (CPU time) is given to that
thread than the other.
Prepared by, Prof. Santosh Kabir.
107
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

11. Multithreading

OOPM ( Sem III Comp / IT )

Thread priorities are relational. As an absolute value thread priority is


meaningless.
e.g. a thread with priority 4 will be given more time than a thread with priority
3, but at the same time a thread with priority 9 will get much more CPU time
than that with priority 4.
[ Extra reading ]
According to the priority, switching occurs from one running thread to the other. This is called Context switch. The
rules that decide when a context switch takes place are as follows,
A running thread can relinquish the control on its own: This is done by explicitly yielding, sleeping or blocking the
current thread. Here, all other threads are examined and the highest priority thread that is ready to run is given a
CPU time.
A thread can be preemptied by a higher priority thread : In this case when a higher priority thread needs processor
(CPU) it blocks any running lower priority thread. This is called as Preemptive multitasking.
Note : Context switching is finally done by Operating System. Different O.S can use different rules and procedures
for context switching.
Note : Context switching is finally done by Operating System. Different O.S can use
different rules and procedures for context switching.

Thread class Methods :


Some of the Thread class methods are described below,
Constructors:
Thread() : The empty thread object is created, which is commonly not used in
programs for creating a multithreaded class.
Thread ( Runnable t) : Creates an object of a class that takes, object of a thread
class as argument. The object t specifies the object on which run() is invoked.
Thread ( Runnable t, String name) : Creates an object of a class that takes, object of
a thread class and thread name as arguments. The object t specifies the object on
which run() is invoked. name specifies a name to be set for the new thread.
Thread ( String name) : Creates an object of a class that takes, thread name as
argument. name specifies a name to be set for the new thread.
Methods:
void setName( String name) : Sets a name for this thread. Every new thread is by default

given some name by Java run-time environment. Proramer can set other name by
invoking this method.
String getName( String name) : Returns a name for this thread.
void setPriority() , int getPriority() : Discussed in topic Thread priority.
Prepared by, Prof. Santosh Kabir.
108
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

11. Multithreading

OOPM ( Sem III Comp / IT )


static Thread currentThread() : Returns a reference to the currently executing thread
object. The method can be used in a following manner.
Thread t = Thread.currentThread();
System.out.println("Thread info:" + t);
t.setName("My Program");
The first statement gets a reference for an object of a current thread. Then, the
information about the thread is displayed. When a thread object is displayed (its
toString() method is called), it outputs the thread name, thread priority and a thread
group.
The typical output for a main thread will be,
Thread info: Thread[main,5,main]
The third statement sets a new name for the thread as My Program.
static void sleep( long ms) : Causes the currently executing thread to sleep (
temporarily pause) for specified number of milliseconds. But thread will not loose the
ownership of a monitor. Throws InterruptedException if it is interrupted by some
other thread. The other threads can (if waiting) work during this interval.
boolean isAlive() : Checks whether this thread is alive. (i.e. not stopped). Returns true
if the thread is alive.
void join() : The method blocks (waits) for this thread to terminate. It throws
InterruptedException.
e.g. if a method is called on a Thread object t, through main thread, then main
thread waits (at the statement where join() is called ) for the thread t to terminate.
One can write following code to make current thread wait, till its child threads (th1
and th2) finish.
try
{
th1.join();
th2.join();
}catch(Exception ex)
{ //empty
}
System.out.println("After join ..th1 working:" + th1.isAlive());
System.out.println("th2 working:" + th2.isAlive());
In this example, both the isAlive() methods will return false.

Thread Synchronization :

(Why required : ) There can be multiple threads working at a time in a Java


program. If these threads need access to some shared resource (e.g. a disk
file, database table or a global data-block like array, variable or object),
programmer needs to provide some way to ensure that the resource will be
used by one thread at a time. When one thread is using a resource, because

Prepared by, Prof. Santosh Kabir.


109
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

11. Multithreading

OOPM ( Sem III Comp / IT )


of contextswitching, any other thread that wants to use the same resource
should be made to wait till this thread finishes its work. If this is not done the
process started by the current thread may remain incomplete and data will
remain semi-processed or in intermediate state, and the other thread will
work with this semi-processed resource.
Thus, care must be taken so that, Multiple threads dont access the same resource at a
time, i.e. till one thread has finished its work, the other thread should not get access to
this shared resource. The process by which this is achieved is called as Synchronization.
Java provides a keyword synchronized, that is used to achieve synchronization
between multiple threads. There are two ways to do this,

1) Synchronized method:

The methods that use same resource can be marked by a keyword


synchronized.
For example, one can define update() and display() methods that are working on
same shared resource, as follows,
synchronized void update()
{
// Some statements to process data
}
synchronized void display()
{
// Some statements to display data
}
In a multithreaded program, when one thread invokes a synchronized
method, Java creates an object called as Monitor (also called as Semaphore)
and the thread acquires a lock on it.
We say that the thread has entered into a monitor. As long as the thread
holds the monitor, no other thread can enter the monitor. And the other
threads are said to be waiting for the monitor.
Other threads cant invoke any synchronized method on the same instance till
the current method has returned. When a synchronized method finishes, the
other thread that is waiting for the monitor can enter into a monitor.
Thus, one method called by one thread will work fully and then only the
resources can be accessed by another thread.

2) Synchronized statements (Synchronized blocks):

The other method to achieve synchronization is to declare block of code as


synchronized as shown below,
synchronized (object )
{
// statements to be synchronized
}
Here, the object represents the reference to the object being synchronized. A
synchronized block ensures that a call to a method that is member of object
occurs only after the current thread has successfully entered the monitor.
This method is commonly used when we are using a class which we have not
written i.e. it can be a pre-defined class or a Java built-in class. In such case

Prepared by, Prof. Santosh Kabir.


110
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

11. Multithreading

OOPM ( Sem III Comp / IT )


we dont know whether the methods defined inside the class are synchronized
or not.
e.g. Say the class MyArray is a pre-written class and we dont know whether
the two methods update() and display() are defined synchronized. The call to
any of these methods can be put into synchronized block as follows,
synchronized ( obj )
{
obj.update();
}
Where obj is reference for object of MyArray. Now, till update() has finished
(returned) no other method (e.g. display() ) can be called on the same object obj.

Java Methods for synchronization :


Java provides three methods which makes synchronization of threads more elegant.
The methods are present in Object class and hence are members of all the Java
claases and user defined classes. The methods are,
void wait() : Causes a current thread to give up the monitor (object) and wait until
another thread acquires a monitor and calls either notify() or notifyAll() method. The
common use of wait() method is as follows,
synchronized type method( parameters )
{
// Some statements
wait( ) ;
// Some statements
}
void notify() : Wakes up a single thread that is waiting on this monitor (object). If there
are multiple threads waiting for access to the monitor, only one of them will be
chosen for waking up. The choice doesnt depend upon particular privilege or
predefined precedence. Normally higer priority thread is picked up to run.
void notifyAll() : Wakes up all the threads that are waiting on this monitor. If there are
multiple threads waiting for access to the monitor, any one thread will be chosen for
waking up. The choice doesnt depend upon particular privilege or predefined
precedence.
Above three methods are defined in Object class of Java.

Stopping and blocking a thread:


A thread automatically stops when it reaches the end of run() method. This state is
called dead state of a thread. A thread can be stoped anytime by invoking a method
stop() on the thread object. The call to this method also causes the thread to move to
dead state.

Prepared by, Prof. Santosh Kabir.


111
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

11. Multithreading

OOPM ( Sem III Comp / IT )


Blocking a thread:
A thread that is running can be temporarily blocked or suspended using following
methods like sleep(), suspend() and yiels().
void suspend() : This thread (if alive) is suspended and makes no further progress till it
is resumed again. If any resource is locked by the thread then it will remain locked
until this thread is resumed again. This can lead to deadlock condition.
void yield() : Causes the currently executing thread object to temporarily pause and
allow other threads to execute. The thread does not loose ownership of any monitors
(i.e. objects).
void sleep( long ms) : Causes currently executing thread to temporarily pause for
specified number of milli seconds. The thread will become active after specified
interval. The method throws InterruptedException if any other interrupts the thread.
void resume() : The method is used to resume a suspended thread only. If this thread
is alive and suspended it will be resumed and allowed to make further progress.

Thread Lifecycle :
Thread can go through many different states during its life-time. The states are
newborn, runnable, running, blocked and dead.

Newborn state: When a new Thread object is created the thread is born and is said to
be in newborn state. From here either thread can be given to scheduler (by calling
start() method) to schedule it for running or can be killed by calling stop method.
From Java point of view the thread is not alive yet.

Active state : Once start() method is invoke and run() starts execution, the thread
enters into Active state. In active state the thread can be in two different states, as
follows,
Runnable state : This state means thread is ready to run and is waiting for availability of CPU.
The thread has now joined thread queue that are waiting for execution. The threads
are scheduled by default on first-come-first-serve basis.
Running state: Running state stands for currently CPU has given a time for the thread.
After thread works for some time context switching will occur and this thread will go
into runnable state.
From Active state thread can relinquish itself or can be forced to do so by high
priority thread.
Blocked state: The thread is said to be blocked when it is prevented from entering into
the runnable state.
Thread can be temporarily stopped from executing by invoking suspend method.
Here, purpose is not to kill the thread but suspend the working of the thread for
some time. Thread can be made to sleep for some interval by calling sleep method.
The thread goes out of the thread queue for that interval, and re-enters the runnable
state after that interval.
Prepared by, Prof. Santosh Kabir.
112
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

11. Multithreading

OOPM ( Sem III Comp / IT )


The thread can be made to wait by calling wait() method and will be scheduled to
run again when other thread calls notify() or notifyAll().
This is done by calling suspend, sleep or wait method.
Dead state: Thread ends when the run() method terminates. The thread is said to be
dead.
The thread can be moved to dead state by calling stop() method also.
A dead thread can Not be restarted.
Figure for thread life-cycle is shown on next page,

Newborn

New thread

stop()

start()

stop()
Running

Dead

Runnable
Killed
thread

Active
thread

suspend()
sleep()
wait()

resume()
notify()
notifyAll()

stop()

Blocked
Idle thread

Thread Life-Cycle
In JVM there are two types of threads : Deamon, and Non-deamon thread. Deamon
threads are the threads used by JVM such as thread that performs Garbage
collection.
A thread that starts with main() method is a non-deamon thread. When all non-

daemon threads of a Java application terminate, the virtual machine instance will exit.
----0000----

Prepared by, Prof. Santosh Kabir.


113
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

11. Multithreading

OOPM ( Sem III Comp / IT )

Subjects Conducted by Santosh Kabir.


Semester Branch
FE Sem I

Subject
--

S.P.A.
FE Sem II

[ Structured Programming Approach ]


Programming with C.. Very important subject for Comp/IT students
and
for those who are interested in making career in I.T.

DSAA
[ Data Structures and Algo. Analysis ]
Lots of programming with Arrays, Pointers and structures.
SE Sem III [IT]

OOPM
[ Object Oriented Programming Methodology ]
Learn Object Oriented Prog with Java, with features like Exception
handling, Applets and Multithreading

DS
SE Sem III
[Comp]

[ Data Structures ]
Lots of programming with Arrays, Pointers and structures.

OOPM
(OOP with Java)

W.P.
SE Sem IV [IT]

SE Sem VI [IT]

[ Web Programming ]
(HTML, JavaScript,C#, ASP.Net,ADO.Net, PHP, JSP etc)
Want to develop your Web Site (Yahoo, facebook ..!)..
Learn the subject seriously
If you are learning with me ... hw abt dvlping mini fb
PMRC (Old syllabus)

Regular and Vacation batches are taken at Andheri , Dadar, Thane, Dombivli.
( Demo. of programs on Projector )

Mobile : 98336 29398. Visit : www.santoshkabirsir.com

Prepared by, Prof. Santosh Kabir.


114
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

11. Multithreading

Reference Section.
String class :
int length() : Returns length of a string i.e. number of characters in a string.
char charAt( int index) : Returns a character located at a specified index. ( index starts with 0. i.e.
index of first character is 0 and last character has an index length -1.

char [ ] toCharArray( ) : Allocate a new char array whose length is the length of this string and whose
contents are initialized to contain the character sequence represented by this string.

String [ ] split(String token) : Decomposes the invoking string into parts and returns an array that
contains the result. Each part is delimited by the token passed as string parameter.

void getChars(int srcBegin, int srcEnd, char[ ] dst, int dstBegin):


Copies characters from this string into the destination character array. The first character to
be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the
total number of characters to be copied is srcEnd-srcBegin). The characters are copied into
the subarray of dst starting at index dstBegin

String substring ( int begIndex ) : Returns a new string that is a substring of this string. The substring
begins with the character at the specified begIndex and extends to the end of this string.
"unhappy".substring(2) returns "happy"
"emptiness".substring(9) returns "" (an empty string)

String substring( int beginIndex, int endIndex ): Returns a new string that is a substring of this
string. The substring begins at the specified beginIndex and extends to the character at index endIndex
- 1. Thus the length of the substring is endIndex-beginIndex.
e.g. "hamburger".substring(4, 8) returns "urge"

static String valueOf( int v ) : Return string representation of a specified int value.
The representation is exactly the one returned by the Integer.toString( ) method with one argument.
This, method works for byte and short data types, also.
This method is overloaded to work with all primitive data types of (except for byte and short), for char
array and for Object.
e.g. for double it is used as follows,

static String valueOf( double d ) : Returns the string representation of the double argument.
int indexOf( int ch ) : Returns the index of the first occurrence of the specified character within this
string. Returns -1 if character does not occur.

int indexOf(int ch, int fromIndex) : Returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index. If a character is not found at or after the
specified index then method returns -1.
Prepared by, Prof. Santosh Kabir.
115
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

int lastIndexOf(int ch): Returns the index of the last occurrence of the specified character within this
string. The String is searched backwards starting at the last character. Returns -1 if character not found.

int lastIndexOf( int ch, int fromIndex ) : Returns the index of the specified character within this string
of the last occurrence, searching backward starting at the specified index. If fromIndex is greater than
or equal to the length of this string then searching will start from last character of a string.
Following indexOf methods work similar to above methods for String argument.

int indexOf(String str) : Returns the index within this string of the first occurrence of the specified
substring.

int indexOf(String str, int fromIndex) : Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.
int lastIndexOf(String str) : Returns the index within this string of the rightmost occurrence of the
specified substring.

int lastIndexOf(String str, int fromIndex) : Returns the index within this string of the last occurrence
of the specified substring, searching backward starting at the specified index.

Methods to get modified string :


These methods operate on a current string object and return modified string. Current string is not
modified.

String toLowerCase( ): Returns a string with all the alphabets of the current string converted to lower
case. Other characters are unaffected.
String toUpperCase( ): Returns a string with all the alphabets of the current string converted to upper
case. Other characters are unaffected.

String trim( ) : Returns a string with all leading and trailing whitespaces removed from the current
string. Whitespaces are spaces, tab character, line feed.

String concate( String s ) : Concatenates a given string i.e. s to the current string and returns the
new string.

String replace( char oldChar , char newChar) : Returns a new string resulting from replacing all the
occurrences of old character by character newChar.

String Compare methods :


boolean equals(Object obj) : Compares this string to the specified object. The result is true if and only
if the argument obj is not null and is a String object that represents the same sequence of characters as
this object.

Prepared by, Prof. Santosh Kabir.


116
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

boolean equalsIgnoreCase( String str ) : Compares this String to str, ignoring case considerations.
Two strings are considered equal ignoring case if they are of the same length, and corresponding
characters in the two strings are equal ignoring case.

boolean startsWith( String s) : Returns true if a current string starts with the string s else returns
false.

boolean endsWith( String s) : Returns true if a current string ends with the string s else returns false.
int compareTo( String str) : The characters in current string object and those in argument str are
compared to return an integer that indicate which string object is greater than the other alphabetically.
If both strings are identical (length and characters are same) returns 0.
If current string Unicode wise or ASCII code wise precedes the argument then returns ve int, else
returns positive int value. The method compares each corresponding character (starting from index 0)
in the two strings. When the first mismatch is found stops the comparison and returns the difference
between the Unicode values.

int compareToIgnoreCase( String str ) : Compares two strings in the way described in previous
method ignoring the case considerations.
Following example program demonstrates the working of string methods:

class StringOper
{
public static void main(String[]args)
{
char a[ ] = new char[20];
String s1 = "Welcome : Strings in Java";
String s2= "Hello";
System.out.println("s1=" + s1 + ", s2=" + s2 );
System.out.println("Length of s1=" + s1.length() );
String []sa = s1.split( ); // split the string at space
System.out.println("Split string at spaces);
for( int j=0; j < sa.length(); j++)
System.out.println( sa[j] );
System.out.println("s1 Upper case=" + s1.toUpperCase() );
System.out.println("s1 Lower case=" + s1.toLowerCase() );
System.out.println("Same=" + s2.equals("hello") );
System.out.println("Same=" + s2.equalsIgnoreCase("hello") );
// String methods are by-default case sensitive
System.out.println("s1 starts with Wel : " + s1.startsWith("Wel") );
System.out.println("s1 starts with WEL : " + s1.startsWith("WEL") );
// if string or char not found then returns -1
System.out.println("- come - is at pos:=" + s1.indexOf("come") );
System.out.println("- CoMe - is at pos:=" + s1.indexOf("CoMe") );
String p = "ABCDBEFBMNBADBVD";
System.out.println("char. at pos 5 = " + p.charAt( 5 ));
System.out.println("String p =" + p);
System.out.println("B first occurs at :" + p.indexOf("B" ) );
// no exptn for index out of string limit
Prepared by, Prof. Santosh Kabir.
117
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

System.out.println("B occurs after pos 5 at :" + p.indexOf("B", 5 ) );


System.out.println("last occurrence of B :" + p.lastIndexOf("B") );
System.out.println("last occurrence of B before 8 :"
+ p.lastIndexOf("B" , 8) );
// if any index is out of string size : runtime error occurs
System.out.println("Substring of p - 2 to 6...:" +
p.substring(2,6)); // excludes last index
System.out.println("Substring from 5 =" + p.substring(5) );
System.out.println("First string s1 is: "
+ (s1.compareTo(s2) < 0 ? "smaller" : "greater") );
String s4 = s1.replace('e' , 'a');
System.out.println("e Changed to a :s4 :" + s4);
a = s2.toCharArray(); // Read chars from s2 into char array
// s2.getChars(0, s2.length() ,a, 0); // Equivalent to above line
System.out.println("chars. in s2:");
for(int i=0; i<s2.length(); i++)
System.out.println(a[ i ] );
// Creating string buffer from string
StringBuffer bfr = new StringBuffer(s2);
bfr.setCharAt(3, 'k'); // Buffer contents are modified
System.out.println("new buffer=" + bfr);
}
}
Output:
s1=Welcome : Strings in Java, s2=Hello
Length of s1=25
Split string at spaces
Welcome
:
Strings
In
Java
s1 Upper case=WELCOME : STRINGS IN JAVA
s1 Lower case=welcome : strings in java
Same=false
Same=true
s1 starts with Wel : true
s1 starts with WEL : false
- come - is at pos:= 3
- CoMe - is at pos:= -1
char. at pos 5 = E
String p =ABCDBEFBMNBADBVD
B first occurs at :1
B occurs after pos 5 at :7
last occurance of B :13
last occurance of B before 8 :7
Substring of p - 2 to 6...:CDBE
Substring from 5 =EFBMNBADBVD
Prepared by, Prof. Santosh Kabir.
118
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

First string s1 is: greater


e Changed to a :s4 :Walcoma : Strings in Java
chars. in s2:
H
e
l
l
o
new buffer=Helko

Math class :
Fields:
E: static double E: Constant with value that represents base for natural logarithm. Approximately equal
to 2.72
PI : static double PI : Constant with value representing mathematical constant

pi.

Approximately equal to 3.14

Some Methods:
1. static int abs ( int val ) : Returns absolute value of the specified int val. If the parameter val is
positive then return same value. It is overloaded for double, float, long
Similar methods are.
2. static double abs ( double val )
3. static float abs ( float val )
4. static long abs( long val )
5. static double cos (double a ) : Return the trigonometric cosine of an angle. If the argument is
Not a number (NaN) or an infinity, then the result is NaN. Parameter a is an angle, in radians.
Similar methods are
6. static double sin (double a ) :
7. static double tan (double a ) :
8. static double acos(double a ) : Returns the arc cosine of a value; the returned angle is in the
range 0.0 through pi. If the argument is NaN or its absolute value is greater than 1, then the
result is NaN.
Similar methods are:
9.

static double asin (double a) : Returns the arc sine of a value; the returned angle is in the rangepi/2 through pi. If the argument is NaN or its absolute value is greater than 1, then the result is NaN.
If the argument is zero, then the result is a zero with the same sign as the argument.

10. static double atan(double a) : Returns the arc tangent of a value; the returned angle is in the range
(-pi/2) through (pi/2). If the argument is NaN, then the result is NaN. If the argument is zero, then
the result is a zero with the same sign as the argument.
11. static double cosh (double x) : Return the hyperbolic cosine of a double value. The hyperbolic
x

-x

cosine of x is defined to be (e + e ) / 2 where e is Eulers number. If the argument is NaN, then


Prepared by, Prof. Santosh Kabir.
119
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

the result is NaN. If the argument is infinite, then the result is positive infinity. If the argument is
zero, then the result is 1.0
12. static double cosh (double x) : Returns hyperbolic sine of x.
13. static

double

tanh

(double

14. static

double

cbrt

(double

val

15. static

double

sqrt

(double

val

16. static

double

log

double

val

x)
)
)
)

:
:

Returns

Returns

hyperbolic

sine

of

x.

cube-root

of

the

parameter

val.

of

the

parameter

val.

the

parameter

val.

Returns

square-root

Returns

natural

log

of

17. static double log10 ( double val ) :Returns log to the base 10 of the parameter val.
y

18. static double pow ( double x, double y ) :Returns x raised to the power y, i.e. x .
19. static double ceil(double val ) : Return the smallest whole number greater than or equal to the
parameter val.
e.g. ceil (2.8) will give 3, ceil (7.25) will give 8, and ceil (-3.25) will give -3
20. static double floor ( double val ) : Return the largest whole number less than or equal to the
parameter val .
e.g. floor(2.8) will give 2, floor(7.25) will give 7, and floor(-3.25) will give -4
21. static int round (float val) : Returns the closest int to the argument. The result is rounded to an
integer by adding , taking yhe floor of the result, and casting the result to type int. In other words,
the

result

is

equal

to

the

value

of

the

expression:

( int ) Math . floor ( val + 0.5f)


22. static double toDegrees ( double rad) : Converts the angle measured in degree into an
approximately equivalent angle in radians.
23. static double toRadians ( double deg) :

Converts the angle measured in degree into an

approximately equivalent angle in radians.

Vector class :
The constructors of Vector are as follows,
Vector( )
Constructs an empty vector so that its internal data
array has size 10
Vector(int capacity)
Vector(int capacity, int incr)

Vector(Collection c)

Constructs an empty vector with the specified initial


capacity
Constructs an empty vector with the specified initial
capacity and capacity increment.
Constructs a vector containing the elements of the
specified collection. Throws NullPointerException if
the specified collection is null.

Prepared by, Prof. Santosh Kabir.


120
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

In addition to the methods implemented from a List interface Vector class has some additional methods
also. Most commonly used methods are described below.

Method

Description

void add( int index,


Object element) *

The Method inserts a specified element at a specified position


in the Vector object.

int capacity( ) *

Returns the capacity of the vector.

Object clone( )
boolean contains(Object element)*

Returns a duplicate of the invoking vector.


Returns true if element is contained by the vector,
and returns false if it is not.
The elements contained in the invoking vector are
copied into the array specified by array.

void copyInto(Object array[ ])

Object elementAt(int index) *

Returns the element at the location specified by


index.

Enumeration elements( )

Returns an enumeration of the elements in the


vector.

void ensureCapacity(int size)

Sets the minimum capacity of the vector to size.

Object firstElement( )

Returns the first element in the vector.

int indexOf(Object element)

Returns the index of the first occurrence of


element. If the object is not in the vector, 1 is
returned.

int indexOf(Object element, int start)


Returns the index of the first occurrence of element
at or after start. If the object is not in that portion
of the vector, 1 is returned.
void insertElementAt(Object element, int index)
Adds element to the vector at the location specified
by index.
boolean isEmpty( ) *
Returns true if the
vector is empty and returns
false if it contains one or more elements.
Object lastElement( )

Returns the last element in the vector.

int lastIndexOf(Object element)

Returns the index of the last occurrence of element.


If the object is not in the vector, 1 is returned.

int lastIndexOf(Object element, int start) Returns the index of the last
occurrence of element
before start.If the object is not in that portion of the
vector, 1 is returned.
void removeAllElements( )

Empties the vector. After this method executes, the


size of the vector is zero.

boolean removeElement(Object element) *


Removes element from the vector. If more than one
Prepared by, Prof. Santosh Kabir.
121
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

instance of the specified object exists in the vector,


then it is the first one that is removed. Returns
true if successful and false if the object is not
found.
void removeElementAt(int index)*

Removes the element at the location specified by


index.
void setElementAt(Object element, int index) * The location specified by index is
assigned element
void setSize(int size)

int size( ) *
String toString( )
void trimToSize( )

Sets the number of elements in the vector to size. If


the new size is less than the old size, elements are
lost. If the new size is larger than the old size, null
elements are added.
Returns the number of elements currently in the
vector.
Returns the string equivalent of the vector.
Sets the vectors capacity equal to the number of
elements that it currently holds.

( In exam. For Short notes on Vector mention the methods marked with * )
Consider a following example to understand working of basic features of Vector class,

import java.util.*;
class VectorDemo1
{
public static void main(String[ ] args)
{
Vector v = new Vector(4, 3);
//Initial cap=4, and capacity increment=3

System.out.println("Size=" + v.size() + " Cap=" + v.capacity());


// Add 8 elements into the vector

for(float i=50; i<=57; i++)


{
v.add( i );
System.out.print("...Size="+v.size() + " Cap=" + v.capacity());
}
System.out.println("\n Vector :" + v);
v.setElementAt(new Integer(25), 3 );
v.remove( 6 );
System.out.println("Vector :" + v);
System.out.println("Size=" + v.size() + " Cap=" + v.capacity());
System.out.println("Contains 55 : " + v.contains(new Float(55)));
v.add( 5, 5555); // add at end or in the list
System.out.println("Vector :" + v );
v.ensureCapacity(5); // ignored
System.out.println("Size=" + v.size() + " Cap=" + v.capacity());
}
}
Prepared by, Prof. Santosh Kabir.
122
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

Output :
Size=0 Cap=4
...Size=1
Cap=4...Size=2
Cap=4...Size=3
Cap=4...Size=4
Cap=7...Size=6 Cap=7...Size=7 Cap=7...Size=8 Cap=10
Vector :[50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0]
Vector :[50.0, 51.0, 52.0, 25, 54.0, 55.0, 57.0]
Size=7 Cap=10
Contains 55 : true
Vector :[50.0, 51.0, 52.0, 25, 54.0, 5555, 55.0, 57.0]
Size=8 Cap=10

Cap=4...Size=5

Applet class methods:


Some of the commonly used methods defined in the class are described below.
public void start( )
Called by the browser or appletviewer to inform this applet that it should start its execution. It is called
after the init method and each time the applet is revisited in a Web page.
A subclass of Applet should override this method if it has any operation that it wants to perform each
time the Web page containing it is visited. For example, an applet with animation might want to use the
start method to resume animation, and the stop method to suspend the animation.

public void stop( )


Called by the browser or appletviewer to inform this applet that it should stop its execution. It is called
when the Web page that contains this applet has been replaced by another page, and also just before
the applet is to be destroyed.
A subclass of Applet should override this method if it has any operation that it wants to perform each
time the Web page containing it is no longer visible. For example, an applet with animation might want
to use the start method to resume animation, and the stop method to suspend the animation.
The implementation of this method provided by the Applet class does nothing.

public void destroy( )


Called by the browser or appletviewer to inform this applet that it is being reclaimed and that it should
destroy any resources that it has allocated. The stop method will always be called before destroy.
A subclass of Applet should override this method if it has any operation that it wants to perform before it
is destroyed. For example, an applet with threads would use the init method to create the threads and
the destroy method to kill them.
The implementation of this method provided by the Applet class does nothing.

public void init( )


Called by the browser or appletviewer to inform this applet that it has been loaded into the system. It is
always called before the first time that the start method is called.
A subclass of Applet should override this method if it has initialization to perform. For example, an
applet with threads would use the init method to create the threads and the destroy method to kill them.
The implementation of this method provided by the Applet class does nothing.

public Image getImage(URL url)


Prepared by, Prof. Santosh Kabir.
123
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

Returns an Image object that can then be painted on the screen. The url that is passed as an argument
must specify an absolute URL.

public Image getImage(URL url, String name)


Returns an Image object that can then be painted on the screen. The url argument must specify an
absolute URL. The name argument is a specifier that is relative to the url argument. In simple words url
specifies the directory from which to read an image, and the name argument specifies name of the
image file.

public void showStatus(String msg)


Displays the argument string in the "status window" part of browser or appletviewer. Many browsers
and applet viewers provide such a window, where the application can inform users of its current state.
We can also use this method to show any run-time error.
e.g.
showSatus( Error : Image file not loaded);
This message will appear in the status-bar of the browser.

public void resize(int width, int height)


Requests the browser to resize the applet window to specified width and height.

public String getParameter( String name)


Returns the value of the named parameter in the HTML tag. (refer previous topic)
For understanding the working of following two methods, lets assume that we have stored a Java file for
applet named Ap1.java in a following folder
d:\Myprog\applet_test
Also assume that the Java file holds the Applet tag to run the applet.

public URL getCodeBase()


Gets the base URL. This is the URL of the directory which contains this applet.
e.g. file:/d:/Myprog/applet_test

public URL getDocumentBase()


Gets the URL of the document in which this applet is embedded.
e.g. file:/d:/Myprog/applet_test/Ap1.java

public AudioClip getAudioClip(URL url)


Returns the AudioClip object specified by the URL argument.

public AudioClip getAudioClip(URL url, String name)


Returns the AudioClip object specified by the URL and name arguments.
This method always returns immediately, whether or not the audio clip exists. When this applet
attempts to play the audio clip, the data will be loaded.
Parameters:
url - an absolute URL giving the base location of the audio clip.
name - the location of the audio clip, relative to the url argument.

Prepared by, Prof. Santosh Kabir.


124
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

Graphics class methods :


public void draw3DRect( int topleftX, int topleftY, int width, int height, boolean raised)
The method specifies the coordinates for top-left corner and the length and width for the rectangle.
Draws a rectangle with current colour. If the last parameter (raised) is true then the edges are
highlighted in such way that it looks lit from top left corner and a thin shadow on right and bottom edge
of a rectangle.
public void fill3DRect( int topleftX, int topleftY, int width, int height, boolean raised)
The method specifies the coordinates for top-left corner and the length and width for the rectangle.
Draws a filled rectangle with current colour. If the last parameter (raised) is true then the edges are
highlighted in such way that it looks lit from top left corner and a thin shadow on right and bottom edge
of a rectangle.
public void drawRoundRect(int topleftX, int topleftY, int width, int height, int arcWidth, int arcHeight)
Draws a rectangle with curved (rounded) corners. The last two parameters specify the width and height
of the arc joining the adjacent sides of rectangle. Draws only outlines with current color.
public void fillRoundRect(int topleftX, int topleftY, int width, int height, int arcWidth, int arcHeight)
Draws a rectangle with curved (rounded) corners. The last two parameters specify the width and height
of the arc joining the adjacent sides of rectangle. Draws filled rectangle with current color.
========================

Prepared by, Prof. Santosh Kabir.


125
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Reference section

University Question Papers ( Old CP-2 )


June - 2008
N.B.
1. Question NO.1 is compulsory.
2. Attempt any four questions from remaining six questions.
3. Assumptions made should be clearly stated.
4. Answers to questions should be grouped and written together, i,e. all answers to sub questions of
individual questions like 01, 02, 03 etc. should be answered one below other.
5. All computer programs and program segment only in JAVA.
1. (a) Explain Applets in JAVA in terms of the following :-

10

(i) Creating an executable Applet


(ii) Designing a Web page which references an Applet
(iii) Adding Applets to HTML File
(iv) Running the Applet .
(v) The Basic Applet Life Cycle, init(), start(), stop(), and destroy()
(b) Write Object Oriented programs in JAVA to exemplify different types of visibility modifiers

10

namely
(i) public
(ii) protected
(iii) private
(iv)

private protected

(v) friendly (default)


2. (a) Write an object Oriented Program in JAVA that uses Euclid's Algorithm to display the greatest 10
common divisor of two integers. The greatest common divisor of two numbers is the largest
number that divides into both numbers. Here is how the algorithm works?
(i) Find the remainder after dividing the larger number by the smaller number, using the modulus
operator.
(ii) Change the larger number to the smaller number and change the smaller number to the
remainder from step (i)
(iii) Keep doing this until the remainder is zero
Incorporate member functions for data input, displaying the result, default constructor and
constructors with two parameters. Also create objects to reference the member functions.
(b) Develop a JAVA program that determines the number of days in a given semester. Input

10

to the program is the year, month, and day information of the first and the last days of a
semester. The program should accept the date information as a single string instead.of accepting
the year, month and day information separately. The input string must be in the
MM/DD/YYYY format.
3. (a) Write a JAVA program to compute the distances S fallen by an object in freefall.

10

The formula is
2
S = S0 + vt + at
Make a table of S for t = 1, 5, 10, 15, 2Q . . . . . . 100.
(b) Write an object oriented program to arrange the names of students in descending order
Prepared by, Prof. Santosh Kabir.
126
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

MU Exam Papers

10

of their total marks, input data consists of student details such as name, ID.no, Marks of
Mathematics, Physics, Chemistry. Use array of objects.
4. With the help of suitable JAVA programs describe following:

20

(i) Over loading functions


(ii) Overriding functions
(iii) Final methods and classes
(iv) Abstract methods and classes
(v) finalize( ) method.
5. (a) Write detailed note on Exception handling in JAVA in terms of following :-

10

(i) Try-catch
(ii) The finally keyword
(iii) Catching multiple exceptions
(iv) The throws keyword. Throwing Exception.
(b)

With the help of suitable program explain Multithreaded programming in terms of

10

following: .
(i) Creating threads, extending the thread class
(ii) Stopping and blocking a thread
(iii) Lifecycle of a thread.
6. interface Matrix

20

{
final static int M=5, N=5; //Matrix indices
void readMatrix( ); //Read a Matrix
void displayMatrix( );//Display a Matrix
void addMatrix( ); /I/ Add two Matrix
void multMatrix(); //Multiply two matrix.
void transposeMatrix( ); // Transpose of Matrix
}
implement the above interface using a suitable JAVA class program and also develop
the main program.
7. Write notes on the following with the. help of suitable program segments in JAVA:
(a) Vectors
(b) Strings
(c) Packages
(d) Interfaces
-------------------

Dec. 2008
N. B.: (1) Question NO.1 is compulsory.
(2) Attempt any four questions out of remaining six questions.
(3) Assumptions made should be clearly stated.
(4) All computer programs and program segment only in Java.
Prepared by, Prof. Santosh Kabir.
127
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

MU Exam Papers

20

1. (a) Explain life cycle of a thread.

(b) Write a program in Java to find nCr and nPr.

(c) Explain JVM in brief.


(d) Write a program to determine the sum of the series for a given value of n.
1 + + 1/3

+ + + 1/n

2. (a) Compare and contrast overriding method and overloading method with suitable examples.

10

(b) Write a program in java for fitting a straight line through a set of points (Xi, Yi) , i = 1, 2,.. n. 10
The straight line equation is Y = mx + c and the values of m and c are given by
n (Xi Yi) - ( xi) ( Yi)
m = -----------------------------------------2
2
n ( xi ) - ( Yi)
C = 1/n ( yi m xi)
3. (a) Write a program to display the following menus and submenus.

12

Menu Demo
File

Edit

View

Undu
Cut
Copy
Paste

(b) Explain different types of inheritance with suitable examples.

4. (a) What is vector? How it is different from an array?


(b) What are the applications of wrapper classes?
(c) Assume that a bank maintains two kind of account for its customers. The saving account

10

provides compound interest and withdrawal facilities but no cheque book facility. The current
account provides cheque book facility but no interest. Current account holders should also
maintain a minimum balance and if the balance falls below this level, a service charge is
imposed. Create a class account that stores customer name, account number and type of
account. From this derive the classes current-acct and saving-acct to make them more
specific to their requirements. Include the necessary methods in order to achieve the
following tasks: .
(i) Accept deposit from a customer and update the balance.
(ii) Display the balance.
(iii) Compute and deposit interest
(iv) Permit withdrawal and update the balance
(vi)

Check for the minimum balance, impose penalty, if necessary, and update the balance.

5. (a) Explain Java Exception Handling with different examples.

10

(b) Write a program to create multiple threads.

(c) Write a program to check whether given string is palindrome or not.

Prepared by, Prof. Santosh Kabir.


128
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

MU Exam Papers

6. (a) How do you add a class or an interface to a package? Explain with examples.

10

(b) Will the code compile? if not, why? if yes, write output.

(i) import circle;


class Import Class
{
public static void main (String [ ] args)
{
circle. NewCircle nc = new circle.NewCircle ( ) ;
System.out.println (" Hellow World! ") ;
}
}
(ii) int m = 10;
int n = 7;
while ( m % n > = 0)
{
m=m+1;
n = n + 2;
}
(c) Explain Type Conversion and Type Casting in Java with examples.

7. Write short notes on (any four) :-

20

(a) HTML Applet Tags


(b) Parameter Passing to Applets
(c) Abstract Methods and Classes
(d) Features of Java
(e) Synchronization
(f) String Methods.
---------------

June 2009
N. B.: (1) Question No.1 is compulsory.

(2) Attempt any four questions out of remaining six questions.


(3) Answer to sub questions of individual questions should be answered one below the other.
1. (a) Write short note on

10

(i) JVM (Java Virtual Machine)


(ii) JDK (Java Development Kit)
(b) Write a program to accept any string up to 15 characters. Display the elements of string with their
element nos. Use toCharArray ( ) function.

10

2. (a) What is a package? How do we design a package? What are the benefits of packages?
(b) The annual examination results of 5 students are tabulated as follows :Roll No

Subject1

Subject2

10

Subject3

Prepared by, Prof. Santosh Kabir.


129
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

10

MU Exam Papers

Write a program to read the data and determine the following :- .


(i) Total marks obtained by each student
(ii) The student who obtained the highest total marks.
3. (a) What are constructors? Explain different types of constructor with example.
(b) Write a program to display the following pattern.

10
10

*
* * *
* * * * *
* * *
*
4. (a) What is abstract class? Write a program to display volume of sphere and hemisphere.

10

Make use of abstract class.


(b) Explain with example :-

10

(i) throw (ii) catch (iii) finally5. (a) Write a program to illustrate use of isAlive() and join() and sleep() method. Create three

10

classes A, B and C. Create another class "lsaliveJoin'" to invoke isAlive ( ) and join ( )
methods for these 3 child thread.
(b) Explain static class members with example.

6. (a) Write a program that accepts a shopping list of items and perform the following operations.

12

(i) add an item at a specified location


(ii) delete an item in the list
(iii) Print the contents of the vector
(b) Consider a class network given. The class 'Admin' derives information from the class

10

'Account' which in turn derives information from the 'Person' class. Write a program to display
'Admin' object.
Person
Name
code

Account
Pay

Admin
Exp
7. Write short note on :(any three)

20

(i) Life cycle of an applet


(ii) Call by value and call by reference
Prepared by, Prof. Santosh Kabir.
130
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

MU Exam Papers

(iii) Difference between array and vector


(iv) Explain 'Interface' and use of interface.
-----------------

Dec. 2009
N.B: (1) Question No. 1is compulsory.
(2) Attempt any four questions out of remaining six questions.
1. (a) Write short note on :-

10

(i) Features of Java


(ii) Java Virtual Machine (JVM)
(b) Write a program to print the following pattern.

* * * *
* * *
* *
*

10

*
*
*
*
*

2. (a) What is command line argument? Write a program to find largest of three integers

10

accepted from command line.


(b) Write a program to capitalize the first character of each word from a given sentence
(example: all the best

10

to All The Best).

3. (a) Explain Exception handling mechanism in JAVA.

10

(b) Write a program to search an integer in an Array of integers.

10

4. (a) Explain Interface and use of Interface with example.

10

(b) Write a program to accept student names from the command line and store them

10

in vector.
5. (a) Explain Thread life cycle and explain any five methods of class Thread.

10

(b) Write a program to print. / * / * / * / * / * / * / * using two child thread.

10

(hint: One thread responsible for printing * and another for /)


6. (a) What is the difference between application and applet. Write an applet to display

10

the following.

(b) Explain lifecycle of an applet and demonstrate how to pass parameter to an applet.

Prepared by, Prof. Santosh Kabir.


131
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

MU Exam Papers

10

7. Write short notes (any four) :-

20

(a) Wrapper Classes


(b) Access protection in Java
(c) String Buffer Class
(d) Abstract Class
(e) java.util package.
----------------

June 2010
N. B. :(1) Question No.1 is compulsory.
(2) Solve any four questions from 2 to 7.
1. a) Explain the working of JVM. Also explain how java is architectural neutral.
b) Explain data types in Java. Also explain the role of wrapper class.

10
10

2. a) Write a java program to find factorial of a given number. The number will be provided by

10

user at run time.


b) Create a class employee with data members empid, empname, designation and salary.

10

Write methods getemployee ( ) -To Take user input, showGrade ( ) -to display grade of employee
based on salary. Show employee ( ) to display emp details.
3. a) Write a program to find out number of upper case, lower case, blank spaces,number of digits 10
from the string.
b) Write a program to accept five integers from user and arrange in ascending order.
4. (a) What types of Inheritance provided by java explain with proper example?

10
10

Also discuss about inability of multiple inheritance in java and the alternative way to achieve it.
(b) Explain the difference between abstract class, interface and final class. Write an abstract

10

class program to calculate area of circle, rectangle and triangle.


5. a) Explain the difference between single threaded application and multithreaded application?

10

What is the benefit of multithreading? Explain how java provided multithreading.


b) What is package? How it is useful demonstrate with example?

10

6. a) Explain the excepfion handling feature of java with any suitable example.
b) What is java applet. Write a java applet to display "Hello java". Also write the relation

10
10

between applet and HTML.


7. Short notes on any four :-

20

a) Difference between C++ & Java


b) System.arraycopy ( ) method
c)Static members
d) Access specifiers
e) Thread synchronization.
------------------Prepared by, Prof. Santosh Kabir.
132
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

MU Exam Papers

June -2011
N.B.: Question 1 is compulsory
Answer any four out of remaining six questions.
Assume necessary data wherever necessary.
1. a) Explain life cycle of an Applet.

10

b) With example explain steps to create package and add a class or interface.
2. a) Create three vectors Bank, Deposit and Withdraw. Perform following operations.

10
20

a. New customer. Data should be added to Bank vector.


b. Withdrawal of requested amount if bank customer is present in Bank vector. Account no,
withdrawal amount and date should be added to Withdraw vector, and amount should
be deducted from balance of Bank vector.
c. Deposition of requested amount if bank customer is present in Bank vector. Account no,
deposit amount and date should be added to Deposit vector, and amount should be
added from balance of Bank vector.
d. View the contents of the account.
3. a) Explain exception handling with programmatic examples.

10

b) Write a program to accept a number and compute sum its digits recursively.
4. a) Explain thread life cycle.

10
10

b) Write a short note on access/visibility specifiers.


5. a) With suitable examples explain different types of inheritance.

10
10

b) Write a Java program to accept a number from command line and print the sum of cubes of
individual digits.

10

6. State difference between :

20

a) Applet and applications.


b) Abstract class and interface.
c) Vector and array
d) String and StringBuffer
7. Write short note on:

20

a) Snchronization
b) JVM
c) Wrapper classes
d) toString()
------------------

Prepared by, Prof. Santosh Kabir.


133
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

MU Exam Papers

Dec-2011
N.B.: Question 1 is compulsory
Answer any four out of remaining six questions.
Assume suitable data if required and state the assumption clearly.
Figure the right indicate full marks.
1. a) Differentiate between method overriding and method overloading.

[5]

b) Explain the roll of wrapper classes.

[5]

c) Write a short note on Abstract class.

[5]

d) Explain static members.

[5]

2. a) Write a program to create multiple threads. Demonstrate the use of isAlive(), setName(),
getName(), setPriority(), getPriority() methods of Thread class.

[10]

b) Write a program to evaluate the sum of following series:


2
2
2
2
1 + 1/2 + 1/3 + 1/4 + . + 1/n

[10]

3. a) Write a program to read five names of students from command line and store them in a Vector.
Sort the list in alphabetic order and display.

[10]

b) Write a program to count frequency of occurrence of given character in a given line of text.
For example : the line text is We are students and eat Eggs.
The given character is e,
Then the frequency of occurrence is =5

[10]

4. a) How you define an exception? Explain how Java handles exception during program execution
with suitable example.

[10]

b) What are the benefits of packages? What are the Java API packages? Write a program to
demonstrate the creation and use of package.

[10]

5. a) Write a program to display the area of square and rectangle using the concept of overloaded
constructors.

[10]

b) Write a Java applet to display the house as shown below,


[10]

6. a)Explain the difficulty of Java to implement multiple inheritance. How multiple inheritance is
supported by Java. Explain with suitable example.
Prepared by, Prof. Santosh Kabir.
134
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

[10]

MU Exam Papers

b) How do you define data type? Explain the data types in Java?

[10]

7. Write short notes on any Four of following :

[20]

a) Parameter passing to applet,


b) Life cycle of a thread,
c) System.arraycopy() method,
d) Command line arguments
e) Java access protection.
------------------

Prepared by, Prof. Santosh Kabir.


135
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

MU Exam Papers

Complete Programs from previous exams.

June-2008
1. GCD using given Euclid's algo. (Q2.a )
import

java.io.* ;

Programs solved from


previous papers

class GCD
{
int no1, no2; // the two numbers

MU Exam Questions
June-08 to Dec- 11 (old Syl. )

int g; //for GCD of numbers


GCD()
{
}
GCD(int a, int b)
{
no1 = a;
no2 = b;
}
void input() throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no1, no2 :");
no1 = Integer.parseInt( in.readLine() );
no2 = Integer.parseInt( in.readLine() );
}
void display()
{
System.out.println("Two numbers:" + no1 + "," + no2);
System.out.println("GCD = " + g );
}
void findGCD()
{
// store data-member values in local variables
int n1 = no1, n2 = no2;
int rem;
do
{
if( n1 > n2 )
{
g = n2;
rem = n1 % n2;
n1 = n2;
n2 = rem;
}
else
{
g = n1;
rem = n2 % n1;
Prepared by, Santosh Kabir.
136
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


n2 = n1;
n1 = rem;
}
}while(rem != 0 );
}
}
class A
{
public static void main(String[ ]args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int x, y;
System.out.println("Enter two numbers:");

OUTPUT :

x = Integer.parseInt( in.readLine() );

Enter two numbers:

y = Integer.parseInt( in.readLine() );

12

GCD g1 = new GCD( x, y ); // param. constr

40

g1.findGCD();

Two numbers:12,40

g1.display();

GCD = 4
Enter no1, no2 :

GCD g2 = new GCD(); // default constr

64

g2.input(); // input done using method of class

48

g2.findGCD();

Two numbers:64,48

g2.display();

GCD = 16

}
}
-----------------------------------

2. Calculating number of days in semester. Input statrting and ending dates as strigs. (Q2.b)
import

java.io.* ;

class DaysInSem
{
public static void main(String[ ] args) throws IOException
{
// Store days-of-months in array
int m[ ] = { 0, 31,28,31,30,31,30,31,31,30,31,30,31 };
String first, last;
BufferedReader in = new BufferedReader( new InputStreamReader(System.in) );
System.out.println("Enter first day:(mm/dd/yyyy)");
first = in.readLine();
System.out.println("Enter last day:");
last = in.readLine();
// Read first day variables
String a[ ] = first.split("/");
int m1 = Integer.parseInt( a[0] );
Prepared by, Santosh Kabir.
137
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


int d1 = Integer.parseInt( a[1] );
// Read last day variables
String b[ ] = last.split("/");
int m2 = Integer.parseInt( b[0] );
int d2 = Integer.parseInt( b[1] );

Sem IV IT

Web Programming
By Santosh Kabir.

// Read Year
int yr = Integer.parseInt( a[2] );

Regular batches at
Andheri , Thane

// --- Calculation starts here --// change days of Feb if leap year
if( m1==2 && (yr%400 == 0 ||(yr%4==0 && yr%100 != 0) ) )
m[2] = 29 ;
int days = 0;
// days in first month

OUTPUT :

days += m[ m1 ] - d1 +1;

Enter first day:(mm/dd/yyyy)


07/25/2011

for( int i=m1+1; i< m2; i++ )


days += m[i];

Enter last day:


11/20/2011
No of days:119

// days in last month


days += d2;
System.out.println("No of days:" + days);
}
}
------------------------------------------

3. Calculation of distance travelled by object at different intervals. (Q3.a )


import java.io.* ;
class Distances
{
public static void main(String[]args) throws IOException
{
double s, sz, u, a=9.81, t;
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
System.out.print("Enter inital displ.:");
sz = Float.parseFloat( in.readLine() );
System.out.print("Enter inital velocity (u m/s):");
u = Float.parseFloat( in.readLine() );
System.out.print("Enter acceleration(a m/s.sq):");
a = Float.parseFloat( in.readLine() );
t = 1; // calc. for interval = 1
s = sz + u*t + 0.5 * a*t*t;
Prepared by, Santosh Kabir.
138
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


// Displaying in tabular form
System.out.println("Int.\tDist.");
System.out.println( (int)t + "\t" + s );
for( t = 5; t<=100; t+=5 ) // distances for intervals 5,10,15, ... 100
{
s = sz + u*t + 0.5 * a*t*t;
System.out.println( (int)t + "\t" + s );`
}
}
}
-------------------------------------

santoshkabir@yahoo.com ( or facebook )

OUTPUT :
Enter inital displ.:5
Enter inital velocity (u m/s):2
Enter acceleration(a m/s.sq):3
Int.

Dist.

8.5

52.5

10

175.0

15

372.5

90

12335.0

95

13732.5

100

15205.0

4. Arranging student data in descending order of total marks. (Q3.b )


import java..io.*;
class Student
{
int ID;
String name;
int p, c, m, total;
// for data input
void input() throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
System.out.println("Enter ID, Name and P,C,M marks ...");
ID = Integer.parseInt( in.readLine() );
name = in.readLine();
p = Integer.parseInt( in.readLine() );
c= Integer.parseInt( in.readLine() );
m = Integer.parseInt( in.readLine() );
total = p+ c+ m;
}
void display()
{
System.out.println( ID + "\t" + name + "\t"+ p + "\t"+ c + "\t" +m + "\t" + total);
}
}
Prepared by, Santosh Kabir.
139
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


class StudentList
{
public static void main(String [ ] args) throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
System.out.print("How many students :");
int n = Integer.parseInt( in.readLine() ); // input number of students
Student [ ] a = new Student[ n ]; // Create array to hold sno, Student object variables.
int i ,j;

OUTPUT :

System.out.println("Enter " + n + " students info. :");

How many students :3

for( i=0; i< n ; i++ ) // Input data for multiple students

Enter 3 students info. :

Enter ID, Name and P,C,M marks ...

a[i] = new Student(); // create student object **

23

a[i].input();

ABHI

56
65

// Arrange student records in descending values of total

67

// Bubble sort method

Enter ID, Name and P,C,M marks ...

for( int last= n-1; last>0; last-- )

34

RAJU

for( i=0; i<last; i++ )

67

76

if( a[i+1].total > a[i].total )

65

Enter ID, Name and P,C,M marks ...

Student temp = a[i];

42

a[i] = a[i+1];

TINA

a[i+1] = temp;

60

54

76

Re-arranged records are as follows...


I.D

NAME..PHY CHEM MATH TOTAL

// Display re-arranged records

34

RAJU

67

76

65

208

System.out.println("Re-arranged records are as follows...");

42

TINA

60

54

76

190

System.out.println( "I.D\tNAME..\tPHY

23

ABHI

56

65

67

188

\tCHEM\tMATH\tTOTAL");
for( i=0; i<n; i++ )
{
a[i].display();
}
}
}
---------------------------------------

5. Matrix operation with base interface for matrix addition and multiplication the methods should
have another matrix object as method argument. Hence, they are modified (Q.6 )
Prepared by, Santosh Kabir.
140
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


import java.io.*;
interface Matrix
{
final static int M=3, N=3; // matrix size
void readMatrix() throws IOException;
void displayMatrix();
void addMatrix(MatrixOper x);
void multMatrix(MatrixOper y);
void transposeMatrix();
}
class MatrixOper implements Matrix
{
int a [ ][ ] = new int[M][N]; // Two dim array of MxN
// for data input
static BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
public void readMatrix() throws IOException
{
System.out.println("Enter Matrix values :");
for(int i=0; i<M; i++)
{
for( int j=0; j<N; j++ )
a[i][j] = Integer.parseInt( in.readLine() );
}
}
public void displayMatrix()
{
System.out.println("Matrix values ...");
for(int i=0; i<M; i++)
{
for( int j=0; j<N; j++ )
System.out.print ( a[i][j] + " " );
System.out.println();
}
}
public void addMatrix( MatrixOper r )
{
for(int i=0; i<M; i++) // add arg. matrix to this matrix
{
for( int j=0; j<N; j++ )
a[i][j] += r.a[i][j];
}
}

Prepared by, Santosh Kabir.


141
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


public void multMatrix( MatrixOper r )
{
// Mult. this matrix with arg. r and store in y
MatrixOper y = new MatrixOper();
for(int i=0; i<M; i++)
{
for( int j=0; j<N; j++ )
{
for(int k=0; k<N; k++)
y.a[i][j] += a[i][k] * r.a[k][j];
}

OUTPUT :
Enter Matrix values :
1
2
3
2
3
1
3
2
1

}
System.out.println("Multiplication :");
y.displayMatrix();
}
public void transposeMatrix( )
{
// store transpose in the same matrix
for(int i=0; i<M; i++)
{
for( int j= i; j<N; j++ )
{
int t = a[i][j];
a[i][j] = a[j][i];
a[j][i] = t;
}
}
}

Enter Matrix values :


1
2
1
2
1
1
1
1
2
Matrix values ...
1 2 3
2 3 1
3 2 1
Matrix values ...
1 2 1
2 1 1

1 1 2

class Mat
{
public static void main(String[]args) throws IOException
{
MatrixOper m = new MatrixOper();
MatrixOper n = new MatrixOper();
m.readMatrix();
n.readMatrix();
m.displayMatrix();
n.displayMatrix();
m.addMatrix( n );
System.out.println("Addition:");
m.displayMatrix();

Addition:
Matrix values ...
2 4 4
4 4 2
4 3 3
Multiplication :
Matrix values ...
14 12 14
14 14 12
13 14 13
Transpose :
Matrix values ...
2 4 4
4 4 3
4 2 3

m.multMatrix( n );
Prepared by, Santosh Kabir.
142
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


m.transposeMatrix();
System.out.println("Transpose :");
m.displayMatrix();
}
}
----------------------------------------

Dec. - 2008
6. Program to find nCr, nPr . (Q1.b [5] )
class NCR_NPR
{
static BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
static double factorial(int n)
{
double f = 1;
for( int i=1; i<=n; i++ )
f *= i;
return f;
}
public static void main(String[]args) throws IOException
{
int n, r;
double c, p;

OUTPUT :

System.out.println("Enter n and r :");

Enter n and r :

n = Integer.parseInt( in.readLine() );

r = Integer.parseInt( in.readLine() );

c = factorial(n) / ( factorial(r) * factorial(n-r) ) ;

Compinations :20.0

System.out.println("Compinations :" + c);

Permutations :120.0

p = factorial(n) / factorial(n-r) ;
System.out.println("Permutations :" + p);
}
}
-----------------------------------

7. Find sum of series 1 + 1/2 + 1/3 + 1/4 + ... for n terms. (Q1.d [5] )
import java.io.* ;
class SumSeries
{
static BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
public static void main(String[]args) throws IOException
{
int n;
double i, sum = 0;
System.out.println("Enter n :");
Prepared by, Santosh Kabir.
143
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


n = Integer.parseInt( in.readLine() );
for( i=1; i <=n; i++)
sum += 1/i;

OUTPUT :
Enter n :
5

System.out.println("Sum :" + sum );

Sum :2.283333333333333

}
}
-------------------------------------

8. Designing menu in for Window. (Q3.a [12] )


[ This is is out-of-syllabus question ]
import java.awt.*;
class MenuProg1 extends Frame
{
// Define menubar object to attach to Applet window
MenuBar mb = new MenuBar();
// Define main menus
Menu mnufile = new Menu("File");
Menu mnuedit = new Menu("Edit");
Menu mnuview = new Menu("View");
// Define menu-items
//MenuItem miopen = new MenuItem("Open");
//MenuItem misave = new MenuItem("Save");
//MenuItem miexit = new MenuItem("Exit");
MenuItem miundo = new MenuItem("Undu");
MenuItem micopy = new MenuItem("Copy");
MenuItem micut = new MenuItem("Cut");
MenuItem mipaste = new MenuItem("Paste");
MenuProg1()
{
// create menubar
setMenuBar( mb );
setTitle("Menu Demo"); // setting title for window
// Add menus to the menubar
mb.add(mnufile);
mb.add(mnuedit);
mb.add(mnuview);
// Add menu-items to menus
//mnufile.add(miopen);
//mnufile.add(misave);
//mnufile.add(miexit);
mnuedit.add(miundo);
mnuedit.add(micut);
Prepared by, Santosh Kabir.
144
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


mnuedit.add(micopy);
mnuedit.add(mipaste);
setSize(400,400);
setVisible(true);
}
public static void main(String[ ]args)
{
MenuProg1 obj = new MenuProg1();
}
}
-------------------------------------------

9. Account class with inheritance. Super class Account.


Sub class SavingsAct and CurrentAct. Method overriding. ( Q. 4.c [10] )
We will define a class Account as an abstract/normal class with common members,
like setting account values, display balance, deposit and withdraw as abstract methods
final var. penalty is defined in the class.
class Account
{
int acno;
String name;
String type;
double balance;
Account(int no, String nm, String t, double bal)
{
acno = no;
name = nm;
type = t;
balance = bal;
System.out.println("Acct created.."+ type );
}
public void deposit( double amt )
{
balance += amt;
}
public void displayBalance()
{
System.out.println("Balance = " + balance);
}
}
Prepared by, Santosh Kabir.
145
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


// The classes define the 'withdraw()' method in specific way
class Savings_Act extends Account
{
Savings_Act(int no, String nm, String t, double b)
{
super(no, nm, t, b);
}
public void withdraw(double amt)
{
// Withraw fails if amount is greater then balance
if( balance >= amt )
balance -= amt;
else
System.out.println("Insufficient balance");
}
public void calcInterest()
{
// assume 5% interest rate
balance += balance * 0.05;
}
}
class Current_Act extends Account
{
final int penalty = 50; // Rs.50/- penalty if withdraw fails
Current_Act(int no, String nm, String t, double b)
{
super(no, nm, t,b);
}
public void withdraw(double amt)
{
// Withraw fails if it makes balance less than Rs.2000
if( balance-amt >= 2000 )
balance -= amt;
else
{
balance -= penalty;
System.out.println("Insufficient balance");
}
}
}
class AccountTest
{
public static void main(String []args)
{
Prepared by, Santosh Kabir.
146
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


double a;
// .. Students can do data-input here, and create objects of classes
Savings_Act sa = new Savings_Act(1234, "xyz","saving", 5000);
sa.displayBalance();
sa.deposit(5000);
sa.withdraw(1000);
sa.calcInterest();
sa.displayBalance();
Current_Act ca = new Current_Act(567, "abc","Current", 8000);

OUTPUT :

ca.displayBalance();

Acct created..saving

ca.deposit(2000);

Balance = 5000.0

ca.withdraw(5000);

Balance = 9450.0

ca.displayBalance();

Acct created..Current

ca.withdraw(4000);

Balance = 8000.0

ca.displayBalance();

Balance = 5250.0

Insufficient balance

Balance = 5460.0

------------------------------------

10. Write a program to create multiple threads. (Q5.b [5] )


Explaination :
The program has a Thread class named 'DemoThread,. The class has run() method that displays thread
name 15 times with delay of 10ms, before each new output. The class 'MultiThreads' is a main class,
that creates two objects of DemoThread, sets name for threads and execute the threads by invoking
start() method on the two objects. In the program we can creates multiple objects of DemoThread
class and run multiple threads at a time.
class DemoThread extends Thread
{
public void run()
{
String name = currentThread().getName();
try
{
for(int i = 1; i <= 15; i++)
{
System.out.print( name + " thread i=" +i);
Thread.sleep(10);
}
}catch(Exception e)

System.out.println( name + " Thread ends=");


}
}
Prepared by, Santosh Kabir.
147
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


class MultiThreads
{
public static void main(String args[])
{
DemoThread dt1 = new DemoThread();
dt1.setPriority( 3 );
dt1.setName("...FIRST");
dt1.start(); // spawns a new thread and runs new thread through dt1 object
DemoThread dt2 = new DemoThread();
dt2.setPriority( 8 );
dt2.setName(".....SECOND");
dt2.start(); // spawns a new thread and runs new thread through dt2 object
}
}
----------------------------------------

11. Program to check whether i/p string is a palindrome. ( Q5.c [5] )


import java.io.DataInputStream;
import java.io.IOException;;
class Palindrome
{
public static void main(String[]args) throws IOException
{
boolean F = true; // flag variable
int i,j;
DataInputStream in = new DataInputStream( System.in);
System.out.println("Enter a string:");
String s = in.readLine();
int len = s.length(); //get length of i/p string
for( i=0, j=len-1; i< len/2; i++, j-- )
{
if( s.charAt(i) != s.charAt(j) )
{
F = false;
break; // terminate 'for'
}
}
if( F == true)
System.out.println("It is a palindrome");
else
System.out.println("NOT a palindrome");
}
}
--------------------------------

santoshkabir@yahoo.com ( or facebook )

Prepared by, Santosh Kabir.


148
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


12. Program to display elements in the string with element no. ( Q1.b [10] )
import java.io.*;
class StringChars
{
public static void main(String[]args) throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ));
System.out.print("Enter a string:");
String s = in.readLine();
int len = s.length();
if( len <= 15 )
{
char [ ]a = s.toCharArray();
for( int i=0; i< len; i++)
{
System.out.println( a[i] +"\t" + i );
}

OUTPUT :
Enter a string: hello
h

}
else
System.out.println("Enter max 15 characters");
}
}
--------------------------------

June- 2009
13. Input student marks, find totals and displaying student with highest total. (Q2.b [10] )
class Student
{
private int rno;
private int sub1, sub2, sub3;
int total;
void input() throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
System.out.print("Enter Roll no :");
rno = Integer.parseInt( in.readLine() );
System.out.println("Marks in 3 subjects :");
sub1 = Integer.parseInt( in.readLine() );
sub2 = Integer.parseInt( in.readLine() );
sub3 = Integer.parseInt( in.readLine() );
total = sub1 + sub2 + sub3; // gets total of three subjects
}

Prepared by, Santosh Kabir.


149
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


void display()
{
System.out.println("R.no=" + rno);
System.out.println("Marks :" + sub1 + "\t"+ sub2 + "\t"+ sub3 );
}

OUTPUT :

Enter 5 students info. :


Student ...1

class A

Enter Roll no :111

Marks in 3 subjects :
public static void main(String [] args) throws IOException

65

76
Student []a = new Student[5];

87

int i ,j;

Student ...2

System.out.println("Enter 5 students info. :");

Enter Roll no :222

for( i=0; i<5; i++ )

Marks in 3 subjects :

76
System.out.println("Student ..." + (i+1) );

76

a[i] = new Student();

87

a[i].input();

Student ...3

Enter Roll no :333

// finding student with highest total.

Marks in 3 subjects :

int id = 0; // this will store index of highest scorer

65

int max = a[0].total;

76

System.out.println("Totals are...");

87

for( i=0; i< 5; i++ )

Student ...4

Enter Roll no :444


System.out.println(a[i].total);

Marks in 3 subjects :

if ( a[i].total > max )

54

56
max = a[i].total;

67

id = i;

Student ...5

Enter Roll no :555

Marks in 3 subjects :

// Display data for highest scorer

76

System.out.println("Info. about highest scorer...");

87

a[id].display();

65

Info. about highest scorer...

R.no=222

----------------------------------

Marks :76

76

87

14. Program to display following pattern. (Q3.b [10] )


*
***
*****
***
*
Prepared by, Santosh Kabir.
150
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


class Patrn
{
public static void main(String[] args)
{

Sem IV IT

Web Programming

final int n=3;


int i, j, k;
for( i=1; i<= n; i++)

By Santosh Kabir.

{
for( j=1; j<= n-i; j++)
System.out.print( " " );

Regular batches at
Andheri , Thane

for( j=1; j<= (2*i-1) ; j++)


System.out.print( "* " );
System.out.println();
}
for( i= n-1; i >=1 ; i--)
{
for( j=1; j<= n-i; j++)
System.out.print(" ");
for( j=1; j<= (2*i-1) ; j++)
System.out.print("* ") ;
System.out.println();
}
}
}
// Note : If question was 'Display following pattern for multiple lines, then, Declare 'n' as simple
varibale & input n from user. Remaining program will be same.
--------------------------------------------

15. Program to display volume of sphere and hemisphere. Make use of abstract class. (Q4.a )
Abstract class Shape declares a method to display volume. The sub-class Sphere and Hemisphere
define (i.e. override) the method for displaying corresponding volumes.
abstract class Shape
{
abstract void getVolume(double r);
}
class Sphere extends Shape
{
public void getVolume(double r)
{
double v = 4.0/3 * 3.142 * r*r*r;
System.out.println("Vol. of sphere=" + v );
}
}

Prepared by, Santosh Kabir.


151
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


class Hemisphere extends Shape
{
public void getVolume(double r)
{
double v = 0.5 * (4.0/3 * 3.142 * r*r*r);
System.out.println("Vol. of hemisphere=" + v );
}
}
class AbstClass
{
public static void main(String []args)
{
Sphere s = new Sphere();
s.getVolume(10);
Hemisphere h = new Hemisphere();
h.getVolume(10);
}
}
------------------------------

16. Demo. of isAlive(), join() and sleep() with three child threads . (Q5.a [10] )
// Classes A,B and C are for running child threads
class A extends Thread
{
public void run()
{
try
{
for(int i=1; i<=4; i++)
{
System.out.println("Thread: A");
Thread.sleep(3);
}
}
catch(Exception ex) {

System.out.println("Thread: A ends");
}
}
class B extends Thread
{
public void run()
{

Prepared by, Santosh Kabir.


152
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


try
{
for(int i=1; i<=4; i++)
{
System.out.println("Thread: B");
Thread.sleep(3);
}
}
catch(Exception ex)
{
}
System.out.println("Thread: B ends");
}
}
class C extends Thread
{
public void run()
{
try
{
for(int i=1; i<=4; i++)
{
System.out.println("Thread: C");
Thread.sleep(3);
}
}
catch(Exception ex)
{
}
System.out.println("Thread: C ends");
}
}
class CheckAlive
{
public static void main(String []args)
{
A t1 = new A();
B t2 = new B();
C t3 = new C();
// Threads not running
if(t1.isAlive() )
System.out.println("A working");
else
System.out.println("A Not yet working");
Prepared by, Santosh Kabir.
153
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


// Threads start running here

Example output

t1.start();

(In multithreading programs

t2.start();

outputs can vary)

t3.start();
// checking whether threads are alive (running/runnable)
if(t1.isAlive() )

A Not yet working


Thread: A
Thread: B

System.out.println("A working");

A working

if(t2.isAlive() )
System.out.println("B is working");
if(t2.isAlive() )
System.out.println("B is working");
// blocking main() thread till child threads finish
try

B is working
B is working
Thread: C
Thread: A
Thread: B
Thread: C
Thread: A

Thread: B

t1.join();

Thread: C

t2.join();

Thread: A

t3.join();

Thread: B

}catch(Exception e)

Thread: C

Thread: A ends

}
System.out.println("main Thread ends:");
}

Thread: B ends
Thread: C ends
main Thread ends:

}
-----------------------------------

17. Making Shopping list using Vector.

( Q6.a [10] )

import java.io.*;
import java.util.*;
class Book // this class represents shopping list item
{
int id;
String name;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
void input() throws IOException
{
System.out.println("Enter book Id and Title:");
id = Integer.parseInt(in.readLine());
name = in.readLine();
}
void display()
{
System.out.println("ID=" + id + " .. Name : " + name );
}
}
Prepared by, Santosh Kabir.
154
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


class ShoppingList
{
public static void main(String[]args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int i;
Vector list = new Vector(10,3);
String ans;
// Inputting book list
System.out.println("...Enter Book list");
do

OUTPUT :
...Enter Book list
Enter book Id and Title:
111
CP-II
Continue :

{
Book b = new Book(); //create new book object
b.input();
list.add( b ); // add book obj to vector
System.out.println("Continue :");
ans = in.readLine();
}while( ans.equals("y") ); // loop continue automatically
System.out.println("Total elements in list=" + list.size() );
System.out.println("The book list is as follows...");
for( i=0; i<list.size(); i++)
{
Book a = (Book) list.elementAt(i);
a.display(); // display info
}

y
Enter book Id and Title:
222
Maths
Continue :
y
Enter book Id and Title:
333
ED
Continue :
y
Enter book Id and Title:
444
PHY
Continue :
n

// To insert book in a list


System.out.println("...Enter new Book data: ");
Book m = new Book();
m.input();
System.out.print("Where to insert in list : ");
i = Integer.parseInt( in.readLine() );
list.add(i, m );
// To delete a book
System.out.print("...Enter index of book delete: ");
i = Integer.parseInt( in.readLine() );
list.removeElementAt( i );

Total elements in list=4


The book list is as follows...
ID=111 .. Name : CP-II
ID=222 .. Name : Maths
ID=333 .. Name : ED
ID=444 .. Name : PHY
...Enter new Book data:
Enter book Id and Title:
100
Chemistry
Where to insert in list : 2
...Enter index of book delete: 1

System.out.println("The book list is as follows...");


for( i=0; i<list.size(); i++)
{
//get obj at ith index in vector
Prepared by, Santosh Kabir.
155
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


Book a = (Book) list.elementAt(i);
a.display(); // display info
}
}

OUTPUT Contd..
The book list is as follows...
ID=111 .. Name : CP-II

ID=100 .. Name : Chemistry


ID=333 .. Name : ED
ID=444 .. Name : PHY

-------------------------------------

18. Define Person -> Account -> Admin classes.


Use admin class object to input and display data. ( Q6.b [10] )
class Person
{
int code;
String name;
void person_data(int c, String n)
{
code = c;
name = n;
}
void display()
{
System.out.println("Code=" + code + ", Name=" + name);
}
}
class Account extends Person
{
double pay;
void act_data( double p )
{
pay = p;
}
void display()
{
super.display(); // call display() of Person
System.out.println("Payment =" + pay );
}
}
class Admin extends Account
{
double exp;
void admin_data( double e )
{
exp = e;
}

Prepared by, Santosh Kabir.


156
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


void display()
{
super.display(); // call display() of Account
System.out.println("Experience =" + exp );
}
}
class Test
{
public static void main(String[]args) throws IOException
{
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
Admin a = new Admin(); // Admin class obj.
// -- Input data
System.out.println("Enter CodeNo and name:");
int no = Integer.parseInt( in.readLine());
String n = in.readLine();
a.person_data(no, n );
System.out.println("Enter Pay:");
double p = Double.parseDouble( in.readLine());
a.act_data( p );
System.out.println("Enter experience:");
double ex = Double.parseDouble( in.readLine());
a.admin_data( ex );

OUTPUT :
Enter CodeNo and name:
123
RAVI
Enter Pay:
12000
Enter experience:
4
Admin data...
Code=123, Name=RAVI
Payment =12000.0
Experience =4.0

//-- Display Admin obj.


System.out.println("Admin data...");
a.display();
}
}
-----------------------------------

Dec - 2009
19. Display following pattern. (Q1.b [10] )
* * * * *
* * * *
* * *
* *
*
import java.io.*;
class Patrn2
{
Prepared by, Santosh Kabir.
157
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


public static void main(String[ ] args) throws IOException
{
int i,j,k, n;
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
System.out.println("How many lines:");
n = Integer.parseInt( in.readLine() );
for(i= n; i >= 1; i-- ) // decr. i from n to 1
{
for(j=1; j<= n-i; j++) // for n-i times
{
System.out.print(" "); // 2 space
}
for(j=1; j<= i; j++) // display '*' with space , i times
{
System.out.print( "* " );
}
System.out.println(); // new line
}
}
}
------------------------------

20. Input 3 intergers from command line and find the largest of the three. (Q2.a [5] )
class CmdLine
{
public static void main(String[ ]args)
{
int a,b,c, m, len;
len = args.length;
if( len >= 3 )
{
a = Integer.parseInt( args[0] );
b = Integer.parseInt( args[1] );
c = Integer.parseInt( args[2] );
m = a > b ? a : b;
m = c > m ? c : m;
System.out.println( "Largest of the three = " + m );
}
else
System.out.println("Enter three numbers at com. line");
}
}
------------------------------------

Prepared by, Santosh Kabir.


158
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


21. String program: i/p all the best o/p: All The Best . (Q2.b [10] )
import java.io.*;
class Caps
{
public static void main(String[]args) throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
System.out.print("Enter a String :");
String s = in.readLine();
int len = s.length();
char a[ ] = s.toCharArray(); // put chars in char array
a[0] = Character.toUpperCase( a[0] ); // make 1st letter uppercase
for( int i=0; i< len-1 ; i++ )
{
// if ith char. is space then convert i+1 char to upper case
if( Character.isSpaceChar( a[i] ) )
a[i+1] = Character.toUpperCase( a[i+1] );
}
s = new String( a ); // create new string

OUTPUT :
Enter a String :this is mumbai city
Modified String :This Is Mumbai City

System.out.println("Modified String :" + s );


}
}
---------------------------------

22. Searcing an integer in a array. (Q3.b [10] )


import java.io.*;
class SearchNo
{
public static void main(String[]args) throws IOException
{
int i, n, no;
boolean F = false;
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
System.out.print("Enter array length :");
n = Integer.parseInt( in.readLine() );
int [ ]a = new int[ n ];
System.out.println("Enter array elements :");
for( i=0; i<n; i++ )
{
a[i] = Integer.parseInt( in.readLine() );
}
System.out.print("Enter a no. to search :");
no = Integer.parseInt( in.readLine() );
Prepared by, Santosh Kabir.
159
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


for( i=0; i<n; i++ )
{
if( a[i] == no ) // if no is found, set F as true and stop
{
F = true;
break;
}
}
if( F == true )
System.out.println("The number is found at index :" + i );
else
System.out.println("The number is Not found" );
}
}
--------------------------------23. Read some names from command line, and store them in a Vector. (Q4.b [10] )
import java.util.*;
class StudentVector
{
public static void main(String [ ]args)
{
int len = args.length;
if( len > 0 )
{
Vector v = new Vector(len + 5);
for(int i=0; i<len; i++ ) // put names in the vector
{
v.add( args[i] );
}

OUTPUT :
>java StudentVector xy pq mn xyz abc pqrs

System.out.println("Student list...");
for(int i=0; i<len; i++ )
{
System.out.println( v.elementAt(i) );
}
}
else

Student list...
xy
pq
mn
xyz
abc
pqrs

System.out.println("No student names entered");


}
}
---------------------------------

24. Write a program with two child threads to display / * / * / * / * / * / *


One displays / and the other *. (Q5.b )
class Child1 extends Thread
{
Prepared by, Santosh Kabir.
160
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


public void run()
{
for(int i=1; i<= 5; i++ )
{
System.out.print("/");
try

Sem IV IT

Web Programming
By Santosh Kabir.

{
yield();
}catch(Exception e) { }

Regular batches at
Andheri , Thane

}
}
}
class Child2 extends Thread
{
public void run()
{
for(int i=1; i<= 5; i++ )
{
System.out.print("*");
try
{
yield();
}catch(Exception e) { }
}
}
}
class ChildThreads
{
public static void main(String[]args)
{
Child1 t1 = new Child1();
Child2 t2 = new Child2();
t1.start();
t2.start();
}
}
----------------------------------------

25. Drawing face like shape with eyes (ovals), nose and lips (lines). (Q6.a )
import java.applet.Applet;
import java.awt.*;
public class Face extends Applet
{
public void paint(Graphics g)
{
// Ovals for eyes
g.drawOval( 50, 50, 60, 30 );
Prepared by, Santosh Kabir.
161
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


g.drawOval( 140, 50, 60, 30 );
// Vertical line for nose
g.drawLine(125, 60, 125, 110);
// horizonal line for lips
g.drawLine( 80, 120, 170, 120);
}
}
// Following line loads the applet in browser window
/* <Applet code="Face.class" width=500 height=500> </applet> */
-----------------------------------

June- 2010
26. Input a number and find its factorial. (Q2.a )
import java.io.*;
class factorial
{
public static void main(String []args ) throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
System.out.print("Enter a number :");
int n = Integer.parseInt( in.readLine() );
long f = 1;
for( int i=1; i<=n; i++ )
f *= i;
System.out.println("Factorial =" + f );
}
}
----------------------------------------

27. Q2.b
import java.io.*;
class Employee
{
int id;
String name, desig;
double salary;
void getEmployee() throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
System.out.println("Enter id , name, designation, salary :");
id = Integer.parseInt( in.readLine() );
name = in.readLine();
desig = in.readLine();
salary = Double.parseDouble( in.readLine() );
}
Prepared by, Santosh Kabir.
162
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


void showEmployee()
{
System.out.println("Employee data...");
System.out.println("ID=" + id );
System.out.println("Name=" + name );
System.out.println("Designation=" + desig );
System.out.println("Salary=" + salary );
}
void showGrade()
{
if(salary >= 100000 )
System.out.println("Grade A" );
else if( salary >= 50000 && salary < 100000 )
System.out.println("Grade B" );
else if( salary >= 15000 && salary < 50000 )
System.out.println("Grade C" );
else
System.out.println("Grade D" );
}
}
class Emp
{
static public void main(String []args) throws IOException
{
Employee []a = new Employee[4]; // creates array of ref. var
int i;
for(i=0;i<4; i++)
{
a[i] = new Employee(); // creates objects
a[i].getEmployee();
}
for( i=0; i<4; i++)
{
a[i].showEmployee();
a[i].showGrade();
}
}
}
------------------------------------

28. Count uppercase, lower case letters, blank spaces and digits in a string. (Q3.a )
import java.io.* ;
class CountChars
{
public static void main(String[]args) throws IOException
{
Prepared by, Santosh Kabir.
163
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


BufferedReader in = new BufferedReader( new InputStreamReader( System.in ));
System.out.println("Enter a string:");
String s = in.readLine();
int len = s.length();
//counters for upper-case, lower-case, blanks, digits
int uc=0, lc=0, bs=0 , dg=0;
for( int i=0; i<len; i++ )
{
char ch = s.charAt( i ); // read ith char.
if( Character.isUpperCase( ch ) )
uc++;
else if( Character.isLowerCase( ch ) )
lc++;
else if( Character.isWhitespace( ch ) )
bs++;
else if( Character.isDigit( ch ) )
dg++;
}
System.out.println("Uppercase letter count=" + uc);
System.out.println("Lowercase letter count=" + lc);
System.out.println("Blank space count=" + bs);
System.out.println("Digit count=" + dg);
}
}
-------------------------------------

29. Sorting 5 integers in array. (Q3.b )


class SortArray
{
public static void main(String []args) throws IOException
{
int i, j, last;
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ));
int [ ]a = new int[ 5 ];// allocate array of length : 5
System.out.println("Enter 5 numbers:");
for(i=0; i<5; i++) // input nos
a[i] = Integer.parseInt( in.readLine());
// sorting: bubble sort method
for( last= 4; last> 0; last-- )
{
for(i= 0; i<last; i++ )
{
if( a[i+1] < a[i] ) // swapping
{
int t = a[i];
Prepared by, Santosh Kabir.
164
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


a[i] = a[i+1];
a[i+1] = t;
}
}
}
System.out.println("Sorted array...");
for(i=0; i<5 ;i++ )
System.out.println( a[i] );
}
}
--------------------------------

30. Finding area of rectangle, circle, triangle. use abstract class. (Q4.b )
import java.io.*;
abstract class Shape
{
abstract void getValues( ) throws IOException;
abstract double area( );
}
class Rectangle extends Shape
{
double Len, Br;
void getValues() throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ));
System.out.println("Enter Lenght and Breadth:");
Len = Double.parseDouble( in.readLine() );
Br = Double.parseDouble( in.readLine() );
}
double area()
{
return Len*Br;
}
}
class Triangle extends Shape
{
double Base, Ht;
void getValues() throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ));
System.out.println("Enter Base and Height:");
Base = Double.parseDouble( in.readLine() );
Ht = Double.parseDouble( in.readLine() );
}
Prepared by, Santosh Kabir.
165
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


double area()
{
return 0.5 * Base * Ht;
}
}
class Circle extends Shape
{
double Radius;
void getValues() throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ));
System.out.println("Enter Radius:");
Radius = Double.parseDouble( in.readLine() );
}
double area()
{

OUTPUT :
return 3.14 * Radius * Radius;

Enter Lenght and Breadth:


20

class AbstrsctTest

Area of Rectabgle=100.0

Enter Base and Height:


public static void main(String [ ]args) throws IOException

10

5
Rectangle r = new Rectangle();

Area of Triangle=25.0

r.getValues();

Enter Radius:

System.out.println("Area of Rectabgle=" + r.area() );

10
Area of Circle=314.0

Triangle t = new Triangle();


t.getValues();
System.out.println("Area of Triangle=" + t.area() );
Circle c = new Circle();
c.getValues();
System.out.println("Area of Circle=" + c.area() );
}
}
-------------------------------------

Dec-2010
31. Largest of three numbers read from command line. (Qn.1 C )
class DEC10_1C
{
public static void main(String []args)
{
int a, b , c, m;
Prepared by, Santosh Kabir.
166
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


if( args.length >= 3 )

Sem IV IT

Web Programming

a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = Integer.parseInt(args[2]);

By Santosh Kabir.

m = a>b ? a : b;
m = c>m ? c : m;

Regular batches at
Andheri , Thane

System.out.println("Largest no = " + m);


}
else
System.out.println("Input 3 nos at command line");
}
}
---------------------------------

32. Display message on applet. (Qn.2 A )


import java.applet.*;
import java.awt.*;
public class DEC10_2A extends Applet
{
public void paint(Graphics g )
{
g.drawString("All the Best", 50, 50 );
}
}
// <applet code=DEC10_2A height=300 width=300> </applet>

----------------------------33. I/p integer and display its digits. e.g. 1691

o/p 1 6 9 1

(Qn 2. B )

class DEC10_2B
{
public static void main(String []args) throws IOException
{
int a;
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter an integer:");
a = Integer.parseInt( in.readLine() );
Integer obj = new Integer(a );
String s = obj.toString();

OUTPUT:

System.out.println("Digits:" );

Enter an integer:

for(int i =0; i< s.length(); i++ )

23543

System.out.print( s.charAt(i) + " " );

Digits:
2 3 5 4 3

}
}
------------------------------

santoshkabir@yahoo.com ( or facebook )

Prepared by, Santosh Kabir.


167
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


34.

Displaying pattern: (Qn 3. A )

1
0 1
1 0 1
0 1 0 1
class DEC10_3A
{
public static void main(String []args) throws IOException
{
int i, j, n;
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
System.out.print("Enter an integer:");
n = Integer.parseInt( in.readLine() );
for( i=1; i<=n; i++ )

OUTPUT:

Enter an integer:6
int k = i%2;

for( j=1; j<=i; j++ )

01

101
System.out.print( k + " ");

0101

k = (k == 1) ? 0 : 1;

10101

010101

System.out.println();
}
}
}
-----------------------------

35. Counting uppercase, lower case letters and blank spaces. (Qn 3. B )
class DEC10_3B
{
public static void main(String []args) throws IOException
{
String s;
int lc=0, uc=0, sp=0;
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
System.out.print("Enter a string :");
s = in.readLine();
int len = s.length();
for( int i=1; i< len ; i++ )
{
char ch = s.charAt(i);
if( Character.isUpperCase(ch) )
uc++;
else if( Character.isLowerCase(ch) )
lc++;
Prepared by, Santosh Kabir.
168
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


else if( Character.isWhitespace(ch) )
sp++;
OUTPUT:

Enter a string :This is a new String


System.out.println("No of Uppercace letters:" + uc );

No of Uppercace letters:1

System.out.println("No of Lowercace letters:" + lc );

No of Lowercace letters:14

System.out.println("No of spaces:" + sp );

No of spaces:4

}
}
------------------------------36. To find sum of series. 1 - 1/2 + 1/3 - 1/4 + ... 1/n (Qn 4. B )
class DEC10_4B
{
public static void main(String []args) throws IOException
{
int n;
double sum=0, i;
int s = 1; // To change sign + or BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
System.out.print("Enter n :");
n = Integer.parseInt( in.readLine() );
for( i=1; i<= n ; i++ )
{
sum = sum + 1/i * s;
s = -s; // change sign for next term
}

OUTPUT:
Enter n :4
Sum of
series=0.5833333333333333

System.out.println("Sum of series=" + sum );


}
}
------------------------------

37. Vector with students names. (Qn 5. B)


import java.util.*;
class DEC10_5B
{
public static void main(String [ ]args) throws IOException
{
Vector v = new Vector(10, 5 );
int i;
String name;
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter 5 names:");
for( i=1; i<= 5 ; i++ )
{
Prepared by, Santosh Kabir.
169
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


name = in.readLine(); // input name and add to vector
v.add(name);
}
while( true )
{
int opt;
System.out.print("1.. Add new name | ");
System.out.print("2.. Delete name | ");
System.out.print("3.. Display names | ");
System.out.println("4.. Quit");
System.out.print("Enter option :");
opt = Integer.parseInt( in.readLine() );
switch( opt )
{
case 1 : System.out.print("Enter a name:");
name = in.readLine();
v.add(name);
break;
case 2 : System.out.print("Enter a name to delete :");
name = in.readLine();
v.remove( name );
break;
case 3 : System.out.println("Names ...");
for(i=0; i< v.size(); i++ )
System.out.print( v.elementAt(i) + " , " );
System.out.println();
break;
case 4 : return;
}
}
}
}

santoshkabir@yahoo.com ( or facebook )
Prepared by, Santosh Kabir.
170
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.

OUTPUT:
Enter 5 names:
AJAY
SANJAY
SAM
RAJ
TOM
1.. Add new name | 2.. Delete name | 3.. Display names | 4.. Quit
Enter option :1
Enter a name:ABHI
1.. Add new name | 2.. Delete name | 3.. Display names | 4.. Quit
Enter option :3
Names ...
AJAY , SANJAY , SAM , RAJ , TOM , ABHI ,
1.. Add new name | 2.. Delete name | 3.. Display names | 4.. Quit
Enter option :2
Enter a name to delete :SAM
1.. Add new name | 2.. Delete name | 3.. Display names | 4.. Quit
Enter option :3
Names ...
AJAY , SANJAY , RAJ , TOM , ABHI ,
1.. Add new name | 2.. Delete name | 3.. Display names | 4.. Quit
Enter option :4

-----------------------------

38. Calculate area of square and traingle. use of abstract class. (Qn 6. A)
abstract class Shape
{
abstract double area( double d1, double d2 );
}
class Square extends Shape
{
double area( double d1, double d2)
{
return d1*d2;
}
}
class Triangle extends Shape
{
double area( double d1, double d2)
{
return 0.5* d1 * d2;
}
}
Prepared by, Santosh Kabir.
171
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


class DEC10_6A
{
public static void main(String [ ]args) throws IOException
{
double a=10 , b= 12;
// -- students can input values for a and b
Square s = new Square();

OUTPUT:

System.out.println("Area of square=" + s.area(a, a) );

Area of square=100.0
Area of triangle=60.0

Triangle t = new Triangle();


System.out.println("Area of triangle=" + t.area(a, b) );
}
}
---------------------------

39. Write a program with two child threads to display 1 A 2 B 3 C


One displays Alphabet and the other a digit. (Q6. b )
class Child1 extends Thread
{
public void run()
{
for(int i=1; i<= 5; i++ )
{
System.out.print( i + " "); // digit and a space
try
{
yield();
}catch(Exception e) { }
}

Sem IV IT

}
}
class Child2 extends Thread

Web Programming

{
public void run()
{
char ch='A';
for(int i=1; i<= 5; i++ )

By Santosh Kabir.
Regular batches at
Andheri , Thane

{
System.out.print( ch + " "); // Alphabte and a space
ch++;
try
{
yield();
}catch(Exception e) { }
}
}
}
Prepared by, Santosh Kabir.
172
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


class DEC10_6B
{
public static void main(String[]args)
{
System.out.println("Program with two child threads...");
Child1 t1 = new Child1();
Child2 t2 = new Child2();
t1.start();

OUTPUT:

t2.start();

Program with two child threads...

1 A 2 B 3 C 4 D 5 E

}
----------------------------------------

June- 2011
40. Three Vectors with Bank Account operations. (Q 2. A )
import java.io.*;
import java.util.*;
class Account
{
int acno;
double balance;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
void input() throws IOException
{
System.out.println("Ac.No and amount :");
acno = Integer.parseInt( in.readLine() );
balance = Double.parseDouble(in.readLine());
}
void display()
{
System.out.println("DATA ... Ac No :" + acno + " Balance=" + balance );
}
void addAmt(double amt)
{
balance += amt;
}
void subAmt(double amt)
{
balance -= amt;
}
}

www.santoshkabirsir.com
Prepared by, Santosh Kabir.
173
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


class Data
{ // ACT NO, AMOUNT AND DATE FOR DEPOSIT / WITHDRAWAL
int acno;
double amount;
String date;
Data( int no, double a, String d)
{
acno = no;
amount = a;
date = d;
}
}
class JUN11_2
{
static Vector bank = new Vector(10, 4);
static Vector deposit = new Vector(20, 5);
static Vector withdraw = new Vector(20, 5);
// method to check acct no is present or not
static int check( int no )
{
for( int i=0; i<bank.size(); i++ )
{
Account a = (Account) bank.elementAt(i);
if( a.acno == no )
return i;
}
return -1;
}
public static void main(String[]args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Account m; // varibales reqd for different operations
int i, n;
double a, b;
String dt;
while( true ) // continuous loop
{
System.out.println("Bank account operations");
System.out.println("1 ... New act");
System.out.println("2 ... Deposit");
System.out.println("3 ... Withraw");
System.out.println("4 ... View act");
System.out.println("5 ... EXIT");
Prepared by, Santosh Kabir.
174
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


int oper = Integer.parseInt( in.readLine() );
switch( oper )
{
case 1 : // NEW ACCOUNT CREATION
System.out.println("- NEW ACCOUNT -");
m = new Account( );
m.input();
bank.addElement( m );
break;
case 2 : // DEPOSIT OPERATION
System.out.println("- DEPOSIT -");
System.out.print("Enter no :");
n = Integer.parseInt( in.readLine() );
i = check(n);
if( i != -1 )
{
System.out.print("Enter amount to deposit:");
b = Double.parseDouble( in.readLine() );
System.out.print("Enter Date:");
dt = in.readLine();
Data d = new Data( n, b, dt );
m = (Account)bank.elementAt(i);
m.addAmt( b );
deposit.addElement( d );
m.display();
break;
}

OUTPUT :
Bank account operations
1 ... New act
2 ... Deposit
3 ... Withraw
4 ... View act
5 ... EXIT
1
- NEW ACCOUNT Ac.No and amount :
123
5000
Bank account operations
1 ... New act
2 ... Deposit
3 ... Withraw
4 ... View act
5 ... EXIT
1
- NEW ACCOUNT Ac.No and amount :
234
6000
Bank account operations
1 ... New act
2 ... Deposit

else
System.out.println("Account not present");
break;
case 3: // WITHDRAW OPERATION
System.out.println("- WITHDRAWAL -");
System.out.print("Enter no :");
n = Integer.parseInt( in.readLine() );
i = check(n);

3 ... Withraw
4 ... View act
5 ... EXIT
2
- DEPOSIT Enter no :123
Enter amount to deposit:2500
Enter Date:10/12/2011
DATA ... Ac No :123 Balance=7500.0

if( i != -1 )
{
System.out.print("Enter amount to withdraw:");
b = Double.parseDouble( in.readLine() );
System.out.print("Enter Date:");
dt = in.readLine();
Data w = new Data( n, b, dt );
m = (Account)bank.elementAt(i);
m.subAmt( b );
Prepared by, Santosh Kabir.
175
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


withdraw.addElement( w );
m.display();

OUTPUT contd..

break;
}

Bank account operations

else

1 ... New act

System.out.println("Account not present");

2 ... Deposit
3 ... Withraw

break;

4 ... View act


5 ... EXIT

case 4: // DISPLAY ACCT DATA

System.out.println("- VIEW ACCT. -");

- WITHDRAWAL -

System.out.print("Enter no :");

Enter no :566

n = Integer.parseInt( in.readLine() );

Account not present

i = check(n);

Bank account operations

if( i != -1 )

1 ... New act

2 ... Deposit

m = (Account) bank.elementAt(i);

3 ... Withraw

m.display();

4 ... View act

5 ... EXIT

else

System.out.println("Account not present");


break;

- WITHDRAWAL Enter no :234


Enter amount to withdraw:1500

case 5 :

Enter Date:11/12/11

System.out.println("- EXIT -");

DATA ... Ac No :234 Balance=4500.0

return; // stop program

Bank account operations

1 ... New act


2 ... Deposit

3 ... Withraw
4 ... View act

5 ... EXIT

5
- EXIT -

-----------------------------

41. Finding sum of digits of a no recursively. (Q 3. B)


import java.io.*;
class JUN11_3B
{
static int sum( int no )
{
if( no == 0)
return 0;
else
return no%10 + sum(no/10);
}
Prepared by, Santosh Kabir.
176
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


public static void main(String[ ]args) throws IOException
{
int n, s;
BufferedReader in = new BufferedReader( new InputStreamReader( System.in));
System.out.println("Enter a number");
n = Integer.parseInt( in.readLine() );

OUTPUT :

s = sum( n );

Enter a number
3452

System.out.println("Sum of digits= " + s);

Sum of digits= 14

}
}
-------------------------------

42. Sum of Cubes of digits of a no. input from command line. (Q 5. B )


import java.io.*;
class JUN11_5B
{
public static void main(String[]args) throws IOException
{
int no, d, s=0;
no = Integer.parseInt( args[0] );
while( no != 0 )
{
d = no%10;
s += d*d*d;
no = no /10;

OUTPUTS :
1)
> java JUN11_5B

153

Sum of cubes of digits= 153


2)
> java JUN11_5B

251

Sum of cubes of digits= 134

}
System.out.println("Sum of cubes of digits= " + s);
}
}

--------------------------

Dec - 2011
43. Program to demonstrate some Thread methods. ( Q.2 A )
class DemoThread extends Thread
{
public void run()
{
String name = currentThread().getName();
int p = currentThread().getPriority();
System.out.println("Name= " + name + ", Prio= " + p);
try
{

Prepared by, Santosh Kabir.


177
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.

for(int i = 1; i <= 5; i++)


{
System.out.print( name + i + "..");
Thread.sleep(5);
}
}catch(Exception e)

System.out.println( name + " ends...");


}

Example output :
main starts ....

A is Not alive

class Thread2

Name= A, Prio= 2

Name= B, Prio= 8
A is alive

{
public static void main(String args[])
{
System.out.println("main starts ....");

B1..Name= C, Prio= 4
A1..C1..B2..C2..A2..B3..C3..A3..B4..C4..A4..B5..C5..A5..B ends...
C ends...
A ends...

DemoThread dt1 = new DemoThread();


dt1.setPriority( 2 );
dt1.setName("A");
DemoThread dt2 = new DemoThread();
dt2.setPriority( 8 );
dt2.setName("B");
DemoThread dt3 = new DemoThread();
dt3.setPriority( 4 );
dt3.setName("C");
if( dt1.isAlive() )
System.out.println("A is alive" );
else
System.out.println("A is Not alive" );
dt1.start(); // spawns a new thread and runs new thread through dt1 object
dt2.start(); // spawns a new thread and runs new thread through dt2 object
dt3.start(); // spawns a new thread and runs new thread through dt3 object
if( dt1.isAlive() )
System.out.println("A is alive" );
else
System.out.println("A is Not alive" );
}
}
---------------------------Prepared by, Santosh Kabir.
178
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

www.santoshkabirsir.com
Solved Exam Programs

Complete Programs from previous exams.


44. Sum of series 1 + 1/2^2 + 1/3^2 + 1/4^2 ...+ 1/n^2

(Q 2. B )

import java.io.*;
class DEC11_2B
{
public static void main(String []args) throws IOException
{
int n;
double sum=0, i;
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
System.out.print("Enter n :");
n = Integer.parseInt( in.readLine() );
OUTPUT:

for( i=1; i<= n ; i++ )

Enter n :5
Sum of series=1.4636111111111112

sum = sum + 1/ (i*i);


System.out.println("Sum of series=" + sum );
}
}
--------------------------------

45. Store 5 names in Vector. Also sort the list in aplhabetic order and display. (Q .3 A )
import java.util.*;
import java.io.* ;
class DEC11_3A
{
public static void main(String [ ]args) throws IOException
{
int i, j;
String name;
Vector v = new Vector(5);
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter 5 names:");
for( i=1; i<=5 ; i++ )
{

OUTPUT:

name = in.readLine();

Enter 5 names:

v.add( name );

SAM

RAJ
AJAY

// Sorting : Bubble sorting

RAVI

for( i=4; i>=0; i--)

ABHI

Names in alpha. order[ABHI, AJAY, RAJ, RAVI, SAM]

for( j=0; j< i; j++ )


{
String s1 = (String)v.elementAt( j );
String s2 = (String)v.elementAt( j+1 );
Prepared by, Santosh Kabir.
179
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


if( s2.compareTo( s1 ) < 0 )
{
v.setElementAt( s2, j );
v.setElementAt( s1, j+1 );
}
}
}
System.out.println("Names in alpha. order" + v ); // displays entire vector
}
}
-------------------------------

46. Counting frequency of given char in a given string. (Q .3 B )


import java.io.* ;
class DEC11_3B
{
public static void main(String [ ]args) throws IOException
{
int i, f=0;
String s;
char ch;
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
System.out.print("Enter a string :");
s = in.readLine();
char [ ]a = s.toCharArray();
System.out.print("Enter a char. to check:");
ch = (char) in.read();
for( i=0; i<a.length ; i++ )
{
if( Character.toLowerCase( a[i] ) ==Character.toLowerCase( ch ) )
f++;
}
System.out.println("Freq. of occurence=" + f );
}
}
-----------------------------

47. Area of Square and Rectangle using Overloaded constructors. ( Q . 5 A )


class Rect
{
int Len, Br;
Rect(int s) // One Param. for Square
{
Len = Br = s;
}
Prepared by, Santosh Kabir.
180
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.


Rect( int l, int b ) // Two param. for rectangle
{
Len = l;
Br = b;
}
int area()
{
int a = Len * Br;
return a;
}
}
class DEC11_5A
{
public static void main(String [ ]args) throws IOException

OUTPUT:

Area of square=100
Area of rectangle=40

Rect r = new Rect( 10 );


System.out.println("Area of square=" + r.area() );
Rect s = new Rect( 8 , 5 );
System.out.println("Area of rectangle=" + s.area() );
}
}
-------------------------------

48. Draw shape of house on applet window. (Qn.5 B )


import java.applet.*;
import java.awt.*;
public class DEC11_5B extends Applet
{
public void paint(Graphics g )
{
// drawing roof (Two sides)

Sem IV IT

g.drawLine(200, 50, 100, 150 );


g.drawLine(200, 50, 300, 150 );

Web Programming

// circle in roof
g.drawOval(175, 75,50,50);

By Santosh Kabir.

// Wall ( rectangle)
g.drawRect(100,150, 200,200);

Regular batches at
Andheri , Thane

// Door (rectangle)
g.drawRect(175, 200, 50, 150);
}
}

// <applet code=DEC11_5B height=500 width=500> </applet>

==========0000===========
www.santoshkabirsir.com
Prepared by, Santosh Kabir.
181
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

Complete Programs from previous exams.

Subjects Conducted by Santosh Kabir.


Semester Branch
FE Sem I

Subject
--

S.P.A.
FE Sem II

[ Structured Programming Approach ]


Programming with C.. Very important subject for Comp/IT students
and
for those who are interested in making career in I.T.

DSAA
[ Data Structures and Algo. Analysis ]
Lots of programming with Arrays, Pointers and structures.
SE Sem III [IT]

OOPM
[ Object Oriented Programming Methodology ]
Learn Object Oriented Prog with Java, with features like Exception
handling, Applets and Multithreading

DS
SE Sem III
[Comp]

[ Data Structures ]
Lots of programming with Arrays, Pointers and structures.

OOPM
(OOP with Java)

W.P.
SE Sem IV [IT]

SE Sem VI [IT]

[ Web Programming ]
(HTML, JavaScript,C#, ASP.Net,ADO.Net, PHP, JSP etc)
Want to develop your Web Site (like Yahoo, facebook ..!)..
Learn the subject seriously
If you are learning with me ... hw abt dvlping mini fb
PMRC (Old syllabus)

Regular and Vacation batches are taken at Andheri , Dadar, Thane, Dombivli.
( Demo. of programs on Projector )

Mobile : 98336 29398. Visit : www.santoshkabirsir.com

Prepared by, Santosh Kabir.


182
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]

Solved Exam Programs

You might also like