BE COMPS RAIT, NERUL



RAMRAO ADIK INSTITUTE OF TECHNOLOGY,

NERUL

LAB MANUAL

Object Oriented Programming and Methodology

(Computer Engineering)

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 |

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.

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.

1. temp size()). |

|2 |boolean 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. |

|4 |boolean 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. |

|5 |void clear()  |

| |Removes all of the elements from this list. |

|6 |Object 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)). |

|8 |void 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()). |

|10 |int 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. |

|11 |int 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()). |

|13 |protected 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()). |

|15 |int size()  |

| |Returns the number of elements in this list. |

|16 |Object[] toArray()  |

| |Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the |

| |specified array is null. |

|17 |Object[] 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()  |

| |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.

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

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.

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

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

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.

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.

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

{ // 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=5

5. Write try block

{

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

}

6. Write three catch blocks

a. To handle Divide by zero error

b. To display Array index Error

c. To display Wrong data type

7. Stop.

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

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.

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 :

[pic]

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 |

| 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

     

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

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

For( int i=1;i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download