0% found this document useful (0 votes)
4 views22 pages

Java Lab

The document contains a Java lab manual with multiple programming exercises, including matrix addition, stack implementation, employee management, point manipulation, shape drawing, resizing rectangles, abstract shapes, nested classes, custom exceptions, and thread creation. Each exercise includes code examples and explanations of the concepts being demonstrated, such as polymorphism, inheritance, and exception handling. The manual serves as a comprehensive guide for students to practice and understand Java programming fundamentals.

Uploaded by

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

Java Lab

The document contains a Java lab manual with multiple programming exercises, including matrix addition, stack implementation, employee management, point manipulation, shape drawing, resizing rectangles, abstract shapes, nested classes, custom exceptions, and thread creation. Each exercise includes code examples and explanations of the concepts being demonstrated, such as polymorphism, inheritance, and exception handling. The manual serves as a comprehensive guide for students to practice and understand Java programming fundamentals.

Uploaded by

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

JAVA LAB MANUAL

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 [Link];

class MatrixAddition {
public static void main(String[] args) {

// Check if N is provided
if ([Link] == 0) {
[Link]("Please provide the value of N as a command line argument.");
return;
}

int N = [Link](args[0]);
int[][] A = new int[N][N];
int[][] B = new int[N][N];
int[][] C = new int[N][N];

Scanner sc = new Scanner([Link]);

// Read first matrix


[Link]("Enter elements of first matrix:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
A[i][j] = [Link]();
}
}

// Read second matrix


[Link]("Enter elements of second matrix:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
B[i][j] = [Link]();
}
}

// Add matrices
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}

// Display result
[Link]("Resultant Matrix after Addition:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
[Link](C[i][j] + " ");
}
[Link]();
}

[Link]();
}
}
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 maxSize = 10;
private int[] stackArray;
private int top;

// Constructor
public Stack() {
stackArray = new int[maxSize];
top = -1;
}

// Push operation
public void push(int value) {
if (isFull()) {
[Link]("Stack Overflow: Cannot push " + value);
} else {
stackArray[++top] = value;
[Link](value + " pushed into stack.");
}
}

// Pop operation
public int pop() {
if (isEmpty()) {
[Link]("Stack Underflow: No elements to pop.");
return -1;
} else {
int poppedValue = stackArray[top--];
[Link](poppedValue + " popped from stack.");
return poppedValue;
}
}

// Peek operation
public int peek() {
if (isEmpty()) {
[Link]("Stack is empty.");
return -1;
} else {
return stackArray[top];
}
}

// Check if stack is full


public boolean isFull() {
return (top == maxSize - 1);
}

// Check if stack is empty


public boolean isEmpty() {
return (top == -1);
}
// Display stack elements
public void display() {
if (isEmpty()) {
[Link]("Stack is empty.");
} else {
[Link]("Stack elements: ");
for (int i = 0; i <= top; i++) {
[Link](stackArray[i] + " ");
}
[Link]();
}
}
}

public class Main {


public static void main(String[] args) {
Stack stack = new Stack();
[Link](10);
[Link](20);
[Link](30);
[Link]();

[Link]("Top element is: " + [Link]());

[Link]();
[Link]();

[Link]();
[Link]();
[Link](); // Demonstrate underflow
}
}
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 {
// Instance variables
private int id;
private String name;
private double salary;

// Constructor to initialize an Employee object


public Employee(int id, String name, double salary) {
[Link] = id;
[Link] = name;
[Link] = salary;
}

// Method to increase salary by a given percentage


public void raiseSalary(double percent) {
if (percent > 0) {
salary += salary * percent / 100;
}
}

// Getter methods to access employee details


public int getId() {
return id;
}

public String getName() {


return name;
}

public double getSalary() {


return salary;
}

// Method to display employee details


public void display() {
[Link]("Employee ID: " + id);
[Link]("Employee Name: " + name);
[Link]("Employee Salary: " + salary);
}

public static void main(String[] args) {


// Creating Employee object
Employee emp = new Employee(101, "Alice", 50000);

// Display original details


[Link]("Before Salary Raise:");
[Link]();
// Raise salary by 10%
[Link](10);

// Display updated details


[Link]("\nAfter 10% Salary Raise:");
[Link]();
}
}

