oopm lab manual 2014 updated

59
RAMRAO ADIK INSTITUTE OF TECHNOLOGY, NERUL LAB MANUAL Object Oriented Programming and Methodology (Computer Engineering)

Upload: phadatareaniket

Post on 26-Dec-2015

190 views

Category:

Documents


6 download

DESCRIPTION

oopm

TRANSCRIPT

Page 1: OOPM Lab Manual 2014 Updated

RAMRAO ADIK INSTITUTE OF TECHNOLOGY,

NERUL

LAB MANUAL

Object Oriented Programming and Methodology

(Computer Engineering)

Page 2: OOPM Lab Manual 2014 Updated

LIST OF EXPERIMENTS

Subject: OOPM Lab Session: 2hrs/week

Year & Semester: S.E. Sem III(CBGS Revised) No. of Lectures per week: 4

Facutly Name: Prof.Rajashree Shedage, Prof. Smita Bhoir, Prof. Smita Bharne

Sr.No. Title

1 Write a simple program in Java to Swap two numbers.

2 Write a program to find maximum and minimum between 3 numbers using decision making statements (input with command-line argument)

3 Write a program to find smallest of n numbers taken from user using array.

4 Write a program to demonstrate use of different methods of String class.

5 Write a program to create a Circle class and implement method to calculate area of circle.

6 Write a program to implement method overloading to calculate area of rectangle.

7 Write a program to perform addition of two complex numbers by passing and returning object as an argument.

8 Write a program to implement multilevel inheritance demonstrating method overriding.

9 Write a program to demonstrate use of collection classes.

10 Write program to demonstrate interfaces in java.

11 Write a program to create and import your own package.

12 Write a program on exception handling

13 Write a program to demonstrate multithreading.

14 Write a program for implementation of Applet to print different shapes and string..

15 Case Study :Your Application

Page 3: OOPM Lab Manual 2014 Updated

Experiment No. 1

Aim: Write a simple program in Java to Swap two numbers.

Theory:

Java is an object-oriented language similar to C++, but simplified to eliminate language features that cause common programming errors. Java source code files (files with a .java extension) are compiled into a format called bytecode (files with a .class extension), which can then be executed by a Java interpreter. Compiled Java code can run on most computers because Java interpreters and runtime environments, known as Java Virtual Machines (JVM), exist for most operating systems, including UNIX, the Macintosh OS, and Windows. Bytecode can also be converted directly into machine language instructions by a just-in-time compiler (JIT).Java is a general purpose programming language with a number of features that make the language well suited for use on the World Wide Web. Small Java applications are called Java applets and can be downloaded from a Web server and run on your computer by a Java-compatible Web browser, such as Netscape Navigator or Microsoft Internet Explorer.

You can follow the step by step procedure to arrive at the result.

1. Create a Java program by typing its code in any text editor such as Notepad.

2. Save the program by the name same as that of the class containing the main () method. For e.g. if you create a program to add two integers then name the class a as AddTwoInt. Class AddTwoInt

