Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Java Lab(Bcs306a) 4

Uploaded by

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

Java Lab(Bcs306a) 4

Uploaded by

anushreenaik2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

EXPERIMENT 1

Aim: Develop a JAVA program to add TWO matrices of suitable order N (The value of N should
be read from command line arguments).
Program:
import java.util.Scanner;
public class AddMatrix
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0
Scanner s = new Scanner(System.in);
int a[][]=new int[n][n];
int b[][]=new int[n][n];
int c[][]=new int[n][n];

System.out.println("Enter the elements of First Matrix :");


for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
a[i][j]=s.nextInt();
}
System.out.println("Enter the elements of Second Matrix :");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
b[i][j]=s.nextInt();
}

for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
}
System.out.println("The Matrix after addition :");

for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(c[i][j] + " ");
System.out.println("");
}
}
}
Output:
PS D:\JAVA BCS306A\lab1> javac Example.java
PS D:\JAVA BCS306A\lab1> java Example 3
Enter the elements of First Matrix :
243
540
132
Enter the elements of Second Matrix :
420
156
217
The Matrix after addition :
6 6 3
6 9 6
3 4 9
EXPERIMENT 2
Aim: Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop
a JAVA main method to illustrate Stack operations.
Program:
import java.io.*;
import java.util.*;
import java.util.Scanner;
class P2_Stack{
int stack[];
int tos,sos;
P2_Stack(int size)
{
stack = new int[size];
sos=size;
tos = -1;
}
public void Push(int x)
{
if (isFull())
{
System.out.println("Stack OverFlow");
System.exit(1);
}
stack[++tos] = x;
}
public int Pop()
{
if (isEmpty())
{
System.out.println("Stack Empty");
System.exit(1);
}
return stack[tos--];
}
public int getSize() {
return tos + 1;
}
public Boolean isEmpty() {
return tos == -1;
}
public Boolean isFull() {
return tos == sos-1;
}

public void printStack()


{
for (int i = 0; i <= tos; i++)
System.out.print(stack[i] + " ");
}
public static void main(String[] args)
{
int no,size,choice;
Scanner sc = new Scanner(System.in);
System.out.print ("Enter the size of the Stack : ");
size=sc.nextInt();
P2_Stack s = new P2_Stack(size);
while (true)
{
System.out.print("\nEnter you Choice : 1 : Push \t 2: Pop \t 0: Exit -> ");
choice=sc.nextInt();
switch(choice)
{
case 1:
System.out.print("Enter the Element : ");
no=sc.nextInt();
s.Push(no);
System.out.print("After Push : Stack Elements are: ");
s.printStack();
break;
case 2:
s.Pop();
System.out.print("After Pop : Stack Elements are: ");
s.printStack();
break;
case 0:
System.exit(1);
}
}
}
}

Output:
Enter the size of the Stack : 3

Enter you Choice : 1 : Push 2: Pop 0: Exit -> 1


Enter the Element : 5
After Push : Stack Elements are: 5
Enter you Choice : 1 : Push 2: Pop 0: Exit -> 1
Enter the Element : 8
After Push : Stack Elements are: 5 8
Enter you Choice : 1 : Push 2: Pop 0: Exit -> 1
Enter the Element : 3
After Push : Stack Elements are: 5 8 3
Enter you Choice : 1 : Push 2: Pop 0: Exit -> 2
After Pop : Stack Elements are: 5 8
Enter you Choice : 1 : Push 2: Pop 0: Exit -> 1
Enter the Element : 4
After Push : Stack Elements are: 5 8 4
Enter you Choice : 1 : Push 2: Pop 0: Exit -> 1
Enter the Element : 2
Stack OverFlow
EXPERIMENT 3
Aim: 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.
Program:
import java.util.Scanner;
class Employee {
long EmpId;
String EmpName;
double EmpSalary;

void raiseSalary(double percent) {


EmpSalary += EmpSalary * percent / 100;
}
public static void main(String[] args) {
Employee e = new Employee();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Employee Name: ");
e.EmpName = sc.next();
System.out.print("Enter Employee Id: ");
e.EmpId = sc.nextLong();
System.out.print("Enter Employee Salary: ");
e.EmpSalary = sc.nextDouble();
System.out.print("Enter the percentage to raise Salary: ");
double percent = sc.nextDouble();
e.raiseSalary(percent);
System.out.println("\nEmployee Details After Salary Increment:");
System.out.println("Employee Name: " + e.EmpName);
System.out.println("Employee Id: " + e.EmpId);
System.out.println("Employee Salary: " + e.EmpSalary);
sc.close();
}
}
Output:
PS D:\JAVA BCS306A\lab1> javac Employee.java
PS D:\JAVA BCS306A\lab1> java Employee
Enter Employee Name: Dinga
Enter Employee Id: 123
Enter Employee Salary: 10000
Enter the percentage to raise Salary: 20

Employee Details After Salary Increment:


Employee Name: Dinga
Employee Id: 123
Employee Salary: 12000.0
EXPERIMENT 4
Aim: 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)
Program:
import java.util.Scanner;
class MyPoint {
private int x, y;
MyPoint() {
this.x = 0;
this.y = 0;
}
MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
void setXY() {
Scanner s = new Scanner(System.in);
x = s.nextInt();
y = s.nextInt();
}
int[] getXY() {
int[] coordinates={x,y};
return coordinates;
}
public String toString() {
return "(" + x + "," + y + ")";
}
double distance(int x, int y) {
int diffx=this.x-x;
int diffy=this.y-y;
return(Math.sqrt(diffx*diffx+diffy*diffy));
}
double distance(MyPoint another) {
return distance(another.x, another.y);
}
double distance() {
return distance(0,0);
}
}
class P4_TestMyPoint {
public static void main(String[] args) {
MyPoint point1 = new MyPoint();
MyPoint point2 = new MyPoint(1, 2);
System.out.print("Enter the coordinates for point1 :");
point1.setXY();
System.out.println("Point1: "+point1.toString());
System.out.println("Point2: "+point2.getXY()[0]+","+point2.getXY()[1]);
System.out.println("Distance between point1 and point2
is:"+point1.distance(point2));
System.out.println("Distance between point1 and Origin(0,0)
is:"+point1.distance());
}
}

Output:
PS D:\JAVA BCS306A\lab1> javac P4_TestMyPoint.java
PS D:\JAVA BCS306A\lab1> java P4_TestMyPoint
Enter the coordinates for point1 :2 3
Point1: (2,3)
Point2: 1,2
Distance between point1 and point2 is:1.4142135623730951
Distance between point1 and Origin(0,0) is:3.605551275463989
EXPERIMENT 5
Aim: 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.
Program:
class Shape {
void drawShape() {
System.out.println("Drawing a Shape.");
}
void eraseShape() {
System.out.println("Erasing a Shape.");
}
}
class Circle extends Shape {
void drawShape() {
System.out.println("Drawing a Circle.");
}
void eraseShape() {
System.out.println("Erasing a Circle.");
}
}
class Triangle extends Shape {
void drawShape() {
System.out.println("Drawing a Triangle.");
}
void eraseShape() {
System.out.println("Erasing a Triangle.");
}
}
class Square extends Shape {
void drawShape() {
System.out.println("Drawing a Square.");
}
void eraseShape() {
System.out.println("Erasing a Square.");
}
}
class P5_Shape {
public static void main(String[] args) {
Shape c = new Circle();
Shape t = new Triangle();
Shape s = new Square();
c.drawShape();
c.eraseShape();
t.drawShape();
t.eraseShape();
s.drawShape();
s.eraseShape();
}
}

Output:
Drawing a Circle.
Erasing a Circle.
Drawing a Triangle.
Erasing a Triangle.
Drawing a Square.
Erasing a Square.
EXPERIMENT 6
Aim: 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.
Program:
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}

class Circle extends Shape {


double radius;
Circle() {
}
Circle(double r) {
radius = r;
}
double calculateArea() {
return (Math.PI * Math.pow(radius, 2));
}
double calculatePerimeter() {
return (2 * Math.PI * radius);
}
}

class Triangle extends Shape {


double sa, sb, sc;
Triangle() {
}
Triangle(double a, double b, double c) {
sa = a;
sb = b;
sc = c;
}
double calculateArea() {
double s;
s = (sa + sb + sc) / 2.0;
return (Math.sqrt(s * (s - sa) * (s - sb) * (s - sc)));
}
double calculatePerimeter() {
return (sa + sb + sc);
}
}
class P6_Shape {
public static void main(String[] args) {
Shape c = new Circle(10.0);
Shape t = new Triangle(3.5, 4.5, 5.6);
System.out.println("Area of the Circle \t\t:\t" + c.calculateArea());
System.out.println("Perimeter of the Circle \t:\t" + c.calculatePerimeter());
System.out.println("Area of the Triangle \t\t: \t" + t.calculateArea());
System.out.println("Perimeter of the Triangle \t:\t" + t.calculatePerimeter());
}
}

Output:
PS D:\JAVA BCS306A\lab1> javac P6_Shape.java
PS D:\JAVA BCS306A\lab1> java P6_Shape
Area of the Circle : 314.1592653589793
Perimeter of the Circle : 62.83185307179586
Area of the Triangle : 7.869841167393405
Perimeter of the Triangle : 13.6
EXPERIMENT 7
Aim: 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.
Program:
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

class Rectangle implements Resizable {


int width;
int height;

Rectangle(int w, int h) {
this.width = w;
this.height = h;
}

public void resizeWidth(int w) {


if (w > 0)
this.width = w;
else
System.out.println("Width must be a Positive value. Cannot resize the width");
}

public void resizeHeight(int h) {


if (h > 0)
this.height = h;
else
System.out.println("Height must be a Positive value. Cannot resize the height");
}

void displayRectangle() {
System.out.println("Width : " + this.width + "\t" + "Height : " + this.height);
}
}

public class P7_Interface {


public static void main(String[] args) {
Rectangle r = new Rectangle(8, 6);
System.out.print("Original dimension of the Rectangle\t\t: ");
r.displayRectangle();
r.resizeWidth(10);
r.resizeHeight(8);
System.out.print("New dimension of the Rectangle (after resize)\t: ");
r.displayRectangle();
}
}

Output:
PS D:\JAVA BCS306A\lab1> javac P7_Interface.java
PS D:\JAVA BCS306A\lab1> java P7_Interface
Original dimension of the Rectanlge : Width : 8 Height : 6
New dimension of the Rectanlge (after resize) : Width : 10 Height : 8
EXPERIMENT 8
Aim: 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.
Program:
class Outer {
void funcDisplay() {
System.out.println("Outer Class -> funcDisplay() invoked");
}

class Inner {
void funcDisplay() {
System.out.println("Inner Class -> funcDisplay() invoked");
}
}
}

class P8_OuterInnerClass {
public static void main(String[] args) {
Outer out = new Outer();
out.funcDisplay();
Outer.Inner oi = out.new Inner();
oi.funcDisplay();
}
}

Output:
PS D:\JAVA BCS306A\lab1> javac P8_OuterInnerClass.java
PS D:\JAVA BCS306A\lab1> java P8_OuterInnerClass
Outer Class -> funcDisplay() invoked
Inner Class -> funcDisplay() invoked
EXPERIMENT 9
Aim: Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
Program:
import java.util.Scanner;
class DivisionByZeroException extends Exception {
DivisionByZeroException(String msg) {
super(msg);
}
}

public class P9_Exception {


public static void main(String[] args) {
int fNo, sNo;
double res;
Scanner s = new Scanner(System.in);
System.out.print("Enter the Numerator and Denominator : ");
fNo = s.nextInt();
sNo = s.nextInt();
try {
if (sNo == 0)
throw new DivisionByZeroException(
"Arithmetic Exception (Division By Zero) - Cannot Divide a Number by Zero.");
else {
res = fNo / sNo;
System.out.println(fNo + " / " + sNo + " = " + res);
}
} catch (DivisionByZeroException e) {
System.out.println("Error : " + e.getMessage());
} finally {
System.out.println("Executing the Finally Block...");
}
}
}

Output:
PS D:\JAVA BCS306A\lab expeiments> javac P9_Exception.java
PS D:\JAVA BCS306A\lab expeiments> java P9_Exception
Enter the Numerator and Denominator : 5 3
5 / 3 = 1.0
Executing the Finally Block...
PS D:\JAVA BCS306A\lab expeiments> java P9_Exception
Enter the Numerator and Denominator : 5 0
Error : Arithmetic Exception (Division By Zero) - Cannot Divide a Number by Zero.
Executing the Finally Block...
EXPERIMENT 10
Aim: Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
Program:
// Inside a folder named 'mypack'
package mypack;

public class MyPackageClass {


public void displayMessage() {
System.out.println("Hello from MyPackageClass in mypack package!");
}

public static int addNumbers(int a, int b) {


return a + b;
}
}

/Create the main program in a different file outside the mypack folder:
// Main program outside the mypack folder
import mypack.MyPackageClass;

public class PackageDemo {


public static void main(String[] args) {
MyPackageClass myPackageObject = new MyPackageClass();
myPackageObject.displayMessage();
int result = MyPackageClass.addNumbers(5, 3);
System.out.println("Result of adding numbers: " + result);
}
}

Output:
PS D:\JAVA BCS306A\lab expeiments> javac PackageDemo.java
PS D:\JAVA BCS306A\lab expeiments> java PackageDemo
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8
EXPERIMENT 11
Aim: 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).
Program:
class RunnableThread implements Runnable {
RunnableThread(String tn) {
Thread.currentThread().setName(tn);
}

public void start() {


run();
}

public void run() {


try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " Created and is Running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

class P11_Thread_Runnable {
public static void main(String args[]) {
RunnableThread rt1 = new RunnableThread("T1");
rt1.start();
RunnableThread rt2 = new RunnableThread("T2");
rt2.start();
RunnableThread rt3 = new RunnableThread("T3");
rt3.start();
}
}

Output:
PS D:\JAVA BCS306A\lab1> javac P11_Thread_Runnable.java
PS D:\JAVA BCS306A\lab1> java P11_Thread_Runnable
T1 Created and is Running
T2 Created and is Running
T3 Created and is Running
EXPERIMENT 12
Aim: 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.
Program:
class myThread extends Thread {
myThread(String tname) {
super(tname);
}

public void run() {


System.out.println(this.getName() + " Started...");
try {
System.out.println(this.getName() + " Continues...");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName() + " Completed.");
}
}
public class P12_Thread {
public static void main(String args[]) {
System.out.println("Main Thread Started.");
myThread mt = new myThread("Child-Thread");
mt.start();
System.out.println("Main Thread Continues...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main Thread Completed.");
}
}

Output:
PS D:\JAVA BCS306A\lab1> javac P12_Thread.java
PS D:\JAVA BCS306A\lab1> java P12_Thread
Main Thread Started.
Main Thread Continues...
Child-Thread Started...
Child-Thread Continues...
Main Thread Completed.
Child-Thread Completed.

You might also like