0% found this document useful (0 votes)
44 views26 pages

Java Manual 2024-2025

The document is a lab manual for the Object Oriented Programming with Java course at Don Bosco Institute of Technology, outlining the vision, mission, program educational objectives, and specific outcomes for students in the Department of Artificial Intelligence and Data Science. It includes a series of programming exercises designed to teach Java concepts such as classes, inheritance, polymorphism, exception handling, and multithreading. Additionally, it provides viva questions for each program to assess students' understanding of the material.

Uploaded by

BLΛƆKPIИK
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)
44 views26 pages

Java Manual 2024-2025

The document is a lab manual for the Object Oriented Programming with Java course at Don Bosco Institute of Technology, outlining the vision, mission, program educational objectives, and specific outcomes for students in the Department of Artificial Intelligence and Data Science. It includes a series of programming exercises designed to teach Java concepts such as classes, inheritance, polymorphism, exception handling, and multithreading. Additionally, it provides viva questions for each program to assess students' understanding of the material.

Uploaded by

BLΛƆKPIИK
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/ 26

DON BOSCO INSTITUTE OF

TECHNOLOGY
Kumbalagodu, Mysuru Road, Bengaluru – 560074

Department of
Artificial Intelligence
&
Data Science

III SEMESTER / BE
[As per Choice Based Credit System (CBCS) 2022 Scheme]

Object Oriented
Programming with Java
Laboratory
(BCS306A)

LAB MANUAL

1
DEPARTMENT OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE

VISION

 To develop high caliber Data Science professionals who can render innovative software
services based on AI technologies to provide solutions to ethical problems.

MISSION
 M 1: To provide skill-based training to students on software tools relevant to AI and DS
 M 2: To inculcate specific professional thinking in students this would help them to conceptualize AI solutions
using DS.
 M 3: To inculcate professional ethics which supports students to provide AI based solutions limited to ethical
problems only.
 M 4: To provide students with fundamental knowledge of relevant mathematics in order to make them
conceptualize AI based solutions.

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

 PEO 1: Graduates shall be able to use their knowledge to identify real life problem that fits
well into the solution framework of AI and be able to architect solutions using paradigms of
DS. PEO 2: Graduates shall work individually and in teams for developing innovative
solutions in the area of AI & DS
 PEO 3: Graduates shall be able to grow professionally by enhancing their knowledge and
skills through continuous learning
 PEO 4: Graduates shall exhibit ethical thinking while leveraging their knowledge of AI and
DS to build technology solutions.

PROGRAM SPECIFIC OUTCOMES (PSOs)

 PSO 1: Model specified real life problems using AI paradigms and also to solve challenges
of Big data by using the acquired technical knowledge.
 PSO 2: Develop enough potential to work in teams in order to address multidisciplinary problems
using technical knowledge and life skills
 PSO 3: Keep pace with technological advancements in order to leverage state-of-the-Art solutions
based on Artificial Intelligence and Data Science

COURSE OUTCOMES:
At the end of the course the students are able to:
CO 1. Demonstrate proficiency in writing simple programs involving branching and looping structures.
CO 2. Design a class involving data members and methods for the given scenario.
CO 3. Apply the concepts of inheritance and interfaces in solving real world problems.
CO 4. Use the concept of packages and exception handling in solving complex problem
CO 5. Apply concepts of multithreading, autoboxing and enumerations in program development

2
PROGRAM OUTCOMES(POs)

Engineering Graduates should possess the following:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


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

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

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

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

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

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

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

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

9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.

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

11. 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 multi-disciplinary environments.

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

3
Object Oriented Programming with JAVA-BCS306A

CONTENTS

SI.NO Programs Page. No


1 Develop a JAVA program to add TWO matrices of suitable order N (The value 5-6
of N should beread from command line arguments).

2 Develop a stack class to hold a maximum of 10 integers with suitable methods. 7-8
Develop a JAVAmain method to illustrate Stack operations.

3 A class called Employee, which models an employee with an ID, name and 9-10
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.

5 Develop a JAVA program to create a class named shape. Create three sub 11-13
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 dataand main program.

6 Develop a JAVA program to create an abstract class Shape with abstract 14-15
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.

7 Develop a JAVA program to create an interface Resizable with methods 16-17


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

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

9 Develop a JAVA program to raise a custom exception (user defined exception) 20


for DivisionByZerousing try, catch, throw and finally
10 Develop a JAVA program to create a package named mypack and import & 21-22
implement it in asuitable class.

11 Write a program to illustrate creation of threads using runnable class. (start 23-24
method start each of the newly created thread. Inside the run method there is
sleep() for suspend the thread for 500 ms).
12 Develop a program to create a class MyThread in this class a constructor, call 25-26
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.

4
Object Oriented Programming with JAVA-BCS306A
Program 1: Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).

