0% found this document useful (0 votes)
28 views36 pages

OOPS Lab Manual

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views36 pages

OOPS Lab Manual

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

SRI SHAKTHI

INSTITUTE OF ENGINEERING AND TECHNOLOGY


COIMBATORE – 62

Autonomous Institution, Accredited by NAAC with “A” Grade

21CS322 – OBJECT ORIENTED PROGRAMMING LABORATORY

DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
SRI SHAKTHI INSTITUTE OF ENGINEERING AND
TECHNOLOGY
DEPARTMENT OF

COMPUTER SCIENCE AND ENGINEERING


21CS322 – OBJECT ORIENTED PROGRAMMING LABORATORY

LABORATORY RECORD

NAME: ROLLNO:

CLASS: BRANCH:

ACADEMIC YEAR: BATCH: SEMESTER:

Certified and bonafide record of work done by ………...………….………………

Place:
Date:

Staff In-Charge Head of the Department

University Register Number: ………………………………………………...


Submitted for the University Practical Examination held on ……...…………

INTERNAL EXAMINER EXTERNAL EXAMINER


INDEX

EXP.
DATE NAME OF THE EXPERIMENT MARKS
NO.

1 Simple programs without Classes, Objects and


Methods

2 Program based on the concepts of Classes and


Objects, Constructor, Parameterized Constructor

3 Method Overloading and Constructor Overloading

4 Single Level and Multi-level Inheritance

5 Abstract Classes and Interface

6 Arrays

7 Exception Handling

8 Packages

9 Multi-threading

10 Applet

11 I/O and File Handling

AVERAGE:

SIGNATURE OF THE FACULTY


20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO : 1 SIMPLE PROGRAMS WITHOUT CLASSES AND OBJECTS,


DATE : METHODS

AIM:

To write a simple java program without classes and objects, methods.

ALGORITHM:

1. You can print any text you want with the command, as long as the command
System.out.println("arbitrary text"); i.e., System dot out dot println open parenthesis (“the text"
close parenthesis) and semicolon; remains unchanged.
2. Define base and height and Apply in the formula finally Print the Area.
3. The isPrime (int n) method is used to check whether the parameter passed to it is a prime
number or not. If the parameter passed is prime, then it returns True otherwise it returns False.
4. If the number is less than 1, if (input Number<= 1) it returns false.
5. If the number is not less than or equal to 1, performs division operation.

PROGRAM:

a) Welcome to World of Java:

public static void main (String [] args)


{
System.out.println("Welcome to Java Program with println!!");
System.out.print("Welcome to Java Program with print!!\n");
System.out.printf("Welcome to Java Program with printf!!\n");
}

b) Print the area of triangle:

public static void main (String args [])


{
Scanner scanner = new Scanner (System.in);
System.out.println("Enter the width of the Triangle:");
double base = scanner. nextDouble ();
System.out.println("Enter the height of the Triangle:");

Page | 1
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

double height = scanner. nextDouble ();


double area = (base* height)/2;
System.out.println("Area of Triangle is: " + area);
}
c) Prime or not.:

public static void main (String [] args)


{

int num = 33, i = 2;


boolean flag = false;
while (i <= num / 2) {
if (num % i == 0) {
flag = true;
break;
}
++i;
}
if (! flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}

Page | 2
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

a) Welcome to World of Java:

b) Print the area of triangle:

c) Prime or not.:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL

RESULT:

Thus, the java programs without classes and objects, methods have been executed successfully.

Page | 3
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO : 2 PROGRAM BASED ON THE CONCEPTS OF CLASSES


AND OBJECTS, CONSTRUCTOR, PARAMETERIZED
DATE :
CONSTRUCTOR

AIM:

To write a program based on the concepts of classes and objects, constructor, parameterized
constructor.

ALGORITHM:

1. Create a class Student with data ‘name, city and age’ along with method printData to display
the data. Create the two objects s1, s2 to declare and access the values.
2. Create a class Student2 along with two method getData (), printData () to get the value
through argument and display the data in printData. Create the two objects s1, s2 to declare
and access the values from class STtest.
3. Using parameterized constructor with two parameters id and name. While creating the
objects obj1 and obj2 passed two arguments so that this constructor gets invoked after
creation of obj1 and obj2.

PROGRAM:

a) Default Constructor:

class Main
{
int a;
boolean b;
public static void main (String [] args)
{
Main obj = new Main ();
System.out.println("Default Value:");
System.out.println("a = " + obj. a);
System.out.println("b = " + obj. b);
}
}

Page | 4
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

b) Parametrized Constructor:

class Main
{
String languages;
Main (String lang)
{
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main (String [] args)
{
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}

OUTPUT:

a) Default Constructor:

b) Parametrized Constructor:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL
RESULT:

Thus, the program for constructor, parameterized constructor has been executed successfully.