{ public static void main (String args []) { int a=5, b=8, c=0; c=a+b; System.out.println (“The sum is:” + c); }

Save this program in the directory where JDK is installed. Java Development Kit (JDK) is a program development environment for writing Java applets and applications. It consists of numerous development tools, classes, and methods. The JDK provides a collection of the Java tools, which are used while developing and running Java programs. For e.g.

C:\java\jdk1.5.0_04\bin\ with the file name AddTwoInt.java.

3. Now go to the start menu and open the “Run” dialogue box and type cmd. You will see the command prompt.

Page 4: OOPM Lab Manual 2014 Updated

4. Now switch to the directory where you have saved the Java program i.e. C:\java\jdk1.5.0_04\bin\

5. Type javac AddTwoInt.java to compile the program.

6. You will see that the program compiles successfully and you are left with the prompt C:\java\jdk1.5.0_04\bin\. and AddTwoInt.class file will be created in the C:\java\jdk1.5.0_04\bin directory.

7. Now to run the program type java AddTwoInt

You will see the output as: The sum is: 13

Explanation of main method declaration :-

public static void main( String args[ ] )

main( ) :- is the entry point of the program. Rather we can say it is the main gate to enter inside the apartment. It should be public because the compiler need to enter inside the method (The guest need to access the apartment to reach the security guard).

public :- The main method must be public because it is call from outside the class. It is called by jvm.

static :- Since main method is written inside a class and to access a method of a class we need to create an object of that class first. Since main () is the method which compiler need to call before creating any object of that class we need to declare main as static. Static methods can be called directly by using the class name. That’s why the name of the file should be same as the name of the class contain main () method.

void :- Since the method can return any type of value or it might not return anything also so the compiler is designed in such a way that it should not take any return value so we declare main as void type.

Algorithm:

1. Start.

2. Define class Swap

3. Initialize value of a, b.

4. Declare a temporary variable.

5. Swap a & b.

5.1 temp <- a

Page 5: OOPM Lab Manual 2014 Updated

5.2 a <- b

5.3 b <- temp

6. Display a & b.

7. Stop.

Conclusion: Thus with this first experiment we have studied how to create, save, compile and execute simple java program.

Page 6: OOPM Lab Manual 2014 Updated

Experiment No. 2

Aim : Write a program to find maximum and minimum between 3 numbers using decision making statements (input with command-line argument).

Theory : Java application can accept any number of arguments directly from the command line. The user can enter command-line arguments when invoking the application. When running the java program from java command, the arguments are provided after the name of the class separated by space. For example, suppose a program named CmndLineArguments that accept command line arguments as a string array and print them on standard output device.

CmndLineArguments.java

class CmndLineArguments{

public static void main(String[] args){

int length = args.length; if (length <= 0)

{System.out.println("You need to enter some arguments.");

}for (int i = 0; i < length; i++){

System.out.println(args[i]);}

}}

Compile the program with the statement javac CmndLineArguments.java

Run program with some command line arguments like: java CmndLineArguments zero one two three

OUTPUT : zeroOne two three

Parsing Numeric Command-Line Arguments :

Page 7: OOPM Lab Manual 2014 Updated

If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "34", to a numeric value. Here is a code snippet that converts a command-line argument to an int:class example{

Public static void main(String args[]){

int firstArg, secondArg;firstArg = Integer.parseInt(args[0]); secondArg = Integer.parseInt(args[1]); System.out.println(“ first input: “+ firstArg);

System.out.println(“ second input: “+ secondArg);}

}parseXXX : Accepts a string value and converts that value into primitive data type. It is also called as the parser method in which XXX represents a Wrapper class. For example, parseInt( ), parseFloat( ), parseDouble( ).

Algorithm:1. Start.

2. Define class Maximum.

3. Declare 3 integer variables a, b and c.

4. Read 3 variables a, b, c.

5. Set a= Integer.parseInt(args[0])

Set b= Integer.parseInt(args[1]) Set c=

Integer.parseInt(args[2])

6. if(a>b)

{

large=a;

}

else

{

large=b;

}

if( c>large)

{

Page 8: OOPM Lab Manual 2014 Updated

large=c;

}

else

{

large=large;

}

7. Display “large “ as maximum number.

8. Stop.

Conclusion : We have studied command line argument concept to read input from user. Three integer numbers are taken from user at execution time and maximum number is displayed on screen.

Page 9: OOPM Lab Manual 2014 Updated

Experiment No. 3

Aim : Program to perform smallest of n numbers taken from user using array.

Theory:

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

An array of 10 elements.

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

Array with more than one dimension is called multidimensional array. The two dimensional

arrays is called a matrix.

Declaring Array:

Syntax :

data_type Array_name[ ]=new

OR

data_type[][] array_name;

Page 10: OOPM Lab Manual 2014 Updated

Creating Multi-Dimensional Array:

Syntax :

data_type Array_name[][] = new data_type[no_of_rows][no_of_columns];

For example: int a[][] = new int[3][3];

float ab[][]=new float[5][5];

Algorithm :

1. Start2. Decalre class MinElement3. Declare the integer array a[10] and a variable min.4. Take input in array from user.5. Initialize min = a[0].6. i. Start for loop with i=0.

ii. compare the array value with min.

iii. if min>a[i] store the value a[i] into min

iv. increment the value of I by 1.

7. Print the min value.8. Stop.

Conclusion: Thus we have studied array and have implemented program to find minimum value

from an array.

Page 11: OOPM Lab Manual 2014 Updated

Experiment No. 4

Aim: Write a program to demonstrate use of different methods of String class.

Theory: String manipulation is the most common part of many Java programs. Strings are very

important in programming languages as they are used to process long textual/symbolic

information. The information you provide is in form of ordered sequence of characters and

symbols is called as string.

In c, c++ character arrays are used to process long textual information. Using character

arrays is time consuming so in java, strings are not considered as the fundamental data type. In

Java String class is provided to work with strings along with facility of character array.

In Java, Strings are immutable as once an object of the String class is created and

initialized with some value then it cannot be changed. The Java development environment

Page 12: OOPM Lab Manual 2014 Updated

provides two classes that store and manipulate character data: String, for constant strings, and

StringBuffer, for mutable strings.

The StringBuffer class is used to represent characters that can be modified. This is simply

used for concatenation or manipulation of the strings. StringBuffer is mainly used for the

dynamic string concatenation which enhances the performance. A string buffer implements a

mutable sequence of characters. A string buffer is like a String, but can be modified. At any point

in time it contains some particular sequence of characters, but the length and content of the

sequence can be changed through certain method calls.

Defining string with String class :

1. String str = new String ( );

str = “Hello”;

2. String str = “Hi”;

Defining string with StringBuffer class :

StringBuffer str = new StringBuffer(“Hello”);

Defining array of strings :

String array[] ={“str1”, ”str2”, ”str3” , “str4”};

Different String class methods are given below :

1. s.length( ) : This method is used to find the length of the string s.

Page 13: OOPM Lab Manual 2014 Updated

2. s1.concat(s2 ) : This method is used to concatenate two strings i.e. string s1 and string s2.

3. s1.toLowerCase( ) : This method is used to convert string s1 to lower case.

4. s1.toUpperCase( ) : This method is used to convert string s1 to upper case.

5. s1.substring(n) : This method gives the sub string starting from the nth character till end position.

6. s1.substring(n,m) : This method gives the sub string starting from the nth character upto mth character, excluding mth character.

7. s1.charAt(n) : This method is used to get the character present at index ‘n’ of the given string s1.

8. s1.equals(s2) : This method returns true if string s1 is equal to string s2.

9. s1.compareTo(s2) : This method returns negative if s1<s2, returns positive if s1>s2 and returns zero if string s1=s2.

10. s1.indexOf(‘x’) : This method gives the position of the first occurrence of character ‘x’ in the string s1.

11. s1.lastIndexOf(‘x’) : This method gives the position of the last occurrence of character ‘x’ in the string s1.

Page 14: OOPM Lab Manual 2014 Updated

12. s1.trim( ) : This method removes the white spaces at start and end of the string s1.

Algorithm :

(Note: Algorithm depends on the methods which you are going to implement in this experiment.)

Conclusion: With this experiment we have learned difference between String and StringBuffer

and we have also studied different methods of String class

Experiment No. 5

Aim: Write a program to create a Circle class and implement method to calculate area of circle.

Theory:

Objects are the basic runtime entities in an object oriented system. A class may be thought of as a ‘data type’ and an object as ‘variable’ of that data type. The data and code of the class are accessed by object of that class.

In this program, the object of class circle is used to access the methods: getdata() & area() of this class.

Syntax:-

class Class_Name { public static void main(String args[]) { // Statements; }

}

Page 15: OOPM Lab Manual 2014 Updated

For example:-

class Room { float length; float breadth; void getdata(float a, float b) { length=a; breadth=b; } public static void main(String args[]) { float area; Room r1=new Room(); R1.getdata(20,10); area=r1.length*r1.breadth; System.out.println(“Area= ”+area); }}

Output:-Area=200.0

Algorithm:

1. Start.

2. Declare a class named Circle.

3. Initialize the required variables.

4. Declare a method getdata() and get value of radius from main function as a

parameter.

5. Declare a method area to calculate the area of circle and display the result.

6. Declare main() and create object of class Circle. And access the methods with the

help of object.

7. Display the area.

8. Stop.

Page 16: OOPM Lab Manual 2014 Updated

Conclusion: Thus, we have studied how to define class and use objects to access members of class.

Experiment No. 6

Aim: Write a program to implement method overloading to calculate area of rectangle..

Theory:

Java allows to create methods that have the same name, but different parameter lists and different definitions. This is called method overloading.

class ClassName { void Function1(data_type a, data_type b) { // Statements } void Function1(data_type a, data_type b, data_type c) { // Statements } public static void main(String args[])

Page 17: OOPM Lab Manual 2014 Updated

{ ClassName obj=new ClassName(); obj.Function1(Value1,Value2); obj.Function1(Value1,Value2,Value3); }}

For example:- class Calculation { void sum(int a,int b) {System.out.println("Addition of two numbers is:"+(a+b)); }void sum(int a, int b, int c) { System.out.println("Addition of three numbers is:"+(a+b+c));}public static void main(String args[]){Calculation c=new Calculation();c.sum(10,40,60);c.sum(20,20);}}

Output:-

Addition of two numbers is: 110Addition of three numbers is: 40

Algorithm:

1. Start.

2. Declare a class Rectangle.

3. Initialize the required variables.

4. Declare two methods with same name having parameter of different data type. Calculate area in the methods itself.

5. Declare main() and create object of class. And access the methods with the help of object.

6. Display the result.

Page 18: OOPM Lab Manual 2014 Updated

7. Stop.

Conclusion: Thus, we have calculated the absolute value of number using one of the feature of

java called method overloading.

Experiment No. 7

Aim: Write a program to perform addition of two complex numbers by passing and returning object as an argument.

Theory: A constructor is a special public member method whose task is to initialize the object data members when an object is declared. The constructor of a class should have the same name as the class. For example if the name of class is Employee then the constructor is a method with the name Employee( ).

Characteristics of a constructor are :

1. They should be declared in the public section.

2. They automatically get invoked when the objects are created.

3. They do not have return types not even void and therefore they cannot return values.

4. Like other methods they can have default arguments.

Types of Constructor:

Page 19: OOPM Lab Manual 2014 Updated

1. Default Constructor: A constructor without arguments is called a default constructor. When no constructor is created explicitly then Java first implicitly creates a constructor without any parameter and invokes it. The default constructor then initializes the instance variables to default values, i.e. zero for numeric data types, null for string type and false for Boolean.

2. Parameterized Constructor: The constructor with arguments is called a parameterized constructor. In parameterized constructors the instance variable is initialized automatically at run time according to the values passed to parameters during the object creation.

Constructor overloading means we can create and use more than one constructor in a class. A constructor can be overloaded on the basis of following facts:

1. Number of parameters

2. Data type of parameters

3. Order of parameters

When we create object of the classes, the instance variables are initialized according to the constructor signature.

For example :

class Product

{

int x, y;

Product( ); //Default Constructor

Product(int a, int b ) //Parameterized Constructor

}

Algorithm :

1. Start

2. Define class complex

Page 20: OOPM Lab Manual 2014 Updated

3. Declare two variables x & y

4. Define constructor

complex()

{

x=0

y=0

}

complex(float real,float img)

{

x=real;

y=img;

}

5. Define show method to display number

6. Define sum method which takes object as an argument

void sum(complex c1,complex c2)

{

x=c1.x+c2.x;

y=c1.y+c2.y;

}

7. Define ConstructorOverload class

8. Define main method

9. Create A, B,C objects of Complex type.

10. Give call to sum & show method.

11. Stop

Page 21: OOPM Lab Manual 2014 Updated

Conclusion: We have studied to define constructor, different types of constructor and constructor overloading. Hence implemented the program on addition of two complex numbers.

Experiment No.8

Aim: Write a program to implement multilevel inheritance demonstrating method overriding.

Theory: Inheritance means to take something that is already made. It is one of the most

important features of Object Oriented Programming. It is the concept that is used for reusability

purpose. Inheritance is the mechanism through which we can derive classes from other classes.

The derived class is called as child class or the subclass or we can say the extended class and the

class from which we are deriving the subclass is called the base class or the parent class or the

super class. To derive a class in java the keyword extends is used.

Types of Inheritance:

The derived class inherits some or all of the features from the base class. A class can also inherit

properties from more than one class or from more than one level.

Page 22: OOPM Lab Manual 2014 Updated

1. Single Inheritance: A derived class with only one base class is called as Single Inheritance.

2. Hierarchical Inheritance: More than one class may inherit the features of one class this process is called as Hierarchical Inheritance.

3. Multilevel Inheritance: The mechanism of deriving a class from another derived class is

called Multilevel Inheritance.

A

B

A

B C D

A

B

C

Page 23: OOPM Lab Manual 2014 Updated

4. Hybrid Inheritance: There could be situations where we need to apply one or more

types of inheritances to design a program this process is called Hybrid Inheritance.

Algorithm:

1. Start

2. Create class Car

2.1 Define a method vehicleType()

3. Define class Maruti which extends Car class.

3.1 Write brand() to display brand.

3.2 Write speed() to display speed.

4. Define class Maruti800 which extends Maruti.

4.1 Override a method speed().

5. Define main method

A

B C

D

Page 24: OOPM Lab Manual 2014 Updated

6. Create object of Maruti800 class.

8.1 Invoke vehicleType()

8.2 Invoke brand()

8.3 Invoke speed()

9. Stop.

Conclusion: We have implemented multilevel inheritance.

Experiment No.9

Aim: Write a program to demonstrate use of collection classes.

Theory: The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.

Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.

Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

The ArrayList class supports three constructors. The first constructor builds an empty array list.

ArrayList( )

The following constructor builds an array list that is initialized with the elements of the collection c.

Page 25: OOPM Lab Manual 2014 Updated

ArrayList(Collection c)

The following constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements.

The capacity grows automatically as elements are added to an array list.

ArrayList(int capacity)

Apart from the methods inherited from its parent classes, ArrayList defines following methods:

Sr.No Methods with Description

1

void add(int index, Object element)Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).

2boolean add(Object o) Appends the specified element to the end of this list.

3

boolean addAll(Collection c)Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException if the specified collection is null.

4boolean addAll(int index, Collection c) Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.

5void clear() Removes all of the elements from this list.

Page 26: OOPM Lab Manual 2014 Updated

6Object clone() Returns a shallow copy of this ArrayList.

7

boolean contains(Object o) Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

8void ensureCapacity(int minCapacity) Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

9

Object get(int index) Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).

10int indexOf(Object o) Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.

11int lastIndexOf(Object o)Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.

12

Object remove(int index) 

Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).