Output:
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 MyPointProgram {

// Inner class MyPoint


static class MyPoint {
// Instance variables
private int x;
private int y;

// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
}

// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}

// Getter methods
public int getX() {
return x;
}

public int getY() {


return y;
}

// Setter methods
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}

// Set both x and y


public void setXY(int x, int y) {
this.x = x;
this.y = y;
}

// Get both x and y as array


public int[] getXY() {
return new int[] {x, y};
}

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

// Distance from this point to (x, y)


public double distance(int x, int y) {
int xDiff = this.x - x;
int yDiff = this.y - y;
return [Link](xDiff * xDiff + yDiff * yDiff);
}

// Distance from this point to another MyPoint


public double distance(MyPoint another) {
int xDiff = this.x - another.x;
int yDiff = this.y - another.y;
return [Link](xDiff * xDiff + yDiff * yDiff);
}

// Distance from this point to origin (0, 0)


public double distance() {
return [Link](x * x + y * y);
}
}

// Main method to test MyPoint class


public static void main(String[] args) {
// Create points
MyPoint p1 = new MyPoint(); // (0, 0)
MyPoint p2 = new MyPoint(3, 4); // (3, 4)

// Display points
[Link]("p1 is: " + p1);
[Link]("p2 is: " + p2);

// Modify p1
[Link](5, 6);
[Link]("After setXY, p1 is: " + p1);

// Get coordinates
int[] coords = [Link]();
[Link]("p1's coordinates: (" + coords[0] + ", " + coords[1] + ")");

// Test distances
[Link]("Distance from p1 to (10, 11): %.2f%n", [Link](10, 11));
[Link]("Distance from p1 to p2: %.2f%n", [Link](p2));
[Link]("Distance from p2 to origin: %.2f%n", [Link]());
}
}
5. Develop a JAVA program to create a class named [Link] 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

// Online Java Compiler


// Use this editor to write, compile and run your Java code online

class Shape {
public void draw() {
[Link]("Drawing a shape");
}

public void erase() {


[Link]("Erasing a shape");
}
}

// Circle subclass
class Circle extends Shape {
@Override
public void draw() {
[Link]("Drawing a circle");
}

@Override
public void erase() {
[Link]("Erasing a circle");
}
}

// Triangle subclass
class Triangle extends Shape {
@Override
public void draw() {
[Link]("Drawing a triangle");
}

@Override
public void erase() {
[Link]("Erasing a triangle");
}
}

// Square subclass
class Square extends Shape {
@Override
public void draw() {
[Link]("Drawing a square");
}

@Override
public void erase() {
[Link]("Erasing a square");
}
}

public class Main {


public static void main(String[] args) {

// Creating instances of different shapes


Shape circle = new Circle();
Shape triangle = new Triangle();
Shape square = new Square();

// Demonstrating polymorphism
[Link]();
[Link]();

[Link]();
[Link]();

[Link]();
[Link]();
}
}

Output:
6. 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

// Define the interface


interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

// Rectangle class implementing Resizable


class Rectangle implements Resizable {
private int width;
private int height;

// Constructor
Rectangle(int width, int height) {
[Link] = width;
[Link] = height;
}

// Implement resizeWidth
@Override
public void resizeWidth(int width) {
[Link] = width;
[Link]("Width resized to: " + [Link]);
}

// Implement resizeHeight
@Override
public void resizeHeight(int height) {
[Link] = height;
[Link]("Height resized to: " + [Link]);
}

// Method to display the rectangle dimensions


public void display() {
[Link]("Rectangle -> Width: " + width + ", Height: " + height);
}
}

// Main class to test the program


public class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle(20, 10);
[Link]("Initial dimensions:");
[Link]();
// Resize width and height
[Link](50);
[Link](30);

[Link]("\nAfter resizing:");
[Link]();
}
}
7. 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 class Shape {
// Abstract methods
abstract double calculateArea();
abstract double calculatePerimeter();
}

// Circle class extending Shape


