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

Java Lab Programs

Uploaded by

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

Java Lab Programs

Uploaded by

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

BMS INSTITUTE OF TECHNOLOGY AND

MANAGEMENT YELAHANKA BANGALORE - 560064


Department of Computer Science and Engineering

Java Programs: 3rd SEM


1. Write a java program to implement linear search.
Import java.util.Scanner;

public class LinearSearch {


// Function to perform linear search
public static int linearSearch(int[] arr, int key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) {
return i; // Return the index where the key is found
}
}
return -1; // Return -1 if key is not found
}

public static void main(String[] args) {


Scanner = new Scanner(System.in);

// Input the size of the array


System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

// Input the elements of the array


int[] array = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}

// Input the element to search


System.out.print("Enter the element to search: ");
int key = scanner.nextInt();

scanner.close();

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

// Call linearSearch function to find the index of key


int result = linearSearch(array, key);

if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found in the array.");
}
}
}

Output:
Enter the size of the array: 5
Enter the elements of the array:
10
20
30
40
50
Enter the element to search: 30
Element found at index: 2

2. Write a java program to implement binary search .


import java.util.Scanner;

public class BinarySearch {


// Function to perform binary search
public static int binarySearch(int[] arr, int key) {
int low = 0;
int high = arr.length - 1;

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

while (low <= high) {


int mid = low + (high - low) / 2;

if (arr[mid] == key) {
return mid; // Return the index where the key is found
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // Return -1 if key is not found
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input the size of the array


System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

// Input the elements of the array


int[] array = new int[size];
System.out.println("Enter the elements of the array in sorted
order:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}

// Sort the array (Binary search requires sorted array)


Arrays.sort(array);

// Input the element to search


System.out.print("Enter the element to search: ");

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

int key = scanner.nextInt();

scanner.close();

// Call binarySearch function to find the index of key


int result = binarySearch(array, key);

if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found in the array.");
}
}
}

Output:
Enter the size of the array: 6
Enter the elements of the array in sorted order:
10
20
30
40
50
60
Enter the element to search: 40
Element found at index: 3

3. 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 (args.length != 1) {

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

System.out.println("Usage: java MatrixAddition <order>");


System.exit(1);
}

int order = Integer.parseInt(args[0]);

int[][] matrix1 = generateRandomMatrix(order);


int[][] matrix2 = generateRandomMatrix(order);

System.out.println("Matrix 1:");
printMatrix(matrix1);

System.out.println("Matrix 2:");
printMatrix(matrix2);

int[][] resultMatrix = addMatrices(matrix1, matrix2);

System.out.println("Result Matrix:");
printMatrix(resultMatrix);
}

// Generates a random matrix of given order


private static int[][] generateRandomMatrix(int order) {
int[][] matrix = new int[order][order];

for (int i = 0; i < order; i++) {


for (int j = 0; j < order; j++) {
matrix[i][j] = (int) (Math.random() * 10); // Generate random
numbers between 0 and 9
}
}

return matrix;
}

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

// Adds two matrices


private static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
int order = matrix1.length;
int[][] resultMatrix = new int[order][order];

for (int i = 0; i < order; i++) {


for (int j = 0; j < order; j++) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

return resultMatrix;
}

// Prints a matrix
private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
System.out.println();
}
}

Output:
Matrix 1:
780
114
598

Matrix 2:

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

321
560
469

Result Matrix:
10 10 1
674
9 15 17

4. Multiplication of 2 matrices
import java.util.Scanner;