13protected void removeRange(int fromIndex, int toIndex) Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.

14

Object set(int index, Object element) Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).

15int size() Returns the number of elements in this list.

16Object[] toArray() Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.

17Object[] toArray(Object[] a) Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.

18 void trimToSize() 

Page 27: OOPM Lab Manual 2014 Updated

Trims the capacity of this ArrayList instance to be the list's current size.

Algorithm:

(Note: Algorithm depends on the methods which you are going to implement in this experiment.)

Conclusion: Thus we have implemented different methods of ArrayList class to understand collection classes.

Experiment No. 10

Aim: - Write program to demonstrate interfaces in java.

Theory: The mechanism of inheriting the features of more than one base class into a single class

is known as multiple inheritances. Java does not support multiple inheritance but the multiple

inheritance can be achieved by using the interface.

In Java Multiple Inheritance can be achieved through use of Interfaces by implementing

more than one interface in a class. An interface is a group of related methods with empty bodies.

Interfaces define only abstract methods and final fields. Therefore it is the responsibility of the

class that implements an interface to define the code for implementation of these methods.

Page 28: OOPM Lab Manual 2014 Updated

Syntax:

interface InterfaceName

{

return_type method_name1(parameter-list);

data_type variable_name =value;

}

Algorithm :

1. Start

2. Create class Student