import java.util.Scanner;
public class AddMatrices
{
public static void main(String[] args)
{
int size=Integer.parseInt(args[0]);
int A[][]=new int[size][size];
int B[][]=new int[size][size];
int C[][]=new int[size][size];
Scanner sc=new Scanner(System.in);
System.out.println("\nEnter the elements in to Matrix A:");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
A[i][j]=sc.nextInt();
}
}
System.out.println("\nEnter the elemnts in to Matrix B:");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
B[i][j]=sc.nextInt();
}
}
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
System.out.println("\n Sum of two Matrices:=:");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
System.out.print(" "+C[i][j]);
}
System.out.println();
}
}
}

5
Object Oriented Programming with JAVA-BCS306A

Viva:
1. What is a matrix in programming?
2. How do you declare a 2D array in Java?
3. How do you read values from the command line in Java?
4. What is the purpose of the Scanner class in Java?

6
Object Oriented Programming with JAVA-BCS306A

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

class Stack {
private int arr[];
private int top;
private int capacity;
Stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}
public void push(int x)
{
if (isFull())
{
System.out.println("Stack OverFlow");
System.exit(1);
}
System.out.println("Inserting " + x);

arr[++top] = x;

}
public int pop()
{
if (isEmpty())
{
System.out.println("STACK EMPTY");
System.exit(1);
}
return arr[top--];
}
public int getSize() {
return top + 1;
}
public Boolean isEmpty() {
return top == -1;
}
public Boolean isFull() {
return top == capacity - 1;
}
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}
7
Object Oriented Programming with JAVA-BCS306A
public static void main(String[] args) {
Stack stack = new Stack(5);

stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();

}
}

Viva:
1. What is a stack in programming?
2. What does the push operation in a stack do?
3. What is the purpose of the pop operation in a stack?
4. How do you check if a stack is empty or full in Java?

8
Object Oriented Programming with JAVA-BCS306A
Program 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.

import java.util.Scanner;
class Employee {
String ID, name;
float salary;

float raiseSalary(float percentage) {


return salary + (salary * (percentage / 100));
}
}

public class EmpApp {


public static void main(String[] args) {
Employee e1 = new Employee(); // Use 'empclass' instead of 'Employee'
Scanner sc = new Scanner(System.in);

e1.name = "Abc";
e1.ID = "CSE01";
e1.salary = 50000;

System.out.println("Enter the percentage of increment: ");


int incr = sc.nextInt();

System.out.println("Salary After Increment: " + e1.raiseSalary(incr));


}
}

9
Object Oriented Programming with JAVA-BCS306A

Viva:
1. What is the purpose of the raiseSalary method in the Employee class?
2. How would you encapsulate the fields (ID, name, salary) in the Employee class using getter and setter
methods?
3. Why do we pass a percentage as a parameter in the raiseSalary method, and how is it used to
calculate the new salary?
4. What is the advantage of using constructors in the Employee class to initialize objects?

10
Object Oriented Programming with JAVA-BCS306A
Program 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.

abstract class Shape {


public abstract double getArea();
public abstract double getPerimeter();
}
class Circle extends Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

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

@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double getArea() {
return length * width;
}

@Override
public double getPerimeter() {
return 2 * (length + width);
}
}
class Triangle extends Shape {
private double side1;
private double side2;
private double side3;

11
Object Oriented Programming with JAVA-BCS306A
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

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

@Override
public double getPerimeter() {
return side1 + side2 + side3;
}
}
public class Main {
public static void main(String[] args) {
double r = 4.0;
Circle circle = new Circle(r);
double rs1 = 4.0, rs2 = 6.0;
double ts1 = 3.0, ts2 = 4.0, ts3 = 5.0;
Rectangle rectangle = new Rectangle(rs1, rs2);
Triangle triangle = new Triangle(ts1, ts2, ts3);
System.out.println("Radius of the Circle"+r);
System.out.println("Area of the Circle: " + circle.getArea());
System.out.println("Perimeter of the Circle: " + circle.getPerimeter());
System.out.println("\nSides of the rectangle are: "+rs1+','+rs2);
System.out.println("Area of the Rectangle: " + rectangle.getArea());
System.out.println("Perimeter of the Rectangle: " + rectangle.getPerimeter());
System.out.println("\nSides of the Traiangel are: "+ts1+','+ts2+','+ts3);
System.out.println("Area of the Triangle: " + triangle.getArea());
System.out.println("Perimeter of the Triangle: " + triangle.getPerimeter());
}
}

12
Object Oriented Programming with JAVA-BCS306A

Viva:
1. What is polymorphism, and how is it demonstrated in this program?
2. How does method overriding work in the context of the draw() and erase() methods in the
subclasses?
3. What is the difference between compile-time and run-time polymorphism in Java?
4. How does dynamic method dispatch work in Java when you call draw() and erase() on different
shape objects?

13
Object Oriented Programming with JAVA-BCS306A

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

abstract class Shape {


abstract double calculateArea();
abstract double calculatePerimeter();
}
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;
}
}
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;
}

