0% found this document useful (0 votes)
27 views

Java Lab Manual

java

Uploaded by

vlogz.illa25297
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Java Lab Manual

java

Uploaded by

vlogz.illa25297
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Object Oriented Programming with JAVA- Manual

K S INSTITUTE OF TECHNOLOGY
#14 Raghuvanahalli Kanakapura road Bangalore – 560109

Department Of Computer Science and Design

LAB MANUAL

OBJECT ORIENTED PROGRAMMING WITH JAVA


BCS306A

Prepared By

Dr. Kusuma T
Associate Professor
Dept of CSD
KSIT, Bangalore
Object Oriented Programming with JAVA- Manual

K S INSTITUTE OF TECHNOLOGY

VISION
“To impart quality technical education with ethical values, employable
skills and research to achieve excellence”

MISSION

 To attract and retain highly qualified, experienced & committed faculty.

 To create relevant infrastructure

 Network with industry & premier institutions to encourage emergence

of new ideas by providing research & development facilities to strive

for academic excellence

 To inculcate the professional & ethical values among young


students with employable skills & knowledge acquired to
transform the society
Object Oriented Programming with JAVA- Manual

DEPARTMENT OF COMPUTER SCIENCE


AND DESIGN

VISION

To prepare exceptionally skilled and outstanding professionals in


Computer Science & Design with research skills and ethics for
addressing societal needs.

MISSION

Instill a commitment to enhancing design, and development skills by


Encouraging

To create awareness of research and ethics among students to excel in


various facets of the design profession.

To groom the students with the needed practical skills to cater to the
needs of society through projects.
Object Oriented Programming with JAVA- Manual

PEOs

1. Exhibit design skills and become an excellent employee in the

interdisciplinary field.
2. Exhibit creative thinking and continue learning through higher studies and
research.
3. Proficient in solving real-life problems related to innovation through
teamwork and ethics.

PSOs

1. Ability to Utilize Concepts and Practices of computer science & design to


develop solutions.
2. Ability to demonstrate design and development skills to solve problems in
the broad area of programming concepts and real-world challenges.
Object Oriented Programming with JAVA- Manual

PROGRAM OUTCOMES

PO1. Engineering knowledge: Apply the knowledge of mathematics,


science, engineering fundamentals, and an engineering specialization to the
solution of complex engineering problems.

PO2. Problem analysis: Identify, formulate, review research literature, and


analyze complex engineering problems reaching substantiated conclusions
using first principles of mathematics, natural sciences, and engineering
sciences.

PO3. Design/development of solutions: Design solutions for complex


engineering problems and design system components or processes that meet
the specified needs with appropriate consideration for the public health and
safety, and the cultural, societal, and environmental considerations.

PO4. Conduct investigations of complex problems: Use research-


based knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to provide
valid conclusions.

PO5. Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations.

PO6. The engineer and society: Apply reasoning informed by the


contextual knowledge to assess societal, health, safety, legal and cultural issues
and the consequent responsibilities relevant to the professional engineering
Object Oriented Programming with JAVA- Manual

practice.

PO7. Environment and sustainability: Understand the impact of the


professional engineering solutions in societal and environmental contexts, and
demonstrate the knowledge of, and need for sustainable development.

PO8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.

PO9. Individual and team work: Function effectively as an individual,


and as a member or leader in diverse teams, and in multidisciplinary settings.

PO10. Communication: Communicate effectively on complex engineering


activities with the engineering community and with society at large, such as,
being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear
instructions.

PO11. Project management and finance: Demonstrate knowledge and


understanding of the engineering and management principles and apply these
to one’s own work, as a member and leader in a team, to manage projects and
in multidisciplinary environments.

PO12. Life-long learning: Recognize the need for, and have the
preparation and ability to engage in independent and life-long learning in the
broadest context of technological change.
Object Oriented Programming with JAVA- Manual

List of Experiments
Object Oriented Programming with JAVA- Manual
Object Oriented Programming with JAVA- Manual

COURSE OUTCOMES

