[go: up one dir, main page]

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

Javalab

The document contains multiple Java programming tasks, including matrix addition, stack implementation, employee management, point representation, shape polymorphism, abstract classes, interfaces, and nested classes. Each task includes code snippets demonstrating the required functionality, such as matrix operations, stack methods, employee salary adjustments, and geometric calculations. The document serves as a comprehensive guide for implementing various object-oriented programming concepts in Java.

Uploaded by

Jyoti Siddoji
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)
7 views26 pages

Javalab

The document contains multiple Java programming tasks, including matrix addition, stack implementation, employee management, point representation, shape polymorphism, abstract classes, interfaces, and nested classes. Each task includes code snippets demonstrating the required functionality, such as matrix operations, stack methods, employee salary adjustments, and geometric calculations. The document serves as a comprehensive guide for implementing various object-oriented programming concepts in Java.

Uploaded by

Jyoti Siddoji
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

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.io.*;

class GFG {

// Function to print Matrix


static void printMatrix(int M[][],
int rowSize,
int colSize)
{
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
System.out.print(M[i][j] + " ");

System.out.println();
}
}

// Function to add the two matrices


// and store in matrix C
static int[][] add(int A[][], int B[][],
int size)
{
int i, j;
int C[][] = new int[size][size];

for (i = 0; i < size; i++)


for (j = 0; j < size; j++)
C[i][j] = A[i][j] + B[i][j];

return C;
}