@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;
}
14
Object Oriented Programming with JAVA-BCS306A
}
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());
}
}

Viva:
1. What is the purpose of using an abstract class in Java?
2. How do you implement abstract methods in subclasses of an abstract class?
3. What is the formula for calculating the area and perimeter of a circle?
4. How does method overriding work in the context of subclasses extending an abstract class?

15
Object Oriented Programming with JAVA-BCS306A
Program 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

interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
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);
}
}
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();
}
}

16
Object Oriented Programming with JAVA-BCS306A

Viva:
1. What is an interface in Java, and how is it different from an abstract class?
2. How does a class implement an interface in Java?
3. What is the purpose of the resizeWidth() and resizeHeight() methods in the Resizable interface?
4. Can a class implement multiple interfaces in Java? If so, how would you do that?

17
Object Oriented Programming with JAVA-BCS306A
Program 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{
String so = ("This is Outer Class");
void display()
{
System.out.println(so);
}
void test(){
Inner inner = new Inner();
inner.display();
}
class Inner{
String si =("This is inner Class");
void display(){
System.out.println(si);
}
}
}
class InnerClassDemo{
public static void main(String args[]){
Outer outer = new Outer();
outer.display();
outer.test();
}
}

18
Object Oriented Programming with JAVA-BCS306A
Viva :

1. What is an inner class in Java?


2. How do you access the display() method of the inner class from the main method?
3. What is the difference between a static and non-static inner class in Java?
4. Can an inner class access the private members of its outer class? If yes, how?

19
Object Oriented Programming with JAVA-BCS306A

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

import java.util.*;
class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
int numerator = 5;
int denominator = 0;
try {
if (denominator == 0) {
throw new DivideByZeroException("Error: Cannot divide a number by zero.");
}
int answer = numerator / denominator;
System.out.println("Result: " + answer);
} catch (DivideByZeroException ex) {
System.out.println(ex.getMessage());
}
}
}

Viva:
1. How do you create a user-defined (custom) exception in Java?
2. What is the purpose of the throw keyword in exception handling?
3. How does the finally block work, and when is it executed?
4. Why is it important to handle the division by zero scenario in Java?

20
Object Oriented Programming with JAVA-BCS306A

Program 10: Develop a JAVA program to create a package named mypack and import &
implement it in a suitable class.

package mypack;
class Circle
{
double r;
void area()
{
System.out.println("Area of the circle = " + (3.14 * r * r));
}
}
class Square
{
double s;
void area()
{
System.out.println("Area of the Square = " + (s * s));
}
}
class Rectangle
{
double l,b;
void area()
{
System.out.println("Area of the circle = " + (l * b));
}
}
//implements the package
import mypack.Circle;
import mypack.Rectangle;
import mypack.Square;
class Eg
{
public static void main(String a[])
{
Circle c = new Circle();
c.area();
Rectangle r = new Rectangle();
r.area();
Square s = new Square();
s.area();
}
}

21
Object Oriented Programming with JAVA-BCS306A

Viva:
1. What is a package in Java, and why is it used?
2. How do you create and define a custom package in Java?
3. How do you import a class from a package into another class or program?
4. What is the significance of the CLASSPATH environment variable in relation to packages?

22
Object Oriented Programming with JAVA-BCS306A
Program 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).

class NewThread implements Runnable {


String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MyClass
{
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

23
Object Oriented Programming with JAVA-BCS306A

Viva:
1. What is the difference between implementing Runnable and extending the Thread class in Java?
2. How does the start() method differ from the run() method when working with threads?
3. What is the purpose of the sleep() method in thread handling, and how does it affect the thread's
execution?
4. What happens if an InterruptedException occurs during thread sleep, and how do you handle it?

24
Object Oriented Programming with JAVA-BCS306A

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

class MyThread extends Thread {


MyThread() {
super("Using Thread class");
System.out.println("Child thread: " + this);
start(); // Start the child thread
}

public void run() {


try {
for (int i = 5; i > 0; i--) {
System.out.println("Child thread: " + i);
Thread.sleep(500); // Sleep for 500ms
}
} catch (InterruptedException e) {
System.out.println("Child thread interrupted.");
}
System.out.println("Exiting child thread...");
}
}

class TestMyThread {
public static void main(String[] args) {
new MyThread(); // Create and start a new thread

try {
for (int k = 5; k > 0; k--) { // Corrected the loop condition
System.out.println("Running main thread: " + k);
Thread.sleep(1000); // Sleep for 1000ms
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Exiting main thread...");
}
}

25
Object Oriented Programming with JAVA-BCS306A

Viva:
1. What is the purpose of the super() call in the constructor of the MyThread class?
2. How do you start a thread in Java, and what is the role of the start() method?
3. What is the difference between the start() and run() methods when working with threads?
4. How does Java achieve concurrent execution of the main thread and the child thread?

26

You might also like