2.1 Declare roll_no as int type

2.2 Write getnumber() method to get roll number of a student

2.3 Write putnumber() method to print roll number of a student

3. Define class test which extends student

3.1 Declare sem1,sem2 as float type

3.2 Write getmarks() method to get marks of a student

3.3 Write putmarks() method to print marks of a student

4. Define interface sports

4.1 Declare score of float type

4.2 declare putscore();

5. Define class Result which extends test & implements sports

Page 29: OOPM Lab Manual 2014 Updated

5.1 Declare total of type float

5.2 Write display() method

5.2.1 Calculate total of sem1,sem2 & score

5.2.2 Invoke putnumber() ,putmarks(),putscore() methods

5.2.3 Print total

5.3 Write putscore() method to display score

6. Define class Hybrid

7. Define main method.

8. Create object of class Result

8.1 Invoke getnumber()

8.2 Invoke getmarks()

8.3 Invoke display()

9. Stop

Conclusion: We have implemented multiple inheritances in Java with the help of interfaces.

Page 30: OOPM Lab Manual 2014 Updated

Experiment No. 11

Aim : Write a program to create and import your own package.

Theory :

Benefits of Packages

1. Packages allow us to organize classes into smaller units and make it easy to locate and

use the appropriate class file.

2. It helps to avoid naming conflict.