Applying
Demonstrate proficiency in writing simple programs involving branching
CO1
and looping structures (K3)
Applying
Design a class involving data members and methods for the given
CO2
scenario. (K3)
Applying
Apply the concepts of inheritance and interfaces in solving real world
CO3
problems. (K3)
Applying
Use the concept of packages and exception handling in solving complex
CO4
problem. (K3)
Apply concepts of multithreading, autoboxing and enumerations in Applying
CO5
program development (K3)
Object Oriented Programming with JAVA- Manual

PROGRAMMING EXPERIMENTS

1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be
read from command line arguments).

/*Java Program to add two matrix*/


import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int p, q, m, n; //Declare matrix size
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows in the first matrix:");
p = sc.nextInt(); //Initialize first matrix size
System.out.print("Enter the number of columns in the first matrix:");
q = sc.nextInt(); //Initialize first matrix size
System.out.print("Enter the number of rows in the second matrix:");
m = sc.nextInt(); //Initialize second matrix size
System.out.print("Enter the number of columns in the second matrix:");
n = sc.nextInt(); //Initialize second matrix size
if (p == m && q == n)
{
int a[][] = new int[p][q]; //Declare first matrix
int b[][] = new int[m][n]; //Declare second matrix
int c[][] = new int[m][n]; //Declare third matrix
//Initialize the first matrix
System.out.println("Enter all the elements of first matrix:");
for (int i = 0; i < p; i++)
{
for (int j = 0; j < q; j++)
{
a[i][j] = sc.nextInt();
}
}
System.out.println("");
//Initialize the second matrix
System.out.println("Enter all the elements of second matrix:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
Object Oriented Programming with JAVA- Manual

b[i][j] = sc.nextInt();
}
}
System.out.println("");
//Print the first matrix
System.out.println("First Matrix:");
for (int i = 0; i < p; i++)
{
for (int j = 0; j < q; j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println("");
}
//Print the second matrix
System.out.println("Second Matrix:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(b[i][j]+" ");
}
System.out.println("");
}
//Loop to add matrix elements
for (int i = 0; i < p; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < q; k++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
//Print the resultant matrix
System.out.println("Matrix after addition:");
for (int i = 0; i < p; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println("");
Object Oriented Programming with JAVA- Manual

}
}
else
{
System.out.println("Addition not possible");
System.out.println("Try Again");
}
}
}

OUTPUT
Enter number of rows in first matrix:2
Enter number of columns in first matrix :2
Enter number of rows in second matrix:2
Enter number of columns in second matrix:2
Enter all the elements of first matrix:

23
12
Enter all the elements of second matrix:

33
33
First Matrix:
23
12
Second Matrix:
33
33
Matrix after addition:
56
45

2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.

// Java code for stack implementation

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