Page | 5
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO: 3 METHOD OVERLOADING AND CONSTRUCTOR


DATE : OVERLOADING

AIM:

To write a program in JAVA to demonstrate the method and constructor overloading.

ALGORITHM:

1. In Java, we can overload constructors like methods. The constructor overloading can be
defined as the concept of having more than one constructor with different parameters so that
every constructor can perform a different task.
2. If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
3. Create a class Bird also declares the different parameterized constructor to display the name
of Birds.

PROGRAM:

a) Method Overloading:

class HelperService
{
private String formatNumber (int value)
{
return String.format("%d", value);
}
private String formatNumber (double value)
{
return String.format("%.3f", value);
}
private String formatNumber (String value)
{
return String.format("%.2f", Double.parseDouble(value));
}

Page | 6
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

public static void main (String [] args)


{
HelperService hs = new HelperService ();
System.out.println(hs. formatNumber (500));
System.out.println(hs. formatNumber (89.9934));
System.out.println(hs. formatNumber ("550"));
}
}

b) Constructor Overloading:

class Main
{
String language;
Main ()
{
this. language = "Java";
}
Main (String language)
{
this. language = language;
}
public void getName ()
{
System.out.println("Programming Language: " + this. language);
}
public static void main (String [] args)
{
Main obj1 = new Main ();
Main obj2 = new Main("Python");
obj1.getName();
obj2.getName();
}
}

Page | 7
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

a) Method Overloading:

b) Constructor Overloading:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL

RESULT:

Thus, the program in java to demonstrate the method and constructor overloading has
been executed successfully.

Page | 8
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO : 4
SINGLE LEVEL AND MULTI-LEVEL INHERITANCE
DATE :

AIM:

To write a program to single level and multi-level inheritance.

ALGORITHM:

1. The most important use of inheritance in Java is code reusability. The code that is present
in the parent class can be directly used by the child class. Method overriding is also known
as runtime polymorphism.

2. We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.

3. The constructors of the subclass can initialize only the instance variables of the subclass.
Thus, when a subclass object is instantiated the subclass object must also automatically
execute one of the constructors of the superclass.

PROGRAM:

a) Single Inheritance:

class Animal
{
void eat () {System.out.println("eating...");}
}
class Dog extends Animal
{
void bark () {System.out.println("barking...");}
}
class TestInheritance
{
public static void main (String args [])
{
Dog d=new Dog ();

Page | 9
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

d.bark ();
d.eat ();
}
}

b) Multi-level Inheritance:

class Animal
{
void eat () {System.out.println("eating...");}
}
class Dog extends Animal
{
void bark () {System.out.println("barking...");}
}
class BabyDog extends Dog
{
void weep () {System.out.println("weeping...");}
}
class TestInheritance2
{
public static void main (String args [])
{
BabyDog d=new BabyDog ();
d.weep ();
d.bark ();
d.eat ();
}
}

Page | 10
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

a) Single Inheritance:

b) Multi-level Inheritance:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL

RESULT:

Thus, the program to single level and multi-level inheritance has been executed successfully.

Page | 11
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO : 5
ABSTRAT CLASSES AND INTERFACES
DATE :

AIM:

To write a program in java to generate an abstract class and interfaces.

ALGORITHM:
1. Generate an abstract class A also class B inherits the class A. generate the object forclass B
and display the text “call me from B”.
2. Declare two interface sum and add inherits these interfaces through class a1and display their
content.
3. An abstract class Vehicle inherits this class from two classes car and truck using the method
engine in both display “car has good engine” and “truck has bad engine”.

PROGRAM:

a) Abstract Class:
abstract class MotorBike
{
abstract void brake ();
}
class SportsBike extends MotorBike
{
public void brake ()
{
System.out.println("SportsBike Brake");
}
}
class MountainBike extends MotorBike
{
public void brake () {System.out.println("MountainBike Brake");}
}

Page | 12
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

class Main
{
public static void main (String [] args)
{
MountainBike m1 = new MountainBike ();
m1. brake ();
SportsBike s1 = new SportsBike ();
s1. brake ();
}
}

b) Interfaces:
interface Language
{
void getName (String name);
}
class ProgrammingLanguage implements Language
{
public void getName (String name)
{
System.out.println("Programming Language: " + name);
}
}
class Main
{
public static void main (String [] args)
{
ProgrammingLanguage language = new ProgrammingLanguage ();
language. GetName("Java");
}
}

Page | 13
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

a) Abstract Class:

b) Interfaces:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL

RESULT:

Thus, the program in java to generate an abstract class and interfaces has been successfully
executed.

Page | 14
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO : 6
ARRAYS
DATE :

AIM:

To write a Java Program to find the arrays.

ALGORITHM:

1. Given an array, the task is to find average of that array. Average is the sum of array elements
divided by the number of elements.
2. Declare and initialize 2 two-dimensional arrays a and b.
3. Calculate the number of rows and columns present in the array a (as dimensions of both the
arrays are same) and store it in variables rows and cols respectively.
4. Declare another array sum with the similar dimensions.

PROGRAM:

a) Average of numbers in an array:

public class Average


{
public static void main (String [] args)
{
double [] numArray = {45.3, 67.5, -45.6, 20.34, 33.0, 45.6};
double sum = 0.0;
for (double num: numArray) {sum += num;}
double average = sum / numArray. Length;
System.out.format("The average is: %.2f", average);
}
}

b) Addition of two matrices:

public class AddMatrices


{
public static void main (String [] args)

Page | 15
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

{
int rows = 2, columns = 3;
int [][] firstMatrix = { {2, 3, 4}, {5, 2, 3} };
int [][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} };
int [][] sum = new int[rows][columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}
System.out.println("Sum of two matrices is: ");
for (int [] row: sum)
{
for (int column: row)
{
System.out.print(column + " ");
}
System.out.println();
}
}
}

Page | 16
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

a) Average of numbers in an array:

b) Addition of two matrices:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL

RESULT:

Thus, the Java Program to for arrays has been executed successfully.

Page | 17
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO : 7
EXCEPTION HANDLING
DATE :

AIM:

To write a Java Program in exception handling.

ALGORITHM:

1. Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so
that the normal flow of the application can be maintained.
2. Enter the number through command line argument if first and second number is not entered it
will generate the exception.
3. Divide the first number with second number and generate the arithmetic exception.
4. Arithmetic exception was handled in the catch block.

PROGRAM:

class Main
{
public static void main (String args [])
{
try
{
try
{
System.out.println("Try Block1");
int num =15/0;
System.out.println(num);
}
catch (ArithmeticException e1)
{
System.out.println("Block1 Exception: e1");
}
try

Page | 18
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

{
System.out.println("Try Block2");
int num =100/0;
System.out.println(num);
}
catch (ArrayIndexOutOfBoundsException e2)
{
System.out.println("Block2 Exception: e2");
}
System.out.println("General statement after Block1 and Block2");
}
catch (ArithmeticException e3)
{
System.out.println("Main Block Arithmetic Exception");
}
catch (ArrayIndexOutOfBoundsException e4)
{
System.out.println("Main Block ArrayIndexOutOfBoundsException");
}
catch (Exception e5)
{
System.out.println("Main Block General Exception");
}
System.out.println("Code after Nested Try Block");
}
}

Page | 19
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL

RESULT:

Thus, the Java Program in exception handling has been executed successfully.

Page | 20
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO : 8
PACKAGES
DATE :

AIM:

To write a Java Program in Package.

ALGORITHM:

1. A java package is a group of similar types of classes, interfaces and sub-packages.


2. Package in java can be categorized in two form, built-in package and user-defined package.
3. Preventing naming conflicts. For example, there can be two classes with name Employee in
two packages, college.staff.cse. Employee and college.staff.ee. Employee
4. Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.

PROGRAM:

/* File name: Animal.java */

package animals;
interface Animal
{
public void eat ();
public void travel ();
}

package animals;
/* File name: MammalInt.java */

public class MammalInt implements Animal


{
public void eat ()

Page | 21
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

{
System.out.println("Mammal eats");
}
public void travel ()
{
System.out.println("Mammal travels");
}
public int noOfLegs ()
{
return 0;
}
public static void main (String args [])
{
MammalInt m = new MammalInt ();
m.eat ();
m.travel ();
}
}

Page | 22
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

OUTPUT:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL

RESULT:
Thus, the Java Program in Packages has been executed successfully.

Page | 23
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO : 9
MULTI-THREADING
DATE :

AIM:

To write a Java Program in Multi-threading.

ALGORITHM:

1. Start
2. Create a class even which implements first thread that computes the square of the number.
3. run () method implements the code to be executed when thread gets executed.
4. Create a class odd which implements second thread that computes the cube of the number.
5. Create a third thread that generates random number. If the random number is even, it displays
the square of the number. If the random number generated is odd, it displays the cube of the
given number.
6. The Multithreading is performed and the task switched between multiple threads.
7. The sleep () method makes the thread to suspend for the specified time.
8. Stop.

PROGRAM:

a) Thread creation by extending Thread class:

class Count extends Thread