3. Packages protect classes, data and methods.

Creating a Package

Page 31: OOPM Lab Manual 2014 Updated

To create a package, you choose a name for the package and put a package statement

with that name at the top of every source file that contains the types (classes, interfaces) that you

want to include in the package.

The package statement for example, package graphics; must be the first line in the source

file. There can be only one package statement in each source file, and it applies to all types in the

file.

Package FirstPackage

Public class Rectangle

{

// class body

}

This file would be stored as A.java in a directory named FirstPackage..

If we do not use a package statement, then that class is stored in default package (unnamed

package). Generally speaking, an unnamed package is only for small or temporary applications

or when you are just beginning the development process. Otherwise, classes and interfaces

belong in named packages.

Using Package Members

The types that comprise a package are known as the package members.

To use a public package member from outside its package, you must do one of the following:

Refer to the member by its fully qualified name

Import the package member

Import the member's entire package

Page 32: OOPM Lab Manual 2014 Updated

Importing a Package Member

To import a specific member into the current file, put an import statement at the beginning of the

file before any type definitions but after the package statement, if there is one.

For example,

import FirstPackage.Rectangle;

Now you can refer to the Rectangle class by its simple name.

Rectangle myRectangle = new Rectangle();

myRectangle is an object of class Rectangle

To import an Entire Package with all the classes, we have to use the asterisk (*) wildcard