class Test
{
Object Oriented Programming with JAVA- Manual

// Pushing element on the top of the stack


static void stack_push(Stack<Integer> stack)
{
for(int i = 0; i < 10; i++)
{
stack.push(i);
}
}

// Popping element from the top of the stack


static void stack_pop(Stack<Integer> stack)
{
System.out.println("Pop Operation:");

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


{
Integer y = (Integer) stack.pop();
System.out.println(y);
}
}

// Displaying element on the top of the stack


static void stack_peek(Stack<Integer> stack)
{
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top: " + element);
}

// Searching element in the stack


static void stack_search(Stack<Integer> stack, int element)
{
Integer pos = (Integer) stack.search(element);

if(pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position: " + pos);
}
Object Oriented Programming with JAVA- Manual

public static void main (String[] args)


{
Stack<Integer> stack = new Stack<Integer>();

stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
}
OUTPUT
Pop Operation:
10,9,8,7,6,5,4,3,2,1,0
Element on stack top: 10
Element is found at position: 1
Element not found

3.A class called Employee, which models an employee with an ID, name and salary, is designed
as shown in the following class diagram. The method raiseSalary (percent) increases the salary
by the given percentage. Develop the Employee class and suitable main method for
demonstration.

public class Employee {


private int id;
private String name;
private double salary;

public Employee(int id, String name, double salary) {


this.id = id;
this.name = name;
this.salary = salary;
}

public void raiseSalary(double percent) {


if (percent > 0) {
salary += salary * (percent / 100);
System.out.println("Salary raised by " + percent + "%.");
Object Oriented Programming with JAVA- Manual

} else {
System.out.println("Invalid percentage. Salary remains unchanged.");
}
}

public void displayDetails() {


System.out.println("Employee ID: " + id);
System.out.println("Employee Name: " + name);
System.out.println("Employee Salary: $" + salary);
}

public static void main(String[] args) {


Employee employee = new Employee(1, "John Doe", 50000.0);

System.out.println("Initial Employee Details:");


employee.displayDetails();

employee.raiseSalary(20); // Raise salary by 10%


System.out.println("Updated Employee Details:");
employee.displayDetails();
}
}
OUTPUT
Initial Employee Details:
Employee ID: 1
Employee Name: John Doe
Employee Salary: $50000.0
Salary raised by 20.0%.
Updated Employee Details:
Employee ID: 1
Employee Name: John Doe
Employee Salary: $60000.0
Object Oriented Programming with JAVA- Manual

4.A class called MyPoint, which models a 2D point with x and y coordinates, is designed as
follows: ●Two instance variables x (int) and y (int). ●A default (or "no-arg") constructor that
construct a point at the default location of (0, 0). ●A overloaded constructor that constructs a
point with the given x and y coordinates. ●A method setXY() to set both x and y. ●A method
getXY() which returns the x and y in a 2-element int array.●A toString() method that returns a
string description of the instance in the format "(x, y)". ●A method called distance(int x, int y)
that returns the distance from this point to another point at the given (x, y) coordinates ●An
overloaded distance(MyPoint another) that returns the distance from this point to the given
MyPoint instance (called another) ●Another overloaded distance() method that returns the
distance from this point to the origin (0,0) Develop the code for the class MyPoint. Also develop
a JAVA program (called TestMyPoint) to test all the methods defined in the class.
public class MyPoint {
private int x;
private int y;

public MyPoint() {
this(0, 0); // Default constructor sets the point at (0, 0)
}

public MyPoint(int x, int y) {


this.x = x;
this.y = y;
}

public void setXY(int x, int y) {


this.x = x;
this.y = y;
}

public int[] getXY() {


int[] coordinates = { x, y };
return coordinates;
}

@Override
public String toString() {
return "(" + x + ", " + y + ")";
}

public double distance(int x, int y) {


int xDistance = this.x - x;
int yDistance = this.y - y;
return Math.sqrt(xDistance * xDistance + yDistance * yDistance);
}
Object Oriented Programming with JAVA- Manual

public double distance(MyPoint another) {


return distance(another.x, another.y);
}

public double distance() {


return distance(0, 0);
}
}

Output

Point1 coordinates after setXY: 1, 2


Point2 coordinates: (3, 4)
Distance from Point1 to Point2: 2.8284271247461903
Distance from Point2 to Origin: 5.0

5.Develop a JAVA program to create a class named shape. Create three sub classes namely:
circle, triangle and square, each class has two member functions named draw () and erase ().
Demonstrate polymorphism concepts by developing suitable methods, defining member data
and main program.
class Shape {
public void draw() {
System.out.println("Drawing a generic shape.");
}

public void erase() {


System.out.println("Erasing a generic shape.");
}
}

class Circle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a circle.");
}

@Override
public void erase() {
System.out.println("Erasing a circle.");
}
}

class Triangle extends Shape {


Object Oriented Programming with JAVA- Manual

@Override
public void draw() {
System.out.println("Drawing a triangle.");
}

@Override
public void erase() {
System.out.println("Erasing a triangle.");
}
}

class Square extends Shape {


@Override
public void draw() {
System.out.println("Drawing a square.");
}

@Override
public void erase() {
System.out.println("Erasing a square.");
}
}

public class PolymorphismDemo {


public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();

for (Shape shape : shapes) {


shape.draw();
shape.erase();
System.out.println();
}
}
}

