0% found this document useful (0 votes)
47 views52 pages

OOPS LAB Manual 2024 (2) - IT

Oops lab manual all the correct

Uploaded by

summarsura
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)
47 views52 pages

OOPS LAB Manual 2024 (2) - IT

Oops lab manual all the correct

Uploaded by

summarsura
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/ 52

NATTRAMPALLI – 635 854

(Approved by AICTE New Delhi and Affiliated to Anna University)

NAME : --------------------------------------

REGISTER NUMBER :

SUBJECT NAME /CODE : ----------------------------------------

YEAR/SEM : ------------------------------------------------
NATTRAMPALLI – 635 854
(Approved by AICTE New Delhi and Affiliated to Anna University)

DEPARTMENT OF INFORMATION TECHNOLOGY

BONAFIDE CERTIFICATE

Certified that this is a Bonafide record of the practical work done by ______ 3rd Semester

Computer Science Engineering in CS3381-Object-Oriented Programming Lab during the period

NOV/ DEC 2024

Staff In-Charge Head of the Department

University Register Number:

Submitted for the Practical examination held on………......…………….at Bharathidasan Engineering


College, Nattrampalli.

Internal Examiner External Examiner


Ex. Page Staff
Date Name of the Experiment No.
No Signature
Ex. Page Staff
Date Name of the Experiment No.
No Signature
Ex. Page Staff
Date Name of the Experiment No.
No Signature
1A: TO DEVELOP A JAVA PROGRAM TO SOLVE THE
PROBLEM FOR SEQUENTIAL SEARCH

Program:

public class LinearSearchExample{


public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i; } }
return -1; }
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
} }

Output:
50 is found at index: 3
1B: TO DEVELOP A JAVA PROGRAM TO SOLVE PROBLEM FOR BINARY
SEARCH

Program:

class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}
Output:

F:\>javac BinarySearchExample.java
F:\>java BinarySearchExample
Element is found at index: 2
1C: TO DEVELOP A JAVA PROGRAM TO SOLVE PROBLEMS FOR SELECTION SORT

Program:

public class SelectionSortExample { public


static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j= i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}

public static void main(String a[]){

int[] arr1 = {9,14,3,2,43,11,58,22};


System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();

selectionSort(arr1);//sorting array using selection sort


System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}

Output:

Before Selection Sort


9 14 3 2 43 11 58 22
After Selection Sort
2 3 9 11 14 22 43 58
1D: TO DEVELOP A JAVA PROGRAM TO SOLVE PROBLEM FOR INSERTION SORT

Program:

public class InsertionSortExample {


public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) { int key = array[j]; int i= j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i]; i--; }
array[i+1] = key; } }
public static void main(String a[]){
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Insertion Sort");
for(int i:arr1){
System.out.print(i+" "); }
System.out.println();
insertionSort(arr1);//sorting arrayusing insertion sort
System.out.println("After Insertion Sort");
for(int i:arr1){
System.out.print(i+" "); } } }

Output:

Before Insertion Sort


9 14 3 2 43 11 58 22
After Insertion Sort
2 3 9 11 14 22 43 58
2A: TO DEVELOP A JAVA PROGRAM TO SOLVE STACK DATA STRUCTURES
USING CLASSES AND OBJECTS

Program:

import java.util.*;
public class StackPushPopExample
{
public static void main(String args[])
{
//creating an object of Stack class
Stack <Integer> stk = new Stack<>();
System.out.println("stack: " + stk);
//pushing elements into the stack
pushelmnt(stk, 20);
pushelmnt(stk, 13);
pushelmnt(stk, 89);

pushelmnt(stk, 90);
pushelmnt(stk, 11);
pushelmnt(stk, 45);
pushelmnt(stk, 18);
//popping elements from the stack
popelmnt(stk);
popelmnt(stk);
//throws exception if the stack is empty
try
{
popelmnt(stk);
}
catch (EmptyStackException e)
{
System.out.println("empty stack");
}
}
//performing push operation
static void pushelmnt(Stack stk, int x)
{
//invoking push() method
stk.push(new Integer(x));
System.out.println("push -> " + x);
//prints modified stack
System.out.println("stack: " + stk);
}
//performing pop operation
static void popelmnt(Stack stk)
{
System.out.print("pop -> ");
//invoking pop() method

Integer x = (Integer) stk.pop();


System.out.println(x);
//prints modified stack
System.out.println("stack: " + stk);
}
}
Output:
F:\>java StackPushPopExample
stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11
stack: [20, 13, 89, 90, 11]
push -> 45
stack: [20, 13, 89, 90, 11, 45]
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
stack: [20, 13, 89, 90, 11, 45]
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]
2B: TO DEVELOP A JAVA PROGRM TO SOLVE QUEUE DATA STRUCTURES USING
CLASSES AND OBJECTS

Program:

/* Implementation of the queue using a fixed-length array. */


public class Queue {
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;
Queue() {
front = -1;
rear = -1;
}
boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}
boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}
void enQueue(int element) {
if (isFull()) {
System.out.println("\nThe queue is full");
}
else {
if (front == -1) {
front = 0;
}
rear++;

items[rear] = element;
System.out.println("\nThe element " + element + " is inserted");
}
}
int deQueue() {
int element;
if (isEmpty()) {
System.out.println("\nThe queue is empty");
return (-1);
}
else {
element = items[front];
if (front >= rear) {
front = -1;
rear = -1;
}
else {
front++;
}
System.out.println("\nThe element " +element + " is deleted");
return (element);
}
}
void display() {
int i;
if (isEmpty()) {
System.out.println("The queue is empty");
}
else {
System.out.println("\nThe elements of the queue are: ");
for (i = front; i <= rear; i++)

System.out.print(items[i] + " ");


}
}
public static void main(String[] args) {
Queue input_queue = new Queue();
for(int i = 1; i < 6; i ++) {
input_queue.enQueue(i * 100);
}
System.out.println("The queue is defined as: " + input_queue);
input_queue.enQueue(6);
input_queue.display();
input_queue.deQueue();
input_queue.display();
}
}
Output:
F:\>java Queue

The element 100 is inserted

The element 200 is inserted

The element 300 is inserted

The element 400 is inserted

The element 500 is inserted


The queue is defined as: Queue@72ea2f77

The queue is full

The elements of the queue are:


100 200 300 400 500
The element 100 is deleted

The elements of the queue are:


200 300 400 500
3: TO DEVELOP A JAVA APPLICATION WITH GENERATE AN EMPLOYEE PAY SLIP

Program:

import java.util.Scanner;
class Employee{
String Emp_name;
int Emp_id;
String Address;
String Mail_id;
int Mobile_no;
void display(){
System.out.println(Emp_name);
//Syetem.out.println(Address);
System.out.println(Emp_id);
System.out.println(Mail_id);
System.out.println(Mobile_no);
}
}
class Programmer extends Employee{
int BP;

/*int DA= (int) (0.97*BP);


HRA=(int) (0.10*BP);
PF=(int) (0.12*BP); */
void display(){
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);
}
}
class Assistant_Professor extends Employee{
int BP;

void display(){
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);

}
}
class Associate_Professor extends Employee{
int BP;

void display(){
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);

}
}
class Professor extends Employee{
int BP;

void display(){
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);

}
}
class Main{
public static void main(String args[]){
System.out.println("\n 1.Programmer\n2.Assistant_Professor\n3.Associate_Professor\n4.Professor");
Scanner input=new Scanner(System.in);
System.out.print("Enter an integer: ");
int ch=input.nextInt();
switch (ch) {
case 1:
Employee e1=new Employee();
Programmer p1=new Programmer();
e1.Emp_name="ABC";
e1.Address="y-city";
e1.Mail_id="[email protected]";
e1.Emp_id=567;
e1.Mobile_no=2345678;
p1.BP=15000;
p1.display();
e1.display();
break;
case 2:
Employee e2=new Employee();
Assistant_Professor p2=new Assistant_Professor();
e2.Emp_name="DEF";
e2.Address="A-city";
e2.Mail_id="[email protected]";
e2.Emp_id=123;
e2.Mobile_no=987321;
p2.BP=30000;
p2.display();
e2.display();
break;
case 3:
Employee e3=new Employee();
Associate_Professor p3=new Associate_Professor();
e3.Emp_name="GHF";
e3.Address="B-city";
e3.Mail_id="[email protected]";
e3.Emp_id=456;
e3.Mobile_no=98710;
p3.BP=30000;
p3.display();
e3.display();
break;
case 4:
Employee e4=new Employee();
Professor p4=new Professor();
e4.Emp_name="KANNAN";
e4.Address="TRICHY";
e4.Mail_id="[email protected]";
e4.Emp_id=789;
e4.Mobile_no=9810;
p4.BP=30000;
p4.display();
e4.display();
break;
case 5:
//exit(1);

default:
System.out.println("enter correct choice");

}
}
}