class Circle extends Shape {
double radius;

// Constructor
Circle(double radius) {
[Link] = radius;
}

// Implement area
@Override
double calculateArea() {
return [Link] * radius * radius;
}

// Implement perimeter
@Override
double calculatePerimeter() {
return 2 * [Link] * radius;
}
}

// Triangle class extending Shape


class Triangle extends Shape {
double side1, side2, side3;

// Constructor
Triangle(double s1, double s2, double s3) {
this.side1 = s1;
this.side2 = s2;
this.side3 = s3;
}

// Implement area using Heron's formula


@Override
double calculateArea() {
double s = (side1 + side2 + side3) / 2; // semi-perimeter
return [Link](s * (s - side1) * (s - side2) * (s - side3));
}

// Implement perimeter
@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
}

// Main class to test


public class Main {
public static void main(String[] args) {

// Create Circle object


Circle circle = new Circle(5);
[Link]("Circle Area: " + [Link]());
[Link]("Circle Perimeter: " + [Link]());

// Create Triangle object


Triangle triangle = new Triangle(3, 4, 5);
[Link]("\nTriangle Area: " + [Link]());
[Link]("Triangle Perimeter: " + [Link]());
}
}
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.

// Outer class
class Outer {
void display() {
[Link]("This is the display() method of the Outer class.");
}

// Inner class
class Inner {
void display() {
[Link]("This is the display() method of the Inner class.");
}
}
}

// Main class
public class MainClass {
public static void main(String[] args) {

// Create object of Outer class


Outer outerObj = new Outer();
[Link]();

// Create object of Inner class using outer class reference


[Link] innerObj = [Link] Inner();
[Link]();
}
}
9. Develop a JAVA program to raise a custom exception (user defined
exception) for DivisionByZero using try, catch, throw and finally.

// Custom Exception
class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}

public class Main {


// Method to divide two numbers
static int divide(int a, int b) throws DivisionByZeroException {
if (b == 0) {
throw new DivisionByZeroException("Error: Division by zero is not
allowed!");
}
return a / b;
}

public static void main(String[] args) {


try {
int x = 10;
int y = 0;

int result = divide(x, y);


[Link]("Result: " + result);

} catch (DivisionByZeroException e) {
[Link]("Custom Exception Caught: " + [Link]());

} finally {
[Link]("Finally block executed.");
}
}
}
10. 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 MyThread implements Runnable {

private String threadName;

MyThread(String name) {
[Link] = name;
}

// run() method of Runnable


public void run() {
try {
for (int i = 1; i <= 5; i++) {
[Link](threadName + " - Count: " + i);
[Link](500); // Suspend thread for 500 milliseconds
}
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
}
}
}

public class Main {


public static void main(String[] args) {

// Create Runnable objects


MyThread t1 = new MyThread("Thread 1");
MyThread t2 = new MyThread("Thread 2");

// Create actual threads


Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t2);

// Start the threads


[Link]();
[Link]();
}
}
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 Main implements Runnable


{
public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{
[Link]([Link]().getName() + " : " + i);
[Link](500); // sleep for 500 milliseconds
}
}
catch (InterruptedException e)
{
[Link]("Thread interrupted");
}
}

public static void main(String[] args)


{
Main obj = new Main();

Thread t1 = new Thread(obj, "Thread-1");


Thread t2 = new Thread(obj, "Thread-2");

[Link](); // start thread 1


[Link](); // start thread 2
}
}
12th program is not included for CIE just copy it for the record.

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 Main


{
// Child thread class
static class MyThread extends Thread
{
// Constructor
MyThread()
{
super(); // calling base class constructor
start(); // start the thread
}

// run method
public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{
[Link]("Child thread : " + i);
[Link](500);
}
}
catch (InterruptedException e)
{
[Link]("Child thread interrupted");
}
}
}

// Main method
public static void main(String[] args)
{
// Create child thread
MyThread t = new MyThread();
try
{
for (int i = 1; i <= 5; i++)
{
[Link]("Main thread : " + i);
[Link](500);
}
}
catch (InterruptedException e)
{
[Link]("Main thread interrupted");
}
}
}

You might also like