OUTPUT
$ java ShapeDemo
Drawing a circle with radius 5.0
Erasing a circle with radius 5.0

Drawing a triangle with base 4.0 and height 6.0


Object Oriented Programming with JAVA- Manual

Erasing a triangle with base 4.0 and height 6.0


Drawing a square with side length 3.0
Erasing a square with side length 3.0

6. Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle that extend the
Shape class and implement the respective methods to calculate the area and perimeter of each
shape.
// Shape.java
// Abstract class Shape
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}
// Circle.java
// Subclass Circle
class Circle extends Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
double calculateArea() {
return Math.PI * radius * radius;
}

@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
// Triangle.java
// Subclass Triangle
class Triangle extends Shape {
private double side1;
private double side2;
private double side3;

public Triangle(double side1, double side2, double side3) {


this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
Object Oriented Programming with JAVA- Manual

@Override
double calculateArea() {
double s = (side1 + side2 + side3) / 2; // Semi-perimeter
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
}
// Main.java
// Subclass Main

public class Main {


public static void main(String[] args) {
double r = 4.0;
Circle circle = new Circle(r);
double ts1 = 3.0, ts2 = 4.0, ts3 = 5.0;
Triangle triangle = new Triangle(ts1, ts2, ts3);
System.out.println("Radius of the Circle"+r);
System.out.println("Area of the Circle: " + circle.calculateArea());
System.out.println("Perimeter of the Circle: " + circle.calculatePerimeter());
System.out.println("\nSides of the Traiangel are: "+ts1+','+ts2+','+ts3);
System.out.println("Area of the Triangle: " + triangle.calculateArea());
System.out.println("Perimeter of the Triangle: " + triangle.calculatePerimeter());
}
}
OUTPUT

Radius of the Circle: 4.0


Area of the Circle: 50.26548245743669
Perimeter of the Circle: 25.132741228718345

Sides of the Traiangel are: 3.0,4.0,5.0


Area of the Triangle: 6.0
Perimeter of the Triangle: 12.0
Object Oriented Programming with JAVA- Manual

7. Develop a JAVA program to create an interface Resizable with methods resizeWidth(int


width) and resizeHeight(int height) that allow an object to be resized. Create a class Rectangle
that implements the Resizable interface and implements the resize methods

//Resizable.java
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
//Rectangle.java
class Rectangle implements Resizable {
private int width;
private int height;

public Rectangle(int width, int height) {


this.width = width;
this.height = height;
}

public void resizeWidth(int width) {


this.width = width;
}

public void resizeHeight(int height) {


this.height = height;
}

public void printSize() {


System.out.println("Width: " + width + ", Height: " + height);
}
}
//Main.java
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(100, 150);
rectangle.printSize();

rectangle.resizeWidth(150);
rectangle.resizeHeight(200);
rectangle.printSize();
}
}

OUTPUT
Object Oriented Programming with JAVA- Manual

Width: 100, Height: 150


Width: 150, Height: 200

8. Develop a JAVA program to create an outer class with a function display. Create another class
inside the outer class named inner with a function called display and call the two functions in
the main class.

class Outer {
void display() {
System.out.println("Outer class display()");
}

class Inner {
void display() {
System.out.println("Inner class display()");
}
}
}

public class pgm8 {


public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

outer.display(); // Call the display method of the outer class


inner.display(); // Call the display method of the inner class
}
}
OUTPUT
Outer class display()
Inner class display()
Object Oriented Programming with JAVA- Manual

9.Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally
// Custom exception class for DivisionByZero

class DivisionByZeroException extends Exception {


public DivisionByZeroException() {
super("Division by zero is not allowed.");
}
}

