0% found this document useful (0 votes)
11 views21 pages

Java Matrix, Stack, and Shape Classes

Uploaded by

laxmigundmi
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)
11 views21 pages

Java Matrix, Stack, and Shape Classes

Uploaded by

laxmigundmi
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

1.

Develop a JAVA program to add TWO matrices of suitable order N (The


value of N should be read from command line arguments).

public class MatrixAddition{


public static void main(String[]args){
if([Link]!=1){
[Link]("Usage:javaMatrixAddition<N>");
return;
}

int N=[Link](args[0]);
int[][] matrixA=new int[N][N];
int[][] matrixB=new int[N][N];
int[][] resultMatrix=new int[N][N];

fillMatrix(matrixA,N);
fillMatrix(matrixB,N);

for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
resultMatrix[i][j]=matrixA[i][j]+matrixB[i][j];
}
}

[Link]("MAtrixA:");
printMatrix(matrixA,N);
[Link]("MAtriB:");
printMatrix(matrixB,N);
[Link]("Sum of matrices of A and B ar:");
printMatrix(resultMatrix,N);
}

private static void fillMatrix(int[][] matrix,int N){


for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
matrix[i][j]=(int)([Link]()*100);
}
}
}

private static void printMatrix(int[][] matrix,int N){


for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
[Link](matrix[i][j]+" ");
}
[Link]();
}
[Link]();

1
}

OUTPUT:

Javac [Link]
Java MatrixAddition 2
Matrix A:
71 19
77 45
Matrix B:
25 18
20 39
Sum of matrices of A and B are:
96 37
97 84

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

package prg2;

import [Link];
class Stack{
int top;
int s[]=new int[10];
Stack(){
top-=1;
}

void push(int item){


if([Link]-1==top){
[Link]("Stack over folw");
return;
}

else{
top+=1;
s[top]=item;
}
}

void pop(){
if(top==-1){
[Link]("Stack underflow");
return;
}

else{
int item=s[top];
[Link]("item deleted popped :"+item);
top-=1;
}
}

void display(){
if(top==-1){
[Link]("Stack is empty, no item to display");
}

else{
[Link]("Item in stack are:");
for(int i=top;i>=0;i--){
[Link](s[i]);
} } }}

public class Prg2 {

3
public static void main(String[] args) {

int ch;
Stack stk=new Stack();
Scanner in=new Scanner([Link]);
while(true){
[Link]("Stack operation demo");
[Link]("Enter 1:push,2:pop,3:display item,4:exit");
ch=[Link]();
switch(ch){

case 1:
[Link]("Enter the item to be pushed into stack");
int item=[Link]();
[Link](item);
break;
case 2:[Link]();
break;
case 3:
[Link]();
break;
case 4:[Link](0);
default:[Link]("enter the valid choice");
}
}
}
}

OUTPUT:

run:
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
1
Enter the item to be pushed into stack
10
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
1
Enter the item to be pushed into stack
20
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
1
Enter the item to be pushed into stack
30
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
1

4
Enter the item to be pushed into stack
40

Stack operation demo


Enter 1:push,2:pop,3:display item,4:exit
2
item deleted popped :40
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
3
Item in stack are:
30
20
10
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit

5
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 raise
Salary (percent) increases the salary by the given percentage. Develop the
Employee class and suitable main method for demonstration.
class Employeesal{

private int id;


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

public void raiseSalary(double percent){


if(percent>0){
double raiseAmount=salary*(percent/100);
salary+=raiseAmount;
[Link](name+"'s salary rasied by "+percent+"%.\nNewsalary:$"+salary);
}
else{
[Link]("Invalid [Link] remains unchanged");
}
}

public void EmployeeDetails(){


[Link]("Employee ID "+id+"\nName "+ name+"\nsalary:$"+salary);
}
}
public class Employee{

public static void main(String[] args) {


Employeesal employee=new Employeesal(1,"Vishal",5000);

[Link]("Initial employee deatils:");


[Link]();

[Link](30);

[Link]("Enployee details after raise salary:");


[Link]();

}
}

6
OUTPUT:

run:
Initial employee deatils:
Employee ID 1
Name Vishal
salary:$5000.0
Vishal's salary rasied by 30.0%.
New salary:$6500.0
Enployee details after raise salary:
Employee ID 1
Name Vishal
salary:$6500.0
BUILD SUCCESSFUL (total time: 0 seconds)

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