Output:

1. Programmer
2. Assistant_Professor
3. Associate_Professor
4. Professor
Enter an integer: 1
15000
DA14550.0
HRA1500.0
PF1800.0
STFF CLUD FUND15.0
ABC
567
[email protected]
2345678
4: TO WRITE A JAVE PROGRAM TO CREATE AN ABSTRACT CLASS NAMED SHAPE
THAT CONTAINS TWO INTEGERS AND AN EMPTY METHOD NAMED PRINT AREA( )

Program:

import java.util.*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.area(2,5);
Circle c=new Circle();
c.area(5,5);
Triangle t=new Triangle();
t.area(2,5);
}
}
Output :
F:\>java AbstactDDemo
Area of rectangle is :10.0
Area of circle is :78.5
Area of triangle is :5.0
5: TO DEVELOP A JAVA PROGRAM TO CREATE AN ABSTRACT CLASS USING INTERFACE

Program:
import java.util.*;
abstract class Shapes { double a,b; abstract void printArea(); }
class Rectangle extends Shapes {
void printArea()
{ System.out.println("\t\t Calculating Area of Rectangle");
Scanner input=new Scanner(System.in);
System.out.println("Enter length:");
a=input.nextDouble();
System.out.println("Enter breadth:");
b=input.nextDouble();
double area=a*b;
System.out.println("Area of Rectangle:"+area);
}}
class Triangle extends Shapes { void printArea()
{ System.out.println("\t \t Calculating Area of Triangle");
Scanner input=new Scanner(System.in);
System.out.println("Enter height:");
a=input.nextDouble();
System.out.print("Enter breath:");
b=input.nextDouble();
double area=0.5*a*b;
System.out.println("Area of Triangle:"+area); } }
class Circle extends Shapes {
void printArea()
{ System.out.println("\t \t Calculating Area of Circle");
Scanner input=new Scanner(System.in);
System.out.print("Enter radius:");
a=input.nextDouble();
double area=3.14*a*a;
System.out.println("Area of Circle:"+area); } }

class AbstractClassDemo
{ public static void main(String[] args)
{ Shapes obj;
obj=new Rectangle();
obj.printArea();
obj=new Triangle();
obj.printArea();
obj=new Circle();
obj.printArea();}}

Output:

Calculating Area of Rectangle Enter length:


3
Enter breadth:
5
Area of Rectangle:15.0
Calculating Area of Triangle

Enter height:
6
Enter breath:7
Area of Triangle:21.0

Calculating Area of Circle

Enter radius:7
Area of Circle:153.86
6: TO DEVELOP A JAVA PROGRAM TO IMPLEMENT USER DEFINED
EXCEPTION HANDLING

