Oopm 2013 Demo
Oopm 2013 Demo
Oopm 2013 Demo
/ 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
137 - 181
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 )
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.
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)
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 :
3
Mobile : 98336 29398 ( www.santoshkabirsir.com )
Prepared by, Santosh Kabir
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.
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.
4
Mobile : 98336 29398 ( www.santoshkabirsir.com )
Prepared by, Santosh Kabir
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
Running a
program
Code Interpreted
for Solaris
Computer
with Solaris
system
Class loader
subsystem
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
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
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.
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.
2. Java Basics
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
2. Java Basics
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.
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.
10
2. Java Basics
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
11
2. Java Basics
Relational operators:
These are used to determine the relation of one operand to the other. These
operators are as follows:
< , <=,
>,
>=,
== ,
!=
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.
12
2. Java Basics
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 |.
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
13
2. Java Basics
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
14
2. Java Basics
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;
15
2. Java Basics
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
16
2. Java Basics
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.
17
2. Java Basics
in which it appears.
e.g.
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,
18
2. Java Basics
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,
19
2. Java Basics
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,
2. Java Basics
e.g.
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.
21
2. Java Basics
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.
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.
22
2. Java Basics
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.
23
2. Java Basics
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
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
24
2. Java Basics
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. ]
25
2. Java Basics
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 ]
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 ]
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
In above example class B has its own functions p() and q() and two more functions
x() and y() inherited from class A.
( 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 ]
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,
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.
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
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 );
}
}
The main() method creates objects of a class and invokes methods on it.
Parameter Passing :
Passing Parameters by Value:
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 ]
}
}
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
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 );
}
}
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:
(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 ]
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
}
}
// 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.
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 ]
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
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 ]
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 ]
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. ]
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
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,
4. Inheritance
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.
4. Inheritance
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.
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
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
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.
4. Inheritance
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
2) final methods:
A method declared with a final keyword in a class, cannot be overridden further
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.
4. Inheritance
Abstract method:
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
4. Inheritance
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
4. Inheritance
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 :
4. Inheritance
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 :
4. Inheritance
Class Relationships :
: or more Java classes present
Two
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
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
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.
4. Inheritance
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;
4. Inheritance
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().
4. Inheritance
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.
Interfaces
Defined with keyword interface
Consists of only two type of members:
Method declarations , final static
variables
Can not be instantiated by any means.
----0000----
Sem IV - IT
Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]
4. Inheritance
OOPM [ Comp / IT ]
Subject
--
S.P.A.
FE Sem II
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 )
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 ]
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.
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)
}
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.
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
[ In above explaination outputs may not be mentioned in exam answer, but explain three cases of
working of try-catch-finally ]
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);
}
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
try
{
// program segment that can generate exceptions
}
catch ( exception_type obj )
{
// Statements to handle (or describe) the exception
}
finally
{
//the code that must execute.
}
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.
Sem IV - IT
Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]
5. Exception Handling
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.
6. Packages
package :
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 :
6. Packagess
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
----0000----
Sem IV - IT
Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]
6. Packagess
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.
7. java.lang package
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
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.
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
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.
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.
7. java.lang package
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:
7. java.lang package
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
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 ;
7. java.lang package
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.
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
----0000----
Sem IV - IT
Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]
7. java.lang package
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 ]
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 :
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().
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 :
ArrayList : (class)
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 );
list.remove(2);
list.remove(3);
System.out.println("Size=" + list.size() );
System.out.println("Elements=" + list );
3
30
5
LinkedList :
( class )
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.
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 );
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
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
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.
Extract files form archive. The name of file to extract is specified as first
file name and that is indicated by option f
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 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. ]
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.
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 ]
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
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 ]
Applet class
loaded
Running
stage
start()
init()
stop()
paint()
Display
start()
Idle stage
destroy()
Terminated
(applet object
unloaded )
Graphics Programming
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
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 ]
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.
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 ]
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.
*/
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.
11. Multithreading
11. Multithreading
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
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
Thread Synchronization :
11. Multithreading
1) Synchronized method:
11. Multithreading
11. Multithreading
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
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----
11. Multithreading
Subject
--
S.P.A.
FE Sem II
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 )
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.
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.
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.
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
Reference section
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.
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
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:
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)
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
int capacity( ) *
Object clone( )
boolean contains(Object element)*
Enumeration elements( )
Object firstElement( )
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( )
Reference section
int size( ) *
String toString( )
void trimToSize( )
( 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
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
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.
Reference section
Reference section
10
10
namely
(i) public
(ii) protected
(iii) private
(iv)
private protected
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
10
(i) Try-catch
(ii) The finally keyword
(iii) Catching multiple exceptions
(iv) The throws keyword. Throwing Exception.
(b)
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/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
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.
10
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.
20
June 2009
N. B.: (1) Question No.1 is compulsory.
10
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
10
MU Exam Papers
10
10
*
* * *
* * * * *
* * *
*
4. (a) What is abstract class? Write a program to display volume of sphere and hemisphere.
10
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
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
MU Exam Papers
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
* * * *
* * *
* *
*
10
*
*
*
*
*
2. (a) What is command line argument? Write a program to find largest of three integers
10
10
10
10
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
10
10
the following.
(b) Explain lifecycle of an applet and demonstrate how to pass parameter to an applet.
MU Exam Papers
10
20
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
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
10
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
20
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
10
b) Write a program to accept a number and compute sum its digits recursively.
4. a) Explain thread life cycle.
10
10
10
10
b) Write a Java program to accept a number from command line and print the sum of cubes of
individual digits.
10
20
20
a) Snchronization
b) JVM
c) Wrapper classes
d) toString()
------------------
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]
[5]
[5]
[5]
2. a) Write a program to create multiple threads. Demonstrate the use of isAlive(), setName(),
getName(), setPriority(), getPriority() methods of Thread class.
[10]
[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]
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]
[20]
MU Exam Papers
June-2008
1. GCD using given Euclid's algo. (Q2.a )
import
java.io.* ;
class GCD
{
int no1, no2; // the two numbers
MU Exam Questions
June-08 to Dec- 11 (old Syl. )
OUTPUT :
x = Integer.parseInt( in.readLine() );
y = Integer.parseInt( in.readLine() );
12
40
g1.findGCD();
Two numbers:12,40
g1.display();
GCD = 4
Enter no1, no2 :
64
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 ]
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;
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
OUTPUT :
23
a[i].input();
ABHI
56
65
67
34
RAJU
67
76
65
42
a[i] = a[i+1];
TINA
a[i+1] = temp;
60
54
76
34
RAJU
67
76
65
208
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 ]
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;
}
}
}
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 ]
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 :
Enter n and r :
n = Integer.parseInt( in.readLine() );
r = Integer.parseInt( in.readLine() );
Compinations :20.0
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 ]
OUTPUT :
Enter n :
5
Sum :2.283333333333333
}
}
-------------------------------------
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
------------------------------------
santoshkabir@yahoo.com ( or facebook )
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
}
OUTPUT :
class A
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
Marks in 3 subjects :
76
System.out.println("Student ..." + (i+1) );
76
87
a[i].input();
Student ...3
Marks in 3 subjects :
65
76
System.out.println("Totals are...");
87
Student ...4
Marks in 3 subjects :
54
56
max = a[i].total;
67
id = i;
Student ...5
Marks in 3 subjects :
76
87
a[id].display();
65
R.no=222
----------------------------------
Marks :76
76
87
Sem IV IT
Web Programming
By Santosh Kabir.
{
for( j=1; j<= n-i; j++)
System.out.print( " " );
Regular batches at
Andheri , Thane
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 );
}
}
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()
{
Example output
t1.start();
t2.start();
t3.start();
// checking whether threads are alive (running/runnable)
if(t1.isAlive() )
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:
}
-----------------------------------
( 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 ]
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
OUTPUT Contd..
The book list is as follows...
ID=111 .. Name : CP-II
-------------------------------------
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
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 ]
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");
}
}
------------------------------------
OUTPUT :
Enter a String :this is mumbai city
Modified String :This Is Mumbai City
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
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 ]
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 ]
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 ]
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 ]
OUTPUT :
return 3.14 * Radius * Radius;
class AbstrsctTest
Area of Rectabgle=100.0
10
5
Rectangle r = new Rectangle();
Area of Triangle=25.0
r.getValues();
Enter Radius:
10
Area of Circle=314.0
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 ]
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
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:
23543
Digits:
2 3 5 4 3
}
}
------------------------------
santoshkabir@yahoo.com ( or facebook )
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;
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 ]
No of Uppercace letters:1
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
santoshkabir@yahoo.com ( or facebook )
Prepared by, Santosh Kabir.
170
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]
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 ]
OUTPUT:
Area of square=100.0
Area of triangle=60.0
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 ]
OUTPUT:
t2.start();
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 ]
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 ]
OUTPUT contd..
break;
}
else
2 ... Deposit
3 ... Withraw
break;
- WITHDRAWAL -
System.out.print("Enter no :");
Enter no :566
n = Integer.parseInt( in.readLine() );
i = check(n);
if( i != -1 )
2 ... Deposit
m = (Account) bank.elementAt(i);
3 ... Withraw
m.display();
5 ... EXIT
else
case 5 :
Enter Date:11/12/11
3 ... Withraw
4 ... View act
5 ... EXIT
5
- EXIT -
-----------------------------
OUTPUT :
s = sum( n );
Enter a number
3452
Sum of digits= 14
}
}
-------------------------------
OUTPUTS :
1)
> java JUN11_5B
153
251
}
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
{
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...
www.santoshkabirsir.com
Solved Exam Programs
(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:
Enter n :5
Sum of series=1.4636111111111112
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
RAVI
ABHI
OUTPUT:
Area of square=100
Area of rectangle=40
Sem IV IT
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);
}
}
==========0000===========
www.santoshkabirsir.com
Prepared by, Santosh Kabir.
181
Contact No: 98336 29398 [ santoshkabir@yahoo.com ]
Subject
--
S.P.A.
FE Sem II
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 )