class MyPoint {
private int x;
private int y;

public MyPoint() {
this.x = 0;
this.y = 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;
}

public double distance(int x, int y) {

8
int xDiff = this.x - x;
int yDiff = this.y - y;
return [Link](xDiff * xDiff + yDiff * yDiff);
}

public double distance(MyPoint another) {


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

public double distance() {


return [Link](x * x + y * y);
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
public class TestMyPoint {
public static void main(String[] args) {
MyPoint point1 = new MyPoint(); // Using default constructor
MyPoint point2 = new MyPoint(3, 4); // Using overloaded constructor

[Link](1, 2);
int[] coordinates = [Link]();
[Link]("Point 1 coordinates: (" + coordinates[0] + ", " + coordinates[1] + ")");

[Link]("Distance from Point 1 to (5, 6): " + [Link](5, 6));


[Link]("Distance from Point 1 to Point 2: " + [Link](point2));
[Link]("Distance from Point 1 to the origin: " + [Link]());

[Link]("Point 1: " + point1);


[Link]("Point 2: " + point2);
}
}

OUTPUT:
run:
Point 1 coordinates: (1, 2)
Distance from Point 1 to (5, 6): 5.656854249492381
Distance from Point 1 to Point 2: 2.8284271247461903
Distance from Point 1 to the origin: 2.23606797749979
Point 1: (1, 2)
Point 2: (3, 4)
BUILD SUCCESSFUL (total time: 0 seconds)

9
[Link] 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
package shapes;
class Shape {

public void draw() {


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

public void erase() {


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

class Circle extends Shape {

@Override
public void draw() {
[Link]("Drawing a circle");
}

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

class Triangle extends Shape {

@Override
public void draw() {
[Link]("Drawing a triangle");
}

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

class Square extends Shape {

@Override
public void draw() {
[Link]("Drawing a square");
}

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

public class Shapes {

public static void main(String[] args) {


Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();

for (int i = 0; i<[Link]; i++) {

// Polymorphic method invocation


shapes[i].draw();
shapes[i].erase();
[Link]("------------------------");
}

}
}

OUTPUT:

run:
Drawing a circle
erasing a circle
----------
Drawing a triangle
erasing a triangle
----------
Drawing a square
erasing a square
----------
BUILD SUCCESSFUL (total time: 0 seconds)

11
6. Develop a JAVA program to create an abstract class Shape with abstract
methods calculateArea() andcalculatePerimeter(). Create subclasses Circle
and Triangle that extend the Shape class and implementthe respective methods
to calculate the area and perimeter of each shape.

package abstractshapes;

abstract class Shape_1 {

abstract double calculateArea();

abstract double calculatePerimeter();


}

// Circle subclass
class Circle_1 extends Shape_1 {

private double radius;

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

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

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

// Triangle subclass
class Triangle_1 extends Shape_1 {

private double side1, side2, side3;

// Constructor
public Triangle_1(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

@Override
double calculateArea() {
// Heron's formula for calculating the area of a triangle
double s = (side1 + side2 + side3) / 2;
return [Link](s * (s - side1) * (s - side2) * (s - side));

12
}

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

public class AbstractShapes {


public static void main(String[] args) {
// TODO code application logic here
Circle_1 circle = new Circle_1(5);
[Link]("Circle Area: " + [Link]());
[Link]("Circle Perimeter: " + [Link]());

Triangle_1 triangle = new Triangle_1(3, 4, 5);


[Link]("Triangle Area: " + [Link]());
[Link]("Triangle Perimeter: " + [Link]());
}

OUTPUT:

run:
Cirle Area is 78.53981633974483
Circle Perimeter 31.41592653589793
Triangle Area 6.0
Triangle Perimeter 12.0
BUILD SUCCESSFUL (total time: 0 seconds)

13
7. Develop a JAVA program to create an interface Resizable with methods resize
Width(int width) and resize Height(int height) that allow an object to be
resized. Create a class Rectangle that implements the Resizable interface and
implements the resize methods.

package testresizable;
interface Resizable
{
void resizewidth(int width);
void resizeheight(int height);
}

class Rectangle
{
private int width;
private int height;
public Rectangle(int width,int height)
{
[Link]=width;
[Link]=height;
}
public void resizewidth(int width)
{
[Link]=width;
}
public void resizeheight(int height)
{
[Link]=height;
}
public void display()
{
[Link]("Rectangle width:"+width+",height"+height);
}
}

public class Testresizable{


public static void main(String[] args) {

Rectangle rectangle=new Rectangle(5,10);


[Link]("Orignal display");
[Link]();
[Link](8);
[Link](12);
[Link]("Resize rectangle");
[Link]();
}
}

14
OUTPUT:
Orignal display
Rectangle width:5,height10
Resize rectangle
Rectangle width:8,height12
BUILD SUCCESSFUL (total time: 0 seconds)

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

package nestedclass;
class Outer
{
void display()
{
[Link]("outer class display method");
}
class Inner
{
void display()
{
[Link]("Inner classs display method");
}
}
}
public class NestedClass {
public static void main(String[] args) {
// TODO code application logic here
Outer obj1=new Outer();
[Link]();
[Link] obj2=[Link] Inner();
[Link]();
}

OUTPUT:
run:
outer class display method
Inner classs display method
BUILD SUCCESSFUL (total time: 0 seconds)

16
9. Develop a JAVA program to raise a custom exception (user defined
exception) for Division By Zero using try, catch, throw and finally.

package exception_divbyzero;
class DivisionByZeroException extends Exception{

public DivisionByZeroException(String message){

super(message);

}
}

public class Exception_DivByZero {

public static void main(String[] args) {

int numerator=10;
int denominator=0;
try{
if(denominator==0){

throw new
DivisionByZeroException("divison by zero is not allowed");
}

int remainder=10%0;
[Link]("result of modulus :"+remainder);
int result=numerator/denominator;
[Link]("result of divison :"+result);
}
catch(DivisionByZeroException e){
[Link]("Error :"+[Link]());
}
catch(ArithmeticException e){
[Link]("Error :Dvision by zero occured");
}

finally{
[Link]("Finally block executed");
}

}
}

OUTPUT:

Denominator is 0:
run:
Error :divison by zero is not allowed

17
Finally block executed
BUILD SUCCESSFUL (total time: 0 seconds)

Denominator is 1:
run:
Error :divison by zero occurred.
Finally block executed
BUILD SUCCESSFUL (total time: 0 seconds)

int reminder=10%1

run:
result of modulus :0
result of divison :10
Finally block executed
BUILD SUCCESSFUL (total time: 0 seconds)

18
10. Develop a JAVA program to create a package named my pack and import &
implement it in a suitable class.

[Link]:

import [Link];

public class Mainclass {


public static void main(String[] args)
{
MyPackageClassmyPackageObject=new MyPackageClass();
[Link]();
}

[Link]:

package mypack;

public class MyPackageClass {


public void displayMessage(){
[Link]("THis message isn sent from the myPackageClass inside the mypack package");
}

OUTPUT:
THis message isn sent from the myPackageClass inside the mypack package
BUILD SUCCESSFUL (total time: 0 seconds)

19
[Link] 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).

package mainthreads_1;

class MyRunnable implements Runnable{


@Override
public void run(){
try{
[Link](500);
[Link]("Thread"+[Link]().getId()+"running");
}catch(InterruptedException e){
[Link]();

}
}
}
public class MainThreads_1 {

public static void main(String[] args) {


MyRunnablemyRunnable=new MyRunnable();
Thread thread1=new Thread(myRunnable);
Thread thread2=new Thread(myRunnable);
Thread thread3=new Thread(myRunnable);

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

OUTPUT:

Thread9running
Thread8running
Thread10running
BUILD SUCCESSFUL (total time: 0 seconds)

20
[Link] 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{


public MyThread(String name){
super(name);
start();
}
public void run(){
for(int i=0;i<=5;i++) {
[Link]("Child Thread:"+i);
try{
[Link](500);
}catch(InterruptedException e){
[Link]("Child Thread is interrupted");
}
}
}
}
public class MainThread {

public static void main(String[] args) {


MyThreadmyThread = new MyThread("Child Thread");
for(int i=0;i<=5;i++){
[Link]("Main Thread:"+i);
try{
[Link](500);
}catch(InterruptedException e) {
[Link]("Main Thread is interrupted");
}

}}
}

OUTPUT:

run:
Main Thread:0
Child Thread:0
Main Thread:1
Child Thread:1
Main Thread:2
Child Thread:2
Main Thread:3
Child Thread:3
Main Thread:4
Child Thread:4
Main Thread:5
Child Thread:5
BUILD SUCCESSFUL (total time: 3 seconds)

21

You might also like