public class pgm9 {


public static void main(String[] args) {
try {
int numerator = 10;
int denominator = 0;

if (denominator == 0) {
throw new DivisionByZeroException();
}

int result = numerator / denominator;


System.out.println("Result: " + result);
} catch (DivisionByZeroException ex) {
System.err.println("Error: " + ex.getMessage());
} finally {
System.out.println("Program execution completed.");
}
}
OUTPUT
Error: Division by zero is not allowed.Program execution completed
10 .Develop a JAVA program to create a package named mypack and import & implement it in
a suitable class
create a directory structure that matches the package name. In this case, create a directory named
mypack to store your package-related classes.
1. Inside the mypack directory, create a Java class. For example, let's create a class named
MyClass within the package.
2. In the MyClass class, define some functionality or methods.
3. To use this package in another class, create a new Java class and import the mypack package.
Here's an example of how to create this structure and use it:
Object Oriented Programming with JAVA- Manual

1. Create the mypack directory and the MyClass.java file inside it.
Directory Structure:
- mypack
- MyClass.java

Define a class within the mypack package (MyClass.java):


package mypack;
public class MyClass {
public void displayMessage() {
System.out.println("Hello from MyClass in mypack!");
}
}
Create a Java class outside the mypack package and import and use the mypack package:
import mypack.MyClass;a
public class MainClass {
public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.displayMessage();
}
}
Compile and run the MainClass:
javac MainClass.java
java MainClass
Object Oriented Programming with JAVA- Manual

11.Write a program to illustrate creation of threads using runnable class. (start method start
each of the newly created thread. Inside the run method there is sleep() for suspend the thread
for 500 milliseconds).

public class pgm11 {


public static void main(String[] args) {
// Create multiple threads using the Runnable interface
Thread thread1 = new Thread(new MyRunnable("Thread 1"));
Thread thread2 = new Thread(new MyRunnable("Thread 2"));
Thread thread3 = new Thread(new MyRunnable("Thread 3"));

// Start each thread


thread1.start();
thread2.start();
thread3.start();
}
}

class MyRunnable implements Runnable {


private String name;

public MyRunnable(String name) {


this.name = name;
}

public void run() {


try {
System.out.println(name + " is starting.");
Thread.sleep(500); // Sleep for 500 milliseconds
System.out.println(name + " is done.");
} catch (InterruptedException e) {
System.out.println(name + " was interrupted.");
}
}
}
OUTPUT
Thread 1 is starting.
Thread 2 is starting.
Thread 3 is starting.
Thread 1 is done.
Thread 2 is done.
Thread 3 is done.
Object Oriented Programming with JAVA- Manual

12.Develop a program to create a class MyThread in this class a constructor, call the base class
constructor, using super and start the thread. The run method of the class starts after this. It
can be observed that both main thread and created child thread are executed concurrently.

public class pgm2 extends Thread {


public pgm2() {
super(); // Call the base class (Thread) constructor
}

@Override
public void run() {
System.out.println("Child thread is running.");
}

public static void main(String[] args) {


pgm2 myThread = new pgm2();

// Start the child thread


myThread.start();

System.out.println("Main thread is running concurrently with the child thread.");


}
}

OUTPUT
Main thread is running concurrently with the child thread.
Child thread is running.
Object Oriented Programming with JAVA- Manual

VIAV -QUESTIONS

What is the difference between OOP and SOP?


What is OOPs?
Why use OOPs?
What are the main features of OOPs?
What is an object?
What is a class?
What is the difference between a class and a structure?
Can you call the base class method without creating an instance?
What is the difference between a class and an object?
What is inheritance?
What is Java?
Why is Java a platform independent language?
What are the differences between C++ and Java?
Why is Java not a pure object oriented language?
List the features of the Java Programming language?
What do you get in the Java download file?
Explain JVM, JRE, and JDK.
What is a ClassLoader?
What are the Memory Allocations available in JavaJava?What is Java?
Why is Java a platform independent language?
What are the differences between C++ and Java?
Why is Java not a pure object oriented language?
List the features of the Java Programming language?
What do you get in the Java download file?
Explain JVM, JRE, and JDK.
What is a ClassLoader?
What are the Memory Allocations available in JavaJava?
BCS306A-Object Oriented Programming with JAVA Manual

Department of Computer Science & Design , KSIT Page | 28 2023-24

You might also like