character.

import FirstPackage.*;

Algorithm :

(Note: Algorithm depends on the package name and class name used in this experiment.)

Conclusion : With this experiment we have learned to create user defined package.

Page 33: OOPM Lab Manual 2014 Updated

Experiment No. 12

Aim: Write a program on exception handling.

Theory: An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.

A Java exception is an object that describes an exceptional condition i.e., an error condition that

has occurred in a piece of code. When this type of condition arises, an object representing that

exception is created and thrown in the method that caused the error by the Java Runtime. That

method may choose to handle the exception itself, or pass it on.

If we want the program to continue with the execution of remaining code, then we should try to

catch the exception object thrown by the error condition and then display an appropriate message

for taking corrective action. This task is known as exception handling.

Page 34: OOPM Lab Manual 2014 Updated

This mechanism performs following task:

1. Find the problem(hit the exception)

2. Inform that an error has occurred ( Throw an exception)

3. Receive the error information ( catch the exception)

4. Take corrective action (handle the exception)

In try we put the code whose exceptions we want or need to trap. In catch we put the code

that will be executed if and only if an exception of the given type is thrown. A try block should

associate with at least a catch or a finally block. The sequence of try, catch and finally matters a

lot. If you modify the order of these then the code won’t compile. The final concept is there

should be a single try, multiple catch blocks and a single finally block in a try-catch-finally

block. It is always a good practice to use the finally block. The reason for using the finally block

is, any unreleased resources can be released and the memory can be freed. If you have any catch

clauses associated with the try block, you must put the finally clause after all the catch clauses.

We can have multiple catch blocks associated with a single try block, to catch different types of

exceptions.

Structure of try-catch-finally block is as follows :

try

{/ Block of code with multiple exit points }

catch (Exception e)

{ System.out.println (" Good Morning !"); }

catch ( Exception e)

{ System.out.println (" Hello !");}

finally

Page 35: OOPM Lab Manual 2014 Updated

{ // Block of code that is always executed when the try block is exited,

// no matter how the try block is exited.

System.out.println (" Welcome ");

}

Algorithm :

1. Start

2. Define class MultiExceptionDemo

3. Declare array a of size 3.4. Declare variable b=55. Write try block {

int b=arr[4]/(a-arr[1]);

}

6. Write three catch blocks a. To handle Divide by zero errorb. To display Array index Errorc. To display Wrong data type

7. Stop.

Conclusion : We have learned one of the java feature called exception handling.

Page 36: OOPM Lab Manual 2014 Updated

Experiment No. 13

Aim : WAP to print 1A2B3C4D5E6F7G8H9I10J.

Theory :

Processes and Threads

In concurrent programming, there are two basic units of execution: processes and