Program:
import java.lang.Exception;
class MyOwnException extends Exception
{MyOwnException(String msg)
{super(msg);}}
class MyExceptDemo {
public static void main(String ags[])
{ int age; age=15;
try { if(age<21)
throw new MyOwnException ("Your age is very less than the condition");}
catch(MyOwnException e)
{ System.out.println("This is My Exception block");
System.out.println(e.getMessage()); } finally { System.out.println("Finally block:End of the program");
}}}

Output:

F:\>java MyExceptDemo
This is My Exception block
Your age is very less than the condition
Finally block:End of the program
7: DEVELOP A JAVA PROGRAM THAT IMPLEMENTS A MULTI- THREADED APPLICATION
THAT HAS THREE THREADS.
PROGRAM:
import java.util.*;

class NumberGenerator{
{
private int value; private
boolean flag;
public synchronized void put() {

{
while (flag) {

{
try
{
wait();
}
catch(InterruptedException e) {}
}
flag=true;
Random random=new Random();
this.value=random.nextInt(10); System.out.println("The
generated Number is:"+value); notifyAll();
}
public synchronized void get1() {

{
while (!flag){ try{
wait();
}
catch(InterruptedException e) {}}
if(value%2==0)
{
System.out.println("Second is executing now..."); int
ans=value*value;
System.out.println(value+"is Even Number and its square

is:"+ans);
}
flag=false;
notifyAll();
}
public synchronized void get2(){

{
while (!flag){ try{
wait();
}
catch(InterruptedException e) {}
}
if(value%2==0)
{
System.out.println("Third Thread is executing now..."); int
ans=value*value*value;
System.out.println(value+"is an Odd Number and its cube is:"+ans);
}
flag=false;
notifyAll();

}}}

public class TestNumber


{
public static void main(String[]args){
{
final NumberGenerate obj=new NumberGenerate(); Thread
producerThread=new Thread(){
{System.out.println("Main thread started..."); obj.put();
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}}}};
Thread consumerThread1=new Thread(){
{
public void run(){
{
for(int i=1;i<=3;i++)
{
obj.get1(); try {
{
Thread.sleep(2000);
}
catch(InterruptedException e){}}}};
Thread consumerThread2=new Thread(){
{
public void run(){
{
for(int i=1;i<=3;i++){
{
obj.get2(); try {
{
Thread.sleep(3000);
}
catch(InterruptedException e){}}}}
producerThread.start(); consumerThread1.start(); consumerThread2.startstart();}
}
OUTPUT:
C:\MRKITCSE>javac TestNumber.java
C:\MRKITCSE>java TestNumber
Main thread started...
The generated Number is:7 Third
Thread is executing now...
7is Odd Number and its cube is:343 Main
thread started...
The generated Number is:1 Main
thread started...
The generated Number is:8 Main
thread started...
The generated Number is:6 Second is
executing now...
6is Even Number and its square is:36 Main
thread started...
The generated Number is:3 Main
thread started...
The generated Number is:9 Third
Thread is executing now...
9is Odd Number and its cube is:729
8A: DESIGN A JAVA SIMPLE APPLICATION USING JAVA FX CONTROLS
, LAYOUTS AND MENUS.

PROGRAM:

import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final JFrame f= new JFrame("PopupMenu Example");
final JPopupMenu popupmenu = new JPopupMenu("Edit");
JMenuItem cut = new JMenuItem("Cut");
JMenuItem copy= new JMenuItem("Copy");
JMenuItem paste = new JMenuItem("Paste");
popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
f.add(popupmenu);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample();
}}
OUTPUT:
8B: DESIGN A JAVA SIMPLE APPLICATION USING JAVA FX CONTROLS ,LAYOUTS
AND MENUS.

PROGRAM:

import javax.swing.*;
import java.awt.*;
public class SeparatorExample
{
public static void main(String args[]) {
JFrame f = new JFrame("Separator Example");
f.setLayout(new GridLayout(0, 1));
JLabel l1 = new JLabel("Above Separator");
f.add(l1);
JSeparator sep = new JSeparator();
f.add(sep);
JLabel l2 = new JLabel("Below Separator");
f.add(l2);
f.setSize(400, 100);
f.setVisible(true);
}
}

OUTPUT:
8C: DESIGN A JAVA SIMPLE APPLICATION USING JAVA FX CONTROLS ,LAYOUTS
AND MENUS.

PROGRAM:

import javax.swing.*;
public class ProgressBarExample extends JFrame{
JProgressBar jb;
int i=0,num=0;
ProgressBarExample(){
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
}
}
public static void main(String[] args) {
ProgressBarExample m=new ProgressBarExample();
m.setVisible(true);
} m.iterate();

}
OUTPUT:
8D: DESIGN A JAVA SIMPLE APPLICATION USING JAVA FX CONTROLS ,LAYOUTS
AND MENUS.

PROGRAM:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorChooserExample extends JFrame implements ActionListener{
JFrame f;
JButton b;
JTextArea ta;
ColorChooserExample(){
f=new JFrame("Color Chooser Example.");
b=new JButton("Pad Color");
b.setBounds(200,250,100,30);
ta=new JTextArea();
ta.setBounds(10,10,300,200);
b.addActionListener(this);
f.add(b);f.add(ta);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
Color c=JColorChooser.showDialog(this,"Choose",Color.CYAN);
ta.setBackground(c);
}
public static void main(String[] args) {
new ColorChooserExample();
}
}
OUTPUT:

4
9: Number is odd or even using the constructor

PROGRAM:
import java.util.Scanner;
class Test {
int n, i, p = 1;
Scanner sc = new Scanner(System.in);
Test() {
System.out.print("Enter a number:");
n = sc.nextInt(); }
void check() {
if (n % 2 == 0) {
System.out.println("Number is even :" + n);
} else {
System.out.println("Number is odd :" + n);
} }}
class Main {
public static void main(String args[]) {
Test obj = new Test();
obj.check();
}}

OUTPUT:

Enter a number: 45

Number is odd :45


10: AREA OF SQUARE AND RECTANGLE USING A JAVA INTERFACE

PROGRAM:

interface Area
{
double Compute(double a, double b);
}
class Rectangle implements Area
{
public double Compute(double l, double b)
{
return (l*b); }}
class Triangle implements Area
{ public double Compute(double b, double h)
{
return (b*h/2); }}
public class MainArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
double RArea = rect.Compute(10, 20);
System.out.println("The area of the Rectangle is "+RArea);
Triangle tri = new Triangle();
double TArea = tri.Compute(10, 20);
System.out.println("The area of the triangle is "+TArea);}}

OUTPUT:

The area of the rectangle is 100.0


The area of the triangle is 40.0
11: To find the area of a circle using a Java interface

PROGRAM:

interface Area {
double compute(double r);}
class Circle implements Area {
public double compute(double r) {
return Math.PI * r * r;}
}
public class MainArea{
public static void main(String[] args) {
Circle c = new Circle();
double radius = 5.0;
double area = c.compute(radius);
System.out.println("The area of the circle is " + area);
}
}

OUTPUT :

The area of the circle is 78.5398


12: To implement user-defined exception handling.

PROGRAM :
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class MainArea {
public static void main(String[] args) {
try {
throw new MyException("This is my custom exception.");
} catch (MyException e) {
System.out.println("Caught the exception: " + e.getMessage());
}
}
}

OUTPUT :
Caught the exception : “This is my custom exception."
13: To create a user – defined exception class and handle that
Exception using a try-catch block

PROGRAM :

.public class TryCatchExample3 {

public static void main(String[] args) {

try

int data=50/0; //may throw an exception

// if an exception occurs, the remaining statement will not exceute

System.out.println("rest of the code");

// handling the exception

catch(ArithmeticException e)

System.out.println(e);

OUTPUT :

F:\>javac TryCatchExample3.java
F:\>java TryCatchExample3
java.lang.ArithmeticException: / by zero
14: To create an interface, which has two methods called add() and sub().
Create a class for overloading the given methods for addition and
subtraction of two numbers.

PROGRAM :

class Overload_Demo implements IterF1

{ public void add()

System.out.println("Addition of "+a+" and "+b+" is: "+(a+b));

public void sub()

System.out.println("Addition of "+a+" and "+b+" is: "+(a-b));

public void sub(String[] args)

Overload_Demo obj = new Overload_Demo();

obj.add();

obj.sub(); }}

interface IterF1

int a = 50;

int b = 30;

void add();
void sub();}

OUTPUT :

F:\>javac Overload_Demo.java

F:\>java Overload_Demo.

Addition of 50 and 30 is: 80.

Subtraction of 50 and 30 is: 20


15: Develop a java code to find the maximum value from the given input
Using a generic function

PROGRAM:
import java.util.Scanner;
public class Max {
public <T extends Comparable<T>> T findMax(T[] arr) {
T max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i].compareTo(max) > 0) {
max = arr[i];
}
}
return max;
}

public static void main(String[] args) {


Scanner scnr = new Scanner(System.in);
System.out.println("Enter the number of elements: ");
int n = scnr.nextInt();

Integer[] arr = new Integer[n];


System.out.println("Enter the elements: ");
for (int i = 0; i < n; i++) {
arr[i] = scnr.nextInt();

}
Max obj = new Max();
System.out.println("Maximum value: " + obj.findMax(arr));
}
}
OUTPUT:

Enter the number of elements:

Enter the elements:

Maximum value: 7
16: Develop a java code implement sorting any two algorithms.

PROGRAM:

import java.util.Scanner;
import java.util.Arrays;
public class Sort {
public static <T extends Comparable<T>> T[] selectionSort(T[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i+ 1; j < arr.length; j++) {
if (arr[j].compareTo(arr[minIndex]) < 0) {
minIndex = j;}}
T temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;}
return arr;}
public static <T extends Comparable<T>> T[] bubbleSort(T[] arr) {
boolean swapped = true;
while (swapped) {
swapped = false;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i].compareTo(arr[i + 1]) > 0) {
T temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;}}}
return arr;}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the number of elements: ");
int n = scnr.nextInt();
Integer[] arr = new Integer[n];
System.out.println("Enter the elements: ");
for (int i = 0; i < n; i++) {
arr[i] = scnr.nextInt();
}
System.out.println("Original array: " + Arrays.toString(arr));
Integer[] sortedArr1 = selectionSort(arr.clone());
System.out.println("Array sorted using selection sort: " + Arrays.toString(sortedArr1));
Integer[] sortedArr2 = bubbleSort(arr.clone());
System.out.println("Array sorted using bubble sort: " + Arrays.toString(sortedArr2));
}
}
OUTPUT:
Enter the number of elements:
5
Enter the elements: 2
6
4
7
8
Original array: [2, 6, 4, 7, 8]
Array sorted using selection sort: [2, 4, 6, 7, 8]
Array sorted using bubble sort: [2, 4, 6, 7, 8]
17: Develop a java code to perform any four file operations.

PROGRAM:

import java.io.File;

class FileInfo {

public static void main(String[] args) {

// Creating file object

File f0 = new File("D:FileOperationExample.txt");

if (f0.exists()) {

// Getting file name

System.out.println("The name of the file is: " + f0.getName());

// Getting path of the file

System.out.println("The absolute pathofthe file is: " + f0.getAbsolutePath());

// Checking whether the file is writable or not

System.out.println("Is file writeable?: " + f0.canWrite());

// Checking whether the file is readable or not

System.out.println("Is file readable " + f0.canRead());

// Getting the length of the file in bytes

System.out.println("The size of the file in bytes is: " + f0.length());

} else {

System.out.println("The file does not exist.");


} }}

OUTPUT:

The file does not exist.

You might also like