public class MatrixMultiplication {


public static void main(String[] args) {
Scanner = new Scanner(System.in);

// Input dimensions for the first matrix


System.out.print("Enter the number of rows for the first matrix: ");
int rows1 = scanner.nextInt();
System.out.print("Enter the number of columns for the first matrix:
");
int cols1 = scanner.nextInt();

// Input dimensions for the second matrix


System.out.print("Enter the number of rows for the second matrix:
");
int rows2 = scanner.nextInt();
System.out.print("Enter the number of columns for the second
matrix: ");
int cols2 = scanner.nextInt();

// Check if multiplication is possible


if (cols1 != rows2) {

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

System.out.println("Matrix multiplication not possible. Columns of


the first matrix must be equal to rows of the second matrix.");
return;
}

// Input elements for the first matrix


System.out.println("Enter the elements of the first matrix:");
int[][] matrix1 = inputMatrix(scanner, rows1, cols1);

// Input elements for the second matrix


System.out.println("Enter the elements of the second matrix:");
int[][] matrix2 = inputMatrix(scanner, rows2, cols2);

// Perform matrix multiplication


int[][] resultMatrix = multiplyMatrices(matrix1, matrix2);

// Display the result


System.out.println("Resultant matrix after multiplication:");
displayMatrix(resultMatrix);

scanner.close();
}

// Function to input elements of a matrix


public static int[][] inputMatrix(Scanner, int rows, int cols) {
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}
return matrix;
}

// Function to multiply two matrices


public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {
int rows1 = matrix1.length;

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

int cols1 = matrix1[0].length;


int cols2 = matrix2[0].length;

int[][] resultMatrix = new int[rows1][cols2];

for (int i = 0; i < rows1; i++) {


for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

return resultMatrix;
}

// Function to display a matrix


public static void displayMatrix(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Output:
Enter the number of rows for the first matrix: 2
Enter the number of columns for the first matrix: 2
Enter the number of rows for the second matrix: 2

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

Enter the number of columns for the second matrix: 2


Enter the elements of the first matrix:
12
34
Enter the elements of the second matrix:
56
78
Resultant matrix after multiplication:
19 22
43 50

5. Stack Program
import java.util.*;

public class StackExample {


private static final int MAX_SIZE = 10;
private int[] stackArray;
private int top;

public StackExample() {
stackArray = new int[MAX_SIZE];
top = -1;
}

// Function to push an element onto the stack


public void push(int item) {
if (top == MAX_SIZE - 1) {
System.out.println("Stack Overflow! Cannot push element onto
stack.");
return;
}
stackArray[++top] = item;
System.out.println("Pushed " + item + " onto the stack.");
}

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

// Function to pop an element from the stack


public int pop() {
if (top == -1) {
System.out.println("Stack Underflow! Stack is empty.");
return -1;
}
int poppedItem = stackArray[top--];
System.out.println("Popped " + poppedItem + " from the stack.");
return poppedItem;
}

// Function to display the elements of the stack


public void display() {
if (top == -1) {
System.out.println("Stack is empty.");
return;
}
System.out.println("Elements of the stack:");
for (int i = top; i >= 0; i--) {
System.out.println(stackArray[i]);
}
}

public static void main(String[] args) {


Scanner = new Scanner(System.in);
StackExample stack = new StackExample();

while(true) {
System.out.println("\nStack Operations:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
System.out.print("Enter your choice: ");
int ch = scanner.nextInt();

switch (ch) {

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

case 1:
System.out.print("Enter the element to push: ");
int element = scanner.nextInt();
stack.push(element);
break;
case 2:
stack.pop();
break;
case 3:
stack.display();
break;
default:
System.out.println("Invalid choice!");
}
}
}
}

Output:
Stack Operations:
1. Push
2. Pop
3. Display
Enter your choice: 1
Enter the element to push: 10
Pushed 10 onto the stack.
Do you want to continue (y/n)? y

Stack Operations:
1. Push

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

2. Pop
3. Display

Enter your choice: 1


Enter the element to push: 20
Pushed 20 onto the stack.

Stack Operations:
1. Push
2. Pop
3. Display
Enter your choice: 3
Elements of the stack:
20
10

Stack Operations:
1. Push
2. Pop
3. Display
Enter your choice: 2
Popped 20 from the stack.

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

Stack Operations:
1. Push
2. Pop
3. Display
Enter your choice: 3
Elements of the stack:
10

6. Method Overloading Program

public class MethodOverloadingDemo {

// Method to sum two integers


public static void sum(int a, int b) {
int result = a + b;
System.out.println("Sum of integers: " + result);
}

// Method to sum an integer and a float


public static void sum(int a, float b) {
float result = a + b;
System.out.println("Sum of integer and float: " + result);
}

// Method to sum three floats

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

public static void sum(float a, float b, float c) {


float result = a + b + c;
System.out.println("Sum of three floats: " + result);
}

public static void main(String[] args) {


sum(5, 10);
sum(7, 3.5f);
sum(2.5f, 3.5f, 4.5f);
}
}

Output:
Sum of integers: 15
Sum of integer and float: 10.5
Sum of three floats: 10.5

7. Create a class called “Shape”. Write a method “draw”. Define colour as


a variable. Initialize the colour through read method. Create a child
class called “Rectangle”. Write 2 methods read() and display().
(Inheritance Program)
import java.util.Scanner;

class Shape {
protected String color;

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

public void draw() {


System.out.println("Drawing shape with color: " + color);
}

public void readColor() {


Scanner = new Scanner(System.in);
System.out.print("Enter color: ");
color = scanner.nextLine();
}
}

class Rectangle extends Shape {


private int length;
private int width;

public void read() {


Scanner = new Scanner(System.in);
System.out.print("Enter length: ");
length = scanner.nextInt();
System.out.print("Enter width: ");
width = scanner.nextInt();
readColor();
}

public void display() {


System.out.println("Rectangle - Length: " + length + ", Width: " +
width + ", Color: " + color);
}
}

public class Main {


public static void main(String[] args) {
Rectangle = new Rectangle();
rectangle.read();

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

rectangle.draw();
rectangle.display();
}
}

Output:
Enter length: 5
Enter width: 3
Enter color: Blue
Drawing shape with color: Blue
Rectangle - Length: 5, Width: 3, Color: Blue

8. Develop a JAVA program to create an abstract class Shape with


abstract methods calculate Area() and calculate Perimeter().
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 {
double radius;

public Circle(double radius) {


this.radius = radius;
}

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

@Override
double calculatePerimeter() {

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

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;
}
}
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;
// PLEASE TAKE INPUTS THROUGH SCANNER CLASS AS AN ALTERNATIVE

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

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

}
}
Radius of the Circle4.0
Area of the Circle: 50.26548245743669
Perimeter of the Circle: 25.132741228718345

Sides of the Traiangel are: 3.0,4.0,5.0


Area of the Triangle: 6.0
Perimeter of the Triangle: 12.0

9. Write a java program to show exception handling(division by 0)


import java.util.Scanner;

public class DivisionByZero {


public static void main(String[] args) {
Scanner = new Scanner(System.in);

System.out.print("Enter numerator: ");


int numerator = scanner.nextInt();

System.out.print("Enter denominator: ");


int denominator = scanner.nextInt();

try {
int result = numerator / denominator;
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed!");
}

scanner.close();//not required
}
}

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

Output:
Enter numerator: 10
Enter denominator: 2
Result of division: 5

Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed!

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

@Override
public void resizeWidth(int width) {
this.width = width;
System.out.println("Resized width to: " + width);
}

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

@Override
public void resizeHeight(int height) {
this.height = height;
System.out.println("Resized height to: " + height);
}

public void display() {


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

public class Main {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 10);

System.out.println("Original Rectangle:");
rectangle.display();

// Resizing the rectangle


rectangle.resizeWidth(8);
rectangle.resizeHeight(15);

System.out.println("Resized Rectangle:");
rectangle.display();
}
}

Output
Original Rectangle:
Rectangle - Width: 5, Height: 10
Resized width to: 8

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

Resized height to: 15


Resized Rectangle:
Rectangle - Width: 8, Height: 15

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 mythread1 implements Runnable
{
public void run() {
for(int i = 1;i<5;i++) {
System.out.println(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class mythread2 implements Runnable
{
public void run() {
for(int i = 10;i<15;i++) {
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

// TODO Auto-generated catch block


e.printStackTrace();
}
}
}
}
public class f2 {
public static void main(String[] args) {
mythread1 mt1 = new mythread1();
Thread t1 = new Thread(mt1);
t1.start();
mythread2 mt2 = new mythread2();
Thread t2 = new Thread(mt2);
t2.start();
}
}

Output:
1
10
2
3
4
11
12
13
14

12. Develop a program to create a class My Thread 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 the main
thread and the created child thread are executed concurrently

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

class MyThread extends Thread


{
MyThread()
{
super ("Using Thread class");
System.out.println ("Child thread:" + this);
start();
}
public void run()
{
try
{
for ( int i =5; i > 0; i--)
{
System.out.println ("Child thread" + i);
Thread.sleep (500);
}
}
catch (InterruptedException e) {
// Do nothing
}
System.out.println ("exiting child thread …");
}
}
public class f1 {
public static void main(String[] args) {
MyThread mt = new MyThread();
try {
for ( int k = 5; k < 0; k--)
{
System.out.println ("Running main thread :" + k);
Thread.sleep(1000);
}
}catch (InterruptedException e) { }
System.out.println ("Exiting main thread . . .");
}

Dr. Srivani P Dept of CSE 2023-24


BMS INSTITUTE OF TECHNOLOGY AND
MANAGEMENT YELAHANKA BANGALORE - 560064
Department of Computer Science and Engineering

Output:
Child thread:Thread[#21,Using Thread
class,5,main]
Exiting main thread . . .
Child thread5
Child thread4
Child thread3
Child thread2
Child thread1
exiting child thread …

Dr. Srivani P Dept of CSE 2023-24

You might also like