threads. In the Java programming language, concurrent programming is mostly concerned with

threads.

Processes : A process has a self-contained execution environment. A process generally has a

complete, private set of basic run-time resources; in particular, each process has its own memory

space.

Page 37: OOPM Lab Manual 2014 Updated

Threads : Threads are sometimes called lightweight processes. Both processes and threads

provide an execution environment, but creating a new thread requires fewer resources than

creating a new process. Threads exist within a process — every process has at least one thread.

Threads share the process's resources, including memory and open files. Multithreaded

execution is an essential feature of the Java platform. Every application has at least one thread —

or several, if you count "system" threads that do things like memory management and signal

handling. But from the application programmer's point of view, you start with just one thread,

called the main thread.

Different states of a thread are :

Page 38: OOPM Lab Manual 2014 Updated

New state – After the creations of Thread instance the thread is in this state but before the start()

method invocation. At this point, the thread is considered not alive.

     

Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first

enters runnable state after the invoking of start() method but a thread can return to this state after

either running, waiting, sleeping or coming back from blocked state also. On this state a thread is

waiting for a turn on the processor. 

     

Running state – A thread is in running state that means the thread is currently executing. There

are several ways to enter in Runnable state but there is only one way to enter in Running state:

the scheduler select a thread from runnable pool.

     

Dead state – A thread can be considered dead when its run() method completes. If any thread

comes on this state that means it cannot ever run again.

Blocked - A thread can enter in this state because of waiting the resources that are hold by

another thread.

As we have seen different states that may be occur with the single thread. A running thread can

enter to any non-runnable state, depending on the circumstances. A thread cannot enter directly

to the running state from non-runnable state, firstly it goes to runnable state. Now lets understand

the some non-runnable states which may be occur handling the multithreads.

Sleeping – On this state, the thread is still alive but it is not runnable, it might be return to

runnable state later, if a particular event occurs. On this state a thread sleeps for a specified

amount of time. You can use the method sleep( ) to stop the running state of a thread.

          static void sleep(long millisecond) throws InterruptedException

 Method  Return Type  Description

Page 39: OOPM Lab Manual 2014 Updated

 currentThread( )  Thread Returns an object reference to the thread in which it is invoked.

 getName( )  String  Retrieve the name of the thread object or instance.

 start( )  void  Start the thread by calling its run method.

 run( )  void This method is the entry point to execute thread, like the main method for applications.

 sleep( )  void Suspends a thread for a specified amount of time (in milliseconds).

  isAlive( )  boolean This method is used to determine the thread is running or not.

 activeCount( )  Int This method returns the number of active threads in a particular thread group and all its subgroups.

 interrupt( )  void  The method interrupt the threads on which it is invoked.

 yield( )  void By invoking this method the current thread pause its execution temporarily and allow other threads to execute.

 join( )  void

 This method and join(long millisec) Throws InterruptedException.  These two methods are invoked on a thread. These are not returned until either the thread has completed or it is timed out respectively.

Waiting for Notification – A thread waits for notification from another thread. The thread sends

back to runnable state after sending notification from another thread.

       

     final void wait(long timeout) throws InterruptedException

     final void wait(long timeout, int nanos) throws InterruptedException

     final void wait() throws InterruptedException

     

Page 40: OOPM Lab Manual 2014 Updated

Some Important Methods defined in java.lang.Thread are shown in the table:

Threads can be created in Java in the following ways :

Extending the java.lang.Thread class

Implementing the java.lang.Runnable Interface

1. Extending the java.lang.Thread class

This is a simplest form of creating threads in a program. Consider the following code

snippet.

public class ThreadExample extends Thread

{

public void run()

{

System.out.println(“This is an example on extending thread class”);

}

-----

-----

}

In this code snippet, the ThreadExample class is created by extending the Thread class. The

run( ) method of the Thread class is overridden by the ThreadExample class to provide the code

to be executed by a thread.

In Java we cannot extend a class from more than one class. Therefore while creating a thread

by extending the Thread class we cannot simultaneously extend any other class.

2. Extending the java.lang.Runnable Interface

Page 41: OOPM Lab Manual 2014 Updated

Threads can also be created by implementing the Runnable interface of the java.lang

package. This package allows to define a class that can implement the Runnable interface and

extend any other class. Consider the following code snippet.

public class ThreadExample implements Runnable