{
Count ()
{
super ("my extending thread");
System.out.println("my thread created" + this);
start ();
}
public void run ()
{
try
{

Page | 24
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

for (int i=0; i<10; i++)


{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("My thread run is over”);
}
}
class ExtendingExample
{
public static void main (String args [])
{
Count cnt = new Count ();
try
{
while (cnt. isAlive ())
{
System.out.println("Main thread will be alive till the child
thread is live");
Thread.sleep(1500);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread's run is over”);
}
}

Page | 25
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

b) Thread creation by implementing Runnable Interface:

class Count implements Runnable


{
Thread mythread;
Count ()
{
mythread = new Thread (this, "my runnable thread");
System.out.println("my thread created" + mythread);
mythread. start ();
}
public void run ()
{
try
{
for (int i=0; i<10; i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("mythread run is over”);
}
}
class RunnableExample
{
public static void main (String args [])
{
Count cnt = new Count ();
try

Page | 26
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

{
while (cnt. mythread. isAlive ())
{
System.out.println("Main thread will be alive till the child
thread is live");
Thread.sleep(1500);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread run is over”);
}
}

OUTPUT:

a) Thread creation by extending Thread class:

Page | 27
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

b) Thread creation by implementing Runnable Interface:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL

RESULT:

Thus, the Java Program in Multi-threading has been executed successfully.

Page | 28
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO : 10
APPLET
DATE :

AIM:

To write a Java Program in applet.

ALGORITHM:

1. Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
2. An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
3. An applet is a Java class that extends the java. applet. Applet class.
4. The applet can create a graphical user interface after a user gets an applet. It has restricted
access to resources so that complicated computations can be carried out without adding the
danger of viruses or infringing data integrity.

PROGRAM:

GraphicsDemo1.java

import java. applet. Applet;


import java.awt. *;
public class GraphicsDemo1 extends Applet
{
public void paint (Graphics g)
{
g. setColor (Color. Black);
g. drawstring ("Welcome to studytonight",50, 50);
g.setColor(Color.blue);
g. fillOval (170,200,30,30);
g. drawArc (90,150,30,30,30,270);
g. fillArc (270,150,30,30,0,180);
g. drawLine (21,31,20,300);

Page | 29
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

g. drawRect (70,100,30,30);
g. fillRect (170,100,30,30);
g. drawOval (70,200,30,30);
}
}
GraphicsDemo1.html

<html>
<body>
<applet code="GraphicsDemo1.class" width="300" height="300">
</applet>
</body>
</html>

OUTPUT:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL
RESULT:

Thus, the java program in applet has been successfully executed.

Page | 30
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

EX. NO : 11
I/O AND FILE HANDLING
DATE :

AIM:

To write a java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length of the
file in bytes.

ALGORITHM:

1. Start
2. Create a class filedemo. Get the file name from the user.
3. Use the file functions and display the information about the file.
4. getName () displays the name of the file.
5. getPath () displays the path name of the file.
6. getParent () -This method returns the pathname string of this abstract pathname’s parent
7. null if this pathname does not name a parent directory.
8. exists () – Checks whether the file exists or not.
9. canRead ()-This method is basically a check if the file can be read.
10. canWrite ()-verifies whether the application can write to the file.
11. isDirectory () – displays whether it is a directory or not.
12. isFile () – displays whether it is a file or not.
13. lastmodified () – displays the last modified information.
14. length ()- displays the size of the file.
15. delete () – deletes the file
16. Invoke the predefined functions to display the information about the file.
17. Stop.

PROGRAM:

filedemo.java

import java.io. *;
import java.util.*;

Page | 31
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

class filedemo
{
public static void main (String args [])
{
String filename;
Scanner s=new Scanner (System.in);
System.out.println("Enter the file name ");
filename=s. nextLine ();
File f1=new File(filename);
System.out.println("******************");
System.out.println("FILE INFORMATION");
System.out.println("******************");
System.out.println("NAME OF THE FILE "+f1.getName());
System.out.println("PATH OF THE FILE "+f1.getPath());
System.out.println("PARENT"+f1.getParent());
if (f1. exists ())
System.out.println("THE FILE EXISTS ");
else
System.out.println("THE FILE DOES NOT EXISTS ");
if (f1. canRead ())
System.out.println("THE FILE CAN BE READ ");
else
System.out.println("THE FILE CANNOT BE READ “);
if (f1. canWrite ())
System.out.println("WRITE OPERATION IS PERMITTED");
else
System.out.println("WRITE OPERATION IS NOT PERMITTED");
if (f1. isDirectory ())
System.out.println("IT IS A DIRECTORY ");
else
System.out.println("NOT A DIRECTORY");
if (f1. isFile ())
System.out.println("IT IS A FILE ");

Page | 32
20CS315 – OBJECT ORIENTED PROGRAMMING LAB

else
System.out.println("NOT A FILE");
System.out.println("File last modified "+ f1. lastModified ());
System.out.println("LENGTH OF THE FILE “+f1.length());
System.out.println("FILE DELETED "+f1.delete());
}
}

OUTPUT:

CLASS PERFORMANCE

RECORD

VIVA

TOTAL

RESULT:
Thus, the java program in I/O and file handling has been executed successfully.

Page | 33

You might also like