// Driver code
public static void main(String[] args)
{
int size = 4;

int A[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices A
System.out.println("\nMatrix A:");
printMatrix(A, size, size);

int B[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices B
System.out.println("\nMatrix B:");
printMatrix(B, size, size);

// Add the two matrices


int C[][] = add(A, B, size);

// Print the result


System.out.println("\nResultant Matrix:");
printMatrix(C, size, size);
}
}

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
{
// Pushing element on the top of the stack
static void stack_push(Stack<Integer> stack)
{
for(int i = 0; i < 5; 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);
}

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);
}
}

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.io.*;
public class Employee {
private String name;
private String jobTitle;
private double salary;
public Employee(String name,
String jobTitle, double salary) {
this.name = name;
this.jobTitle = jobTitle;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String
name) {
this.name = name;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String
jobTitle) {
this.jobTitle = jobTitle;
import java.io.*;
public class Employee {
private String name;
private String jobTitle;
private double salary;
public Employee(String name,
String jobTitle, double salary) {
this.name = name;
this.jobTitle = jobTitle;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String
name) {
this.name = name;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String
jobTitle) {
this.jobTitle = jobTitle;
import java.io.*;
public class Employee {
private String name;
private String jobTitle;
private double salary;
public Employee(String name,
String jobTitle, double salary) {
this.name = name;
this.jobTitle = jobTitle;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String
name) {
this.name = name;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String
jobTitle) {
this.jobTitle = jobTitle;
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.
Save Filename as as:
EmployeeMain.java
Solution:-
import java.util.Scanner;
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 int
getId ()
{
return id;
}
public Strin
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.
Save Filename as as:
EmployeeMain.java
Solution:-
import java.util.Scanner;
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 int
getId ()
{
return id;
}
public Strin
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)
{
double raiseAmount = salary * (percent / 100);
salary += raiseAmount;
System.out.println(name + "'s salary raised by " + percent + "%. New salary: $" +
salary);
}

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

public String toString() {


return "Employee ID: " + id + ", Name: " + name + ", Salary: $" + salary;
}

public static void main(String[] args)


{
// Creating an Employee object
Employee employee = new Employee(1, "John Doe", 50000.0);

// Displaying employee details


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

// Raising salary by 10%


employee.raiseSalary(10);

// Displaying updated employee details


System.out.println("\nEmployee Details after Salary Raise:");
System.out.println(employee);
}
}

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;

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

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

// Set both x and y


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

// Get x and y in a 2-element int array


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

// Return a string description of the instance in the format "(x, y)"


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

// Calculate distance from this point to another point at (x, y) coordinates


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

// Calculate distance from this point to another MyPoint instance (another)


public double distance(MyPoint another) {
return distance(another.x, another.y);
}

// Calculate distance from this point to the origin (0,0)


public double distance() {
return distance(0, 0);
}
}
TestMyPoint.java

public class TestMyPoint {


public static void main(String[] args) {
// Creating MyPoint objects using different constructors
MyPoint point1 = new MyPoint();
MyPoint point2 = new MyPoint(3, 4);
// Testing setXY and getXY methods
point1.setXY(1, 2);
System.out.println("Point1 coordinates after setXY: " + point1.getXY()[0] + ", " +
point1.getXY()[1]);

// Testing toString method


System.out.println("Point2 coordinates: " + point2.toString());

// Testing distance methods


System.out.println("Distance from Point1 to Point2: " + point1.distance(point2));
System.out.println("Distance from Point2 to Origin: " + point2.distance());
}
}

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 15.09.2023 14.09.2023 Annexure-II 3 3 polymorphism
concepts by developing suitable methods, defining member data and main program.

class Shape
{
void draw()
{
System.out.println(“Shape draw()”);
}
void erase()
{
System.out.println (“ Shape erase()”);
}
}
class Circle extends Shape
{
void draw()
{
System.out.println (“Circle draw()”);
}
void erase()
{
System.out.println (“Circle erase()”);
}
}
class Triangle extends Shape
{
void draw()
{
System.out.println(“Triangle erase()”);
}
}
class Square extends Shape
{
void draw()
{
System.out.println (“Square draw()”);
}
void erase()
{
System.out.println (“Square erase()”);
}
}
public class Shapes
{
public static Shape randshape()
{
switch((int)(Math.random()*3))
{
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
default : System.out.println(“default”);
return new Shape();
}
}
public static void main (String arg[])
{
Shape s[] = new Shape[9];
for(int i = 0;i< s.length; i++)
s[i] = randshape();
for(int i= 0;i < s.length; i++)
s[i].draw();
}
}

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
mport java.util.*;

abstract class shape

int a,b;

abstract public void printarea();

class rectangle extends shape

public int area_rect;

public void printarea()

Scanner s=new Scanner(System.in);

System.out.println("enter the length and breadth of rectangle");

a=s.nextInt();

b=s.nextInt();

area_rect=a*b;
System.out.println("Length of rectangle "+a +"breadth of rectangle "+b);

System.out.println("The area ofrectangle is:"+area_rect);

class triangle extends shape

double area_tri;

public void printarea()

Scanner s=new Scanner(System.in);

System.out.println("enter the base and height of triangle");

a=s.nextInt();

b=s.nextInt();

System.out.println("Base of triangle "+a +"height of triangle "+b);

area_tri=(0.5*a*b);

System.out.println("The area of triangle is:"+area_tri);

class circle extends shape

{
double area_circle;

public void printarea()

Scanner s=new Scanner(System.in);

System.out.println("enter the radius of circle");

a=s.nextInt();

area_circle=(3.14*a*a);

System.out.println("Radius of circle"+a);

System.out.println("The area of circle is:"+area_circle);

public class shapeclass

public static void main(String[] args)

rectangle r=new rectangle();

r.printarea();

triangle t=new triangle();

t.printarea();

circle r1=new circle();


r1.printarea();

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

// Declare the Resizable interface


interface Resizable {
// Declare the abstract method "resizeWidth" to resize the width
void resizeWidth(int width);

// Declare the abstract method "resizeHeight" to resize the height


void resizeHeight(int height);
}

Rectangle.java

// Declare the Rectangle class, which implements the Resizable interface

class Rectangle implements Resizable {

// Declare private instance variables to store width and height

private int width;

private int height;

// Constructor for initializing the width and height

public Rectangle(int width, int height) {

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

// Implement the "resizeWidth" method to resize the width

public void resizeWidth(int width) {

this.width = width;

// Implement the "resizeHeight" method to resize the height

public void resizeHeight(int height) {

this.height = height;

// Method to print the current width and height of the rectangle

public void printSize() {

System.out.println("Width: " + width + ", Height: " + height);

Copy
// Main.java

// Declare the Main class

public class Main {

public static void main(String[] args) {

// Create an instance of the Rectangle class with an initial size

Rectangle rectangle = new Rectangle(100, 150);


// Print the initial size of the rectangle

rectangle.printSize();

// Resize the rectangle by changing its width and height

rectangle.resizeWidth(150);

rectangle.resizeHeight(200);

// Print the updated size of the rectangle

rectangle.printSize();

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.
Java Program to Demonstrate Nested class

// Class 1
// Helper classes
class Outer {

// Class 2
// Simple nested inner class
class Inner {

// show() method of inner class


public void show()
{

// Print statement
System.out.println("In a nested class method");
}
}
}

// Class 2
// Main class
class Main {
// Main driver method
public static void main(String[] args)
{

// Note how inner class object is created inside


// main()
Outer.Inner in = new Outer().new Inner();

// Calling show() method over above object created


in.show();
}
}

9. Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally
lass Main {
public static void main(String args[]) {
//try block
try{
System.out.println("::Try block::");
int num=67/0;
System.out.println(num);
}
//catch block
catch(ArithmeticException e){
System.out.println("::Catch block::");
System.out.println("ArithmeticException::Number divided by zero");
}
//finally block
finally{
System.out.println("::Finally block::");
}
System.out.println("Rest of the code continues...");
}
}

10. Develop a JAVA program to create a package named mypack and import &
implement it in a suitable class
//create a package
package my pack;
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 my pack. Circle;
class Eg
{
public static void main(String a[])
{
Circle c = new Circle();
c.area();
}
}

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 IntThread implements Runnable
{
Thread t;
IntThread()
{ t = new Thread ( this, “Test thread”);
System.out.println (“ Child thread :” + t);
t.start();
}
public void run()
{ try
{
for (int i= 5; i0; j--)
{ System.out.println (“Main thread :” + j); Thread.sleep (1000); } } catch
(InterruptedException e) { } System.out.println ( “Main thread exiting …”); } }

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 MyRunnable implements Runnable {


private volatile boolean running = true;

@Override
@SuppressWarnings("deprecation")
public void run() {
while (running) {
try {
// Suppress deprecation warning for Thread.sleep()
Thread.sleep(500);
System.out.println("Thread ID: " + Thread.currentThread().getId() + " is
running.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}

public void stopThread() {


running = false;
}
}

public class RunnableThreadExample {


public static void main(String[] args) {
// Create five instances of MyRunnable
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
MyRunnable myRunnable3 = new MyRunnable();
MyRunnable myRunnable4 = new MyRunnable();
MyRunnable myRunnable5 = new MyRunnable();

// Create five threads and associate them with MyRunnable instances


Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
Thread thread3 = new Thread(myRunnable3);
Thread thread4 = new Thread(myRunnable4);
Thread thread5 = new Thread(myRunnable5);

// Start the threads


thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();

// Sleep for a while to allow the threads to run


try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

// Stop the threads gracefully


myRunnable1.stopThread();
myRunnable2.stopThread();
myRunnable3.stopThread();
myRunnable4.stopThread();
myRunnable5.stopThread();
}
}

You might also like