{

public void run()

{

System.out.println(“This is an example on runnable interface”);

}

public static void main(String[] args)

{

ThreadExample thrd = new ThreadExample( );

Thread T = new Theard(thrd);

}

}

In above code snippet, the ThreadExample class is declared by implementing Runnable

interface and overriding the run( ) method in which it defines the code to be executed by a

thread.

Algorithm :

1. Start

2. Define class A which inherits Thread class

2.1 Create run( ) method to print 1 to 10 numbers

Page 42: OOPM Lab Manual 2014 Updated

For( int i=1;i<=10;i++)

Print i

3. Define class B which inherits Thread class

3.1 Create run() method to print character using

For( char i=65;i<=74;i++)

Print i

4. Define class multithread

5. Define main method

6. Create objects of A & B

7. Invoke a.start( ) then b.start( )

8. Invoke a.join( ) & b.join( )

9. Stop

Conclusion: In this experiment we have studied different methods to create the thread and one

more example on multithreading.

Page 43: OOPM Lab Manual 2014 Updated

Experiment No.14

Aim: Write a program for implementation of Applet to print different shapes and string..

Theory: Java programs are classified into two groups: Java application and Applets. Programs

with classes that contain main method and run as standalone applications are called as Java

applications. While code written to execute under the control of a browser is called an Applet.

Applets can be used to provide dynamic user- interfaces and a variety of graphical effects for

web pages.

Difference between the Applets and applications are as follows:

Page 44: OOPM Lab Manual 2014 Updated

Applets runs in a web browser, embedded within an html page while Applications runs

standalone.

Applets runs inside the browser, it implicitly uses the inbuilt facilities of event handling

while in applications you have to write the code for event handling , user interface etc

explicitly.

Creation of Applets:

For writing java applet, you must import java.applet.Applet and java.awt.* as all applets are

subclasses of Applet class which provides the standard interface between the applet and the

browser environment and AWT(Abstract Window Toolkit) package is a library of classes that

give applets and stand-alone applications graphical capability.

Following steps are used to create the applet:

Step 1: Write one simple application as follows,

import java.applet.Applet;

import java.awt.*;

public class HelloWorldApplet extends Applet

{

Public void paint (Graphics g)

{

g.drawString (“Hello World!” 10, 10);

}

}

In above example, we have import the two packages applet and awt and extended the class

Applet. Here paint () method of AWT Component class is overridden and this takes graphics

Page 45: OOPM Lab Manual 2014 Updated

object as a parameter. It is used to print the required string using the drawstring () method with x

and y co-ordinates for positioning the string on applet.

Step 2: Save this class as HelloWorldApplet.java and compile it using javac. This will create .class file.

Step 3: Create an HTML file and write following code,

<html>

<head>Java Applet</head>

<body>

<applet code=”HelloWorldApplet.class” width=400 height=100>

</applet>

</body>

</html>

Step 4: Save this file as HelloWorldApplet.html in the same directory as that of your java file.

The applet tag in HelloWorldApplet.html loads the applet HelloWorldApplet.class with width 400 and height as 100.

Step 5: Execute the applet using appletviewer HelloWorldApplet.html.

When an applet is loaded, following things happens-

An instance of the applet’s controlling class is created.

The applet initializes itself.

The applet starts running.

An applet can react to major events in the following ways:

Page 46: OOPM Lab Manual 2014 Updated

1. It can initialize itself.

2. It can start running.

3. It can stop running.

4. It can perform a final cleanup, in preparation for being unloaded.

Algorithm :

(Note: Algorithm depends on the methods which you are going to implement in this experiment.)

Conclusion : With this experiment we have learned to create graphics in Java with the Applet

class. Difference between Applet program and normal application program and how to create

any applet program.

Experiment No. 15

Aim: Design and implement a system for your case study.

1. Define problem statement.

2. Find out classes and objects and their properties.

3. Draw class diagram and object diagram.

4. Add methods to classes and implement.

Page 47: OOPM Lab Manual 2014 Updated

5. Refine above objects by adding constructor and local variables.

6. Show communication between the objects by calling instance of one object from

another class using interaction diagram.

7. Find relationship like inheritance, association, aggregation, composition.

8. Design module and process diagram.

Conclusion: Thus we have designed and implemented real world system (case study) using

Object Oriented Programming Methodology.