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

Java CodeTantra

solutions in java 1

Uploaded by

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

Java CodeTantra

solutions in java 1

Uploaded by

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

S.No: 1 Exp.

Name: Write a Java program on XOR operator Date: 2024-09-18

Aim:
Create a class called BitwiseXOR with main method in it to perform BitwiseXOR operation by taking two input

Page No: 1
numbers.

Constraints:
If two numbers A and C are given you have to find a number B such that A (+)B = C can be read as

ID: 23CSC25
A XOR B = C .

Note: All inputs will be given as command line arguments.


Source Code:

q29544/BitwiseXOR.java

package q29544;

public class BitwiseXOR{


public static void main(String[] args){
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);

2023-27-CSE-C
int num3 = num1 ^ num2;

System.out.println("XOR Result = " + num3);


}
}

BNM Institute Of Technology


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
XOR Result = 4

Test Case - 2

User Output
XOR Result = 32

Test Case - 3

User Output
XOR Result = 0

Test Case - 4

User Output
XOR Result = 1
Exp. Name: Write the code to convert rupees to
S.No: 2 Date: 2024-09-18
dollars

Aim:

Page No: 2
Write a program to convert rupees to dollars. 60 rupees=1 dollar
Source Code:

InrtoUsd.java

ID: 23CSC25
import java.util.*;
public class InrtoUsd{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter INR to convert into USD: ");
double inr = sc.nextDouble();
System.out.println("USD: " + (inr/60));
}
}

2023-27-CSE-C
Execution Results - All test cases have succeeded!
Test Case - 1

User Output
Enter INR to convert into USD:

BNM Institute Of Technology


870
USD: 14.5

Test Case - 2

User Output
Enter INR to convert into USD:
60
USD: 1.0
Exp. Name: Write a Java program to sort a list of
S.No: 3 Date: 2024-09-21
names in ascending order.

Aim:

Page No: 3
Write a Java program to sort a list of names in ascending order.
Source Code:

SortNames.java

ID: 23CSC25
2023-27-CSE-C
BNM Institute Of Technology
import java.util.Scanner;

public class SortNames{

public static int strcmp(String s1, String s2){

Page No: 4
int i = 0;
while((i < s1.length()) && (i < s2.length())){
char a = s1.charAt(i);
char b = s2.charAt(i);
if (a > b){

ID: 23CSC25
return 1;
}else if (a < b){
return -1;
}else{
i++;
}
}
if(i < s1.length()){
return 1;
}else if (i < s2.length()){
return -1;
}else{

2023-27-CSE-C
return 0;
}
}

public static void alphasort(String[] arr){


for(int i = 0; i < arr.length-1; i++){

BNM Institute Of Technology


for(int j = 0; j < arr.length-i-1; j++){
if(strcmp(arr[j], arr[j+1]) >= 0){
String temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

public static void main(String[] args){

Scanner sc = new Scanner(System.in);


System.out.print("Enter the number of names you want to enter: ");
int n = sc.nextInt();
sc.nextLine();

System.out.print("Enter the names: ");


String[] sa = new String[n];
for(int i = 0; i < n; i++){
sa[i] = sc.nextLine();
}

alphasort(sa);
System.out.print("Sorted names:");
for(int i = 0; i < n; i++){
System.out.print(sa[i] + " ");
}

Page No: 5
Execution Results - All test cases have succeeded!
Test Case - 1

ID: 23CSC25
User Output
Enter the number of names you want to enter:
5
Enter the names:
Roy
Dora
Zoya
Suzan
Harry
Sorted names:Dora Harry Roy Suzan Zoya

2023-27-CSE-C
Test Case - 2

User Output
Enter the number of names you want to enter:
10

BNM Institute Of Technology


Enter the names:
Matt
Lionel
Gary
Daniel
Chole
Andreas
Sergio
Eden
zenith
Tim
Sorted names:Andreas Chole Daniel Eden Gary Lionel Matt Sergio Tim zenith

Test Case - 3

User Output
Enter the number of names you want to enter:
7
Enter the names:
Jhon
Jack
Jhonson
Jockey
Jammy
Jacky
Sorted names:Jack Jacky Jammy Jarden Jhon Jhonson Jockey

Page No: 6
ID: 23CSC25
2023-27-CSE-C
BNM Institute Of Technology
Exp. Name: Write the code to print a string entered
S.No: 4 Date: 2024-09-18
in pyramid form

Aim:

Page No: 7
Write an interactive program to print a string entered in pyramid form.
Source Code:

Pattern.java

ID: 23CSC25
import java.util.*;
public class Pattern{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//String s = new String();
System.out.print("Enter a string: ");
String s = sc.nextLine();

for(int i = 0; i < s.length(); i++){


char ch = s.charAt(i);
for(int j = i; j < s.length(); j++){
System.out.print(" ");

2023-27-CSE-C
}
for(int k = 0; k <= i; k++){
System.out.print(s.charAt(k) + " ");
}
System.out.println(" ");
}

BNM Institute Of Technology


}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter a string:
OliVeR
O
O l
O l i
O l i V
O l i V e
O l i V e R

Test Case - 2

User Output
Enter a string:
AmeLiA
A
A m e
A m e L
A m e L i
A m e L i A

BNM Institute Of Technology 2023-27-CSE-C ID: 23CSC25 Page No: 8


Exp. Name: Write the code to find the length of the
S.No: 5 Date: 2024-09-18
string and print the second half of the string

Aim:

Page No: 9
Write a program to find the length of the string and print the second half of the string.
Source Code:

SubString.java

ID: 23CSC25
import java.util.*;
public class SubString{
public static void main(String[] args){

Scanner sc = new Scanner(System.in);


System.out.print("Enter a string: ");
String s = sc.nextLine();

int len = s.length();


System.out.println("Length of the string " + s + " is: " + len);
int half = len/2;
System.out.print("Sub string is: ");

2023-27-CSE-C
for(int i = half; i < len; i++){
char ch = s.charAt(i);
System.out.print(ch);
}
System.out.println();
}

BNM Institute Of Technology


}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter a string:
Programming
Length of the string Programming is: 11
Sub string is: amming

Test Case - 2

User Output
Enter a string:
Thankyou
Length of the string Thankyou is: 8
Sub string is: kyou
Exp. Name: Java Program to check whether the
S.No: 6 Date: 2024-09-18
given number is Palindrome or not

Aim:

Page No: 10
Write a class NumberPalindrome with a public method isNumberPalindrome that takes one parameter number
of type int . Write a code to check whether the given number is palindrome or not.

For example

ID: 23CSC25
Cmd Args : 333
333 is a palindrome

Note: Please don't change the package name.


Source Code:

q10894/NumberPalindrome.java

package q10894;

public class NumberPalindrome {

2023-27-CSE-C
public void isNumberPalindrome(int number) {

int rem, no, res;


no = number;
res = 0;

BNM Institute Of Technology


while(no != 0){
rem = no % 10;
res = (res*10) + rem;
no /= 10;
}

if(number == res){
System.out.println(number + " is a palindrome");
}else{
System.out.println(number + " is not a palindrome");
}

}
}

q10894/NumberPalindromeMain.java
package q10894;
public class NumberPalindromeMain{
public static void main(String[] args){
if (args.length < 1) {
System.out.println("Usage: java NumberPalindromeMain <number>");

Page No: 11
System.exit(-1);
}
try {
int number = Integer.parseInt(args[0]);
NumberPalindrome nPalindrome = new NumberPalindrome();

ID: 23CSC25
nPalindrome.isNumberPalindrome(number);
} catch(NumberFormatException nfe) {
System.out.println("Usage: java NumberPalindromeMain
<number>\n\tage: an integer representing number");
}

}
}

Execution Results - All test cases have succeeded!

2023-27-CSE-C
Test Case - 1

User Output
333 is a palindrome

BNM Institute Of Technology


Test Case - 2

User Output
567 is not a palindrome
S.No: 7 Exp. Name: Write the code to calculate percentage Date: 2024-09-17

Aim:
Write a program that calculates the percentage marks of the student if marks in 6 subjects are given.

Page No: 12
Source Code:

Percentage.java

import java.util.*;

ID: 23CSC25
public class Percentage{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int sum = 0;
for(int i = 0; i < 6; i++){
System.out.print("Enter the marks for subject" + (i+1) + ": ");
sum += sc.nextInt();
}
System.out.println("Percentage: " + (sum/6) + ".0");
}
}

2023-27-CSE-C
Execution Results - All test cases have succeeded!
Test Case - 1

BNM Institute Of Technology


User Output
Enter the marks for subject1:
56
Enter the marks for subject2:
87
Enter the marks for subject3:
29
Enter the marks for subject4:
55
Enter the marks for subject5:
36
Enter the marks for subject6:
48
Percentage: 51.0

Test Case - 2

User Output
Enter the marks for subject1:
85
Enter the marks for subject2:
66
Enter the marks for subject3:
97
Enter the marks for subject4:
85
Enter the marks for subject5:
69
Enter the marks for subject6:

Page No: 13
98
Percentage: 83.0

ID: 23CSC25
2023-27-CSE-C
BNM Institute Of Technology
Exp. Name: Write the code to count the number of
S.No: 8 Date: 2024-09-17
words that start with capital letters

Aim:

Page No: 14
Write a program to count the number of words that start with capital letters.
Source Code:

Cap.java

ID: 23CSC25
import java.util.*;
public class Cap{
public static void main(String[] args){

Scanner sc = new Scanner(System.in);


System.out.print("Enter a line: ");
String s = sc.nextLine();
int c = 0;

for(int i = 0; i < s.length(); i++){


char ch = s.charAt(i);
if(ch >= 65 && ch <= 90){

2023-27-CSE-C
c++;
}
}
System.out.println("Capital letters: " + c);
}
}

BNM Institute Of Technology


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
Enter a line:
Hello there Are Some Capital And Some small
words
Capital letters: 6

Test Case - 2

User Output
Enter a line:
The Train Leaves Early Morning at 8 AM
Capital letters: 7
S.No: 9 Exp. Name: Even Odd without Modulus Date: 2024-09-18

Aim:
Create a class EvenOdd with main method in it to find whether the number is even or odd.

Page No: 15
Constraints :
1. Do not use the Modulus operator.
2. If the number is even print Even otherwise print Odd.
3. If the number is negative then print Error : Invalid Input.

ID: 23CSC25
Note : All Inputs will be given as command line arguments.
Source Code:

q29581/EvenOdd.java

package q29581;
public class EvenOdd{
public static void main(String[] args){
int input = Integer.parseInt(args[0]);
if (input < 0){
System.out.println("Error : Invalid Input");

2023-27-CSE-C
}else{
if((input & 1) == 1){
System.out.println("Odd");
}else{
System.out.println("Even");
}

BNM Institute Of Technology


}
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Even

Test Case - 2

User Output
Odd

Test Case - 3

User Output
Error : Invalid Input
Exp. Name: Find minimum and maximum numbers
S.No: 10 Date: 2024-09-19
from given array.

Aim:

Page No: 16
Write a Java program to find minimum and maximum numbers in a given array of size n.

Constraint:
• 1 ≤ n ≤ 100

ID: 23CSC25
Input Format:
• The first line of input consists of the size of the array (integer).
• The second line of the input consists of elements of the array (integers).

Output Format:
• The first line of output represents the minimum element in the array.
• The second line of output represents the maximum element in the array.
Source Code:

MinMaxArray.java

2023-27-CSE-C
BNM Institute Of Technology
import java.util.*;

public class MinMaxArray{

public static void bubblesort(int[] arr){

Page No: 17
for(int i = 0; i < arr.length - 1; i++){
for(int j = 0; j < arr.length - i - 1; j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];

ID: 23CSC25
arr[j+1] = temp;
}
}
}
}

public static void main(String[] args){

Scanner sc = new Scanner(System.in);


System.out.print("Enter number of elements: ");
int n = sc.nextInt();
int arr[] = new int[n];

2023-27-CSE-C
sc.nextLine();
System.out.print("Enter array elements: ");
String s = sc.nextLine();
String sa[] = s.split("\\s");

BNM Institute Of Technology


for(int i = 0; i < n; i++){
arr[i] = Integer.parseInt(sa[i]);
}

bubblesort(arr);
System.out.println("Minimum element in array is: " + arr[0]);
System.out.println("Maximum element in array is: " + arr[arr.length - 1]);
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter number of elements:
5
Enter array elements:
100 1 135 0 12
Minimum element in array is: 0
Maximum element in array is: 135

Test Case - 2
User Output
Enter number of elements:
10
Enter array elements:
2 2222 222 22222 22 1 1111 111111 111

Page No: 18
11111
Minimum element in array is: 1
Maximum element in array is: 111111

ID: 23CSC25
Test Case - 3

User Output
Enter number of elements:
8
Enter array elements:
88 77 66 55 44 33 22 11
Minimum element in array is: 11
Maximum element in array is: 88

2023-27-CSE-C
BNM Institute Of Technology
Exp. Name: Calculating resistance using two
S.No: 11 Date: 2024-09-20
resistor objects

Aim:

Page No: 19
Define the Resistor class in which we define the following members:

Instance variables:
resistance

ID: 23CSC25
Instance Methods:
giveData(): To assign data to the resistance variable
displayData(): To display data in the resistance variable constructors

Define subclasses for the Resistor class called Series Circuit and Parallel Circuit in which define methods:
calculateSeriesResistance ( ) and calculateParallelResistance () respectively. Both methods should take two
Resistor objects as arguments and return the Resistor object as a result. In the main method, define another class
called Resistor Execute to test the above class.
Source Code:

ResistorExecute.java

2023-27-CSE-C
BNM Institute Of Technology
import java.util.Scanner;

class Resistor {
double resistance;

Page No: 20
void giveData(double r){
this.resistance = r;
}

void displayData(){

ID: 23CSC25
System.out.println("Resistance:" + resistance);
}
}

class SeriesCircuit extends Resistor {


public static Resistor calculateSeriesResistance(Resistor resistor1, Resistor
resistor2) {
double res = resistor1.resistance + resistor2.resistance;
Resistor Series = new Resistor();
Series.resistance = res;
return Series;
}

2023-27-CSE-C
}

class ParallelCircuit extends Resistor {


public static Resistor calculateParallelResistance(Resistor resistor1, Resistor
resistor2) {
double res = 1 / (1 / resistor1.resistance + 1 / resistor2.resistance);

BNM Institute Of Technology


Resistor Parallel = new Resistor();
Parallel.resistance = res;
return Parallel;
}

public class ResistorExecute {


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

System.out.println("Enter resistance value for Resistor-1:");


double resistance1 = scanner.nextDouble();
System.out.println("Enter resistance value for Resistor-2:");
double resistance2 = scanner.nextDouble();

Resistor resistor1 = new Resistor();


Resistor resistor2 = new Resistor();

resistor1.giveData(resistance1);
resistor2.giveData(resistance2);

SeriesCircuit ob1 = new SeriesCircuit();


ParallelCircuit ob2 = new ParallelCircuit();

Resistor Series = ob1.calculateSeriesResistance(resistor1, resistor2);


Resistor Parallel = ob2.calculateParallelResistance(resistor1, resistor2);
resistor1.displayData();
System.out.print("Resistor-2 ");
resistor2.displayData();
System.out.print("Series ");
Series.displayData();

Page No: 21
System.out.print("Parallel ");
Parallel.displayData();
}
}

ID: 23CSC25
Execution Results - All test cases have succeeded!
Test Case - 1

User Output
Enter resistance value for Resistor-1:
40
Enter resistance value for Resistor-2:
30

2023-27-CSE-C
Resistor-1 Resistance:40.0
Resistor-2 Resistance:30.0
Series Resistance:70.0
Parallel Resistance:17.142857142857142

BNM Institute Of Technology


Test Case - 2

User Output
Enter resistance value for Resistor-1:
100
Enter resistance value for Resistor-2:
40
Resistor-1 Resistance:100.0
Resistor-2 Resistance:40.0
Series Resistance:140.0
Parallel Resistance:28.57142857142857
Exp. Name: Area of Triangle, Rectangle and Circle
S.No: 12 Date: 2024-09-21
using interface

Aim:

Page No: 22
Define an interface “Geometric Shape” with methods area() and perimeter() (Both method’s return type and
parameter list should be void and empty respectively.)

Define classes like Triangle, Rectangle, and Circle implementing the “Geometric Shape” interface and calculate the
area and perimeter of the respective Triangle, Rectangle, and Circle and also define the “Execute Main” class

ID: 23CSC25
which includes the main method to test the above class. Prompt the user to enter the choice to select a shape
and dimensions like length l, breadth b, side s, and radius r of each shape as required.

Note: For the value of π, utilize the Math.PI constant.

Constraint:
• 1 ≤ l ≤ 100
• 1 ≤ b ≤ 100
• 1 ≤ s ≤ 100
• 1 ≤ r ≤ 100

Input Format:

2023-27-CSE-C
• The first line of the input consists of a number representing the choice to select a shape (integer).
• The next line of the input consists of the dimensions of the shape respectively.

Output Format:
• The first line of the output represents the area of the selected shape (float).
• The second line of the output represents the perimeter of the selected shape (float).

BNM Institute Of Technology


Source Code:

q17207/ExecuteMain.java
package q17207;
import java.util.*;

interface GSI{
void area();

Page No: 23
void perimeter();
}

class Triangle implements GSI{


int l, b, h;

ID: 23CSC25
Triangle(String[] sa){
l = Integer.parseInt(sa[0]);
b = Integer.parseInt(sa[1]);
h = Integer.parseInt(sa[2]);
}

public void area(){


double s = (double) (l + b + h) / 2;
double x = s * (s-l) * (s-b) * (s-h);
double a = Math.sqrt(x);
System.out.println("Area of Triangle:" + a);
}

2023-27-CSE-C
public void perimeter(){
double p = (double) l + b + h;
System.out.println("Perimeter of Triangle:" + p);
}
}

BNM Institute Of Technology


class Rectangle implements GSI{
int l, b;
Rectangle(String[] sa){
l = Integer.parseInt(sa[0]);
b = Integer.parseInt(sa[1]);
}

public void area(){


double a = (double) l*b;
System.out.println("Area of Rectangle:" + a);
}
public void perimeter(){
double p = (double) (l + b) * 2;
System.out.println("Perimeter of Rectangle:" + p);
}
}

class Circle implements GSI{


int r;
Circle(int r){
this.r = r;
}

public void area(){


double a = (double) Math.PI * r * r;
System.out.println("Area of Circle:" + a);
}
System.out.println("Circumference of Circle:" + p);
}
}

public class ExecuteMain{

Page No: 24
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Choose a geometric shape:");
System.out.println("1.Triangle\n2.Rectangle\n3.Circle");
System.out.println("Enter your choice:");

ID: 23CSC25
int ch = sc.nextInt();

String s = new String();


String[] sa = new String[3];

switch(ch){
case 1:
System.out.println("Enter lengths of the three sides of
Triangle:");
sc.nextLine();
s = sc.nextLine();
sa = s.split("\\s");

2023-27-CSE-C
Triangle ob1 = new Triangle(sa);
ob1.area();
ob1.perimeter();
break;

case 2:

BNM Institute Of Technology


System.out.println("Enter length and breadth of
Rectangle:");
sc.nextLine();
s = sc.nextLine();
sa = s.split("\\s");
Rectangle ob2 = new Rectangle(sa);
ob2.area();
ob2.perimeter();
break;

case 3:
System.out.println("Enter radius of Circle:");
sc.nextLine();
int r = sc.nextInt();
Circle ob3 = new Circle(r);
ob3.area();
ob3.perimeter();
break;

default:
System.out.println("Invalid choice");
}
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Choose a geometric shape:
1.Triangle

Page No: 25
2.Rectangle
3.Circle
Enter your choice:
1

ID: 23CSC25
Enter lengths of the three sides of Triangle:
345
Area of Triangle:6.0
Perimeter of Triangle:12.0

Test Case - 2

User Output
Choose a geometric shape:
1.Triangle

2023-27-CSE-C
2.Rectangle
3.Circle
Enter your choice:
2
Enter length and breadth of Rectangle:
10 20

BNM Institute Of Technology


Area of Rectangle:200.0
Perimeter of Rectangle:60.0

Test Case - 3

User Output
Choose a geometric shape:
1.Triangle
2.Rectangle
3.Circle
Enter your choice:
3
Enter radius of Circle:
6
Area of Circle:113.09733552923255
Circumference of Circle:37.69911184307752

Test Case - 4

User Output
Choose a geometric shape:
1.Triangle
2.Rectangle
5
Invalid choice
Enter your choice:

BNM Institute Of Technology 2023-27-CSE-C ID: 23CSC25 Page No: 26


Exp. Name: Representation of Bank Account using
S.No: 13 Date: 2024-09-22
classes and methods

Aim:

Page No: 27
Define a BankAccount class to represent a bank account and include the following members

Instance variables:
(i) Name of depositor
(ii) Account No

ID: 23CSC25
(iii)Type of account(savings/current)
(iv) Balance amount in the account

Instance Methods:
4. To assign instance variables (Constructors-Zero argument and parameterized)
5. To deposit an amount
6. To withdraw the amount after checking the balance
7. To display name and address

Define the ExecuteAccount class which defines the main method to test the above class.

Note: The defined methods are invoked in the ExecuteAccount class.

2023-27-CSE-C
Source Code:

ExecuteAccount.java

BNM Institute Of Technology


import java.util.Scanner;

class BankAccount {
String name, type;
double balance;

Page No: 28
int account;

BankAccount(String n, String t, double b, int a){


name = n;
type = t;

ID: 23CSC25
balance = b;
account = a;
}

BankAccount(){
name = "None";
type = "savings";
balance = 0;
account = 0;
}

void deposit(double am){

2023-27-CSE-C
balance += am;
System.out.println("Deposit successful. New balance: " + balance);
}

void withdraw(double am){


if (am < balance){

BNM Institute Of Technology


balance -= am;
System.out.println("Withdrawal successful. New balance: " +
balance);
}else{
System.out.println("Insufficient balance");
}
}

void displayAccountDetails(){
System.out.println("Account Details:");
System.out.println("Account Holder: " + name);
System.out.println("Account Number: " + account);
System.out.println("Account Type: " + type);
System.out.println("Balance: " + balance);
}
}
public class ExecuteAccount {
public static void main(String[] args){

Scanner sc = new Scanner(System.in);

System.out.print("account holder: ");


String n = sc.nextLine();
System.out.print("account number: ");
int a = sc.nextInt();
sc.nextLine();
System.out.print("account type: ");
double b = sc.nextInt();
sc.nextLine();

BankAccount account = new BankAccount(n, t, b, a);

Page No: 29
System.out.print("amount to deposit: ");
double depositAmount = sc.nextInt();
sc.nextLine();
if(depositAmount > 0){
account.deposit(depositAmount);

ID: 23CSC25
}else{
System.out.println("Invalid deposit amount");
}

System.out.print("amount to withdraw: ");


double withdrawAmount = sc.nextInt();
sc.nextLine();
if(withdrawAmount > 0){
account.withdraw(withdrawAmount);
}else{
System.out.println("Invalid withdrawal amount");
}

2023-27-CSE-C
account.displayAccountDetails();

}
}

BNM Institute Of Technology


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
account holder:
John
account number:
101011
account type:
savings
initial balance:
1000
amount to deposit:
500
Deposit successful. New balance: 1500.0
amount to withdraw:
800
Withdrawal successful. New balance: 700.0
Account Details:
Account Holder: John
Account Number: 101011
Account Type: savings
Balance: 700.0

Test Case - 2

User Output

Page No: 30
account holder:
Richa
account number:
111222333

ID: 23CSC25
account type:
current
initial balance:
10000
amount to deposit:
-900
Invalid deposit amount
amount to withdraw:
11000
Insufficient balance

2023-27-CSE-C
Account Details:
Account Holder: Richa
Account Number: 111222333
Account Type: current
Balance: 10000.0

BNM Institute Of Technology


Test Case - 3

User Output
account holder:
Smith
account number:
14231421
account type:
savings
initial balance:
8000
amount to deposit:
900
Deposit successful. New balance: 8900.0
amount to withdraw:
-600
Invalid withdrawal amount
Account Details:
Account Holder: Smith
Account Number: 14231421
Account Type: savings
Balance: 8900.0
Exp. Name: Write a Java program to implement a
S.No: 14 Date: 2024-09-20
Constructor

Aim:

Page No: 31
Write a Java program with a class name Staff , contains the data members id (int), name (String) which are
initialized with a parameterized constructor and the method show().

The member function show() is used to display the given staff data.

ID: 23CSC25
Write the main() method with in the class which will receive two arguments as id and name.

Create an object to the class Staff with arguments id and name within the main(), and finally call the method
show() to print the output.

If the input is given as command line arguments to the main() as "18", "Gayatri" then the program should print
the output as:

Id : 18
Name : Gayatri

2023-27-CSE-C
Note: Please don't change the package name.
Source Code:

BNM Institute Of Technology


q11116/Staff.java
package q11116;

public class Staff{


int id;
String name;
Staff(int i, String n){
this.id = i;
this.name = n;
}
void show(){
System.out.println("Id : " + this.id);
System.out.println("Name : " + this.name);
}

public static void main(String[] args){


int a = Integer.parseInt(args[0]);
String b = args[1];

Staff obj = new Staff(a, b);


obj.show();
}

}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 32
Id : 18
Name : Gayatri

Test Case - 2

ID: 23CSC25
User Output
Id : 45
Name : Akbar

2023-27-CSE-C
BNM Institute Of Technology
Exp. Name: Write the code to find area of a
S.No: 15 Date: 2024-09-22
rectangle and triangle respectively.

Aim:

Page No: 33
Write a java program to create a super class called Figure that receives the dimensions of two dimensional
objects. It also defines a method called area that computes the area of an object. The program derives two
subclasses from Figure. The first is Rectangle and second is Triangle. Each of the sub classes override area () so
that it returns the area of a rectangle and triangle respectively.
Source Code:

ID: 23CSC25
SuperClass.java

2023-27-CSE-C
BNM Institute Of Technology
import java.util.*;

class Figure{
int b, h;
Figure(int b, int h){

Page No: 34
this.b = b;
this.h = h;
}

void area(){

ID: 23CSC25
double a = (double) b * h;
System.out.println("Area of figure: " + a);
}
}

class Rectangle extends Figure{


Rectangle(int b, int h){
super(b, h);
}

void area(){
double a = (double) b * h;

2023-27-CSE-C
System.out.println("Area of rectangle: " + a);
}
}

class Triangle extends Figure{


Triangle(int b, int h){

BNM Institute Of Technology


super(b, h);
}

void area(){
double a = (double) (b * h)/2;
System.out.println("Area of triangle: " + a);
}
}

public class SuperClass{


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

System.out.print("Rectangle length: ");


int b1 = sc.nextInt();
System.out.print("Rectangle width: ");
int h1 = sc.nextInt();

Rectangle rect = new Rectangle(b1, h1);

System.out.print("Triangle base: ");


int b2 = sc.nextInt();
System.out.print("Triangle height: ");
int h2 = sc.nextInt();

Triangle tri = new Triangle(b2, h2);


}
}

Page No: 35
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

ID: 23CSC25
Rectangle length:
76
Rectangle width:
43
Triangle base:
6
Triangle height:
3
Area of rectangle: 3268.0
Area of triangle: 9.0

2023-27-CSE-C
Test Case - 2

User Output
Rectangle length:

BNM Institute Of Technology


4
Rectangle width:
5
Triangle base:
5
Triangle height:
7
Area of rectangle: 20.0
Area of triangle: 17.5
S.No: 16 Exp. Name: Dynamic method dispatch Date: 2024-09-22

Aim:
Implement runtime polymorphism using the dynamic method dispatch for the scenario given:

Page No: 36
Create three classes Rectangle (Parent), Square(Child of Rectangle), and Triangle (Child of Rectangle). These
classes contain a method “area” to calculate the area of the shape using appropriate expressions. Create another
class “Calculation” with the “main” method where objects are created, and appropriate methods are called. Here,
implement the method overriding concept. Prompt the user to enter the dimensions like length l, width w, side s,
base b, and height h of each shape as required.

ID: 23CSC25
Constraint:
• 1 ≤ l ≤ 100
• 1 ≤ w ≤ 100
• 1 ≤ s ≤ 100
• 1 ≤ b ≤ 100
• 1 ≤ h ≤ 100

Input Format:
• The first two lines of the input consist of the length, width of the rectangle (integer).
• The next line of the input consists of the side of the square (integer).
• The next two lines of the input consist of the base, height of the triangle (integer).

2023-27-CSE-C
Output Format:
• The output represents the area (integer) of each shape in the next line after taking dimensions respectively.
Source Code:

Calculation.java

BNM Institute Of Technology


import java.util.Scanner;

class Rectangle {
int l, w;
Rectangle(int l, int w){

Page No: 37
this.l = l;
this.w = w;
}

Rectangle(){

ID: 23CSC25
;
}

void area(){
int a = l*w;
System.out.println("Area of rectangle:" + a);
}

class Square extends Rectangle {


int s;

2023-27-CSE-C
Square(int s){
this.s = s;
}

void area(){
int a = s*s;

BNM Institute Of Technology


System.out.println("Area of square:" + a);
}

class Triangle extends Rectangle {


int b, h;
Triangle(int b, int h){
this.b = b;
this.h = h;
}

void area(){
int a = (b*h)/2;
System.out.println("Area of triangle:" + a);
}
}

class Calculation {
public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter length and width of Rectangle:");


int l = sc.nextInt();
int w = sc.nextInt();
Rectangle ob1 = new Rectangle(l, w);
ref = ob1;
ref.area();

System.out.println("Enter side of square:");


int s = sc.nextInt();

Page No: 38
Square ob2 = new Square(s);

ref = ob2;
ref.area();

ID: 23CSC25
System.out.println("Enter base and height of Traingle:");
int b = sc.nextInt();
int h = sc.nextInt();
Triangle ob3 = new Triangle(b, h);

ref = ob3;
ref.area();
}
}

2023-27-CSE-C
Execution Results - All test cases have succeeded!
Test Case - 1

User Output
Enter length and width of Rectangle:

BNM Institute Of Technology


10
7
Area of rectangle:70
Enter side of square:
8
Area of square:64
Enter base and height of Traingle:
15
9
Area of triangle:67
Exp. Name: Preventing inheritance using final
S.No: 17 Date: 2024-09-22
keyword

Aim:

Page No: 39
Write a Java program to prevent the inheritance using the final keyword. Create a class Figure using the keyword
final.

Create another class Square with two members and a method area and return the area of the square. Create a
class PreventInherit with the main method and print the value returned from the method of the area of the class

ID: 23CSC25
Square.

Note: Please don't change the package name.

Source Code:

q29645/PreventInherit.java

package q29645;
import java.util.*;

2023-27-CSE-C
final class Figure{
int side = 10;
int area(){
return 10*10;
}
}

BNM Institute Of Technology


class Square{
int s;
double a;
double area(int s){
this.s = s;
this.a = (double) s * s;
return a;
}
}

public class PreventInherit{


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

System.out.print("Enter the length of Square: ");


int s = sc.nextInt();

Square ob1 = new Square();


System.out.println("Inside Area of Square");
System.out.println("Area of Square is " + ob1.area(s));
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter the length of Square:
10

Page No: 40
Inside Area of Square
Area of Square is 100.0

Test Case - 2

ID: 23CSC25
User Output
Enter the length of Square:
7
Inside Area of Square
Area of Square is 49.0

2023-27-CSE-C
BNM Institute Of Technology
Exp. Name: Write a Java program to achieve
S.No: 18 Date: 2024-09-19
concept of Method Overriding

Aim:

Page No: 41
Assume there is a class called Bank with method calculateInterest(float principal, int time) .

Create sub-classes of Bank with names SBI , ICICI and AXIS and override the
calculateInterest(float principal, int time) method.

ID: 23CSC25
Create a constant of type float called INTEREST_RATE in classes SBI , ICICI and AXIS with values 10.8 ,
11.6 and 12.3 respectively.

Use the formula (principal * INTEREST_RATE * time) / 100 to calculate the interest for given principal and
time and return the value as float in the overriden method.

For example, if the two arguments passed to the main method are 1000 and 5, (principal and time) below is the
expected output:

SBI rate of interest = 540.0


ICICI rate of interest = 580.0

2023-27-CSE-C
AXIS rate of interest = 615.0

Note: Please don't change the package name.

BNM Institute Of Technology


Source Code:

q11271/TestOverriding.java
package q11271;
class Bank {
float calculateInterest(float principal, int time) {
return 0;
}

Page No: 42
}

//complete the below code..


class SBI extends Bank{
final float INTEREST_RATE = 10.8f;

ID: 23CSC25
float calculateInterest(float principal, int time){
return (principal * INTEREST_RATE * time)/100;
}

}
class ICICI extends Bank{
final float INTEREST_RATE = 11.6f;
float calculateInterest(float principal, int time){
return (principal * INTEREST_RATE * time)/100;
}

2023-27-CSE-C
class AXIS extends Bank{
final float INTEREST_RATE = 12.3f;
float calculateInterest(float principal, int time){
return (principal * INTEREST_RATE * time)/100;
}

BNM Institute Of Technology


}

public class TestOverriding {


public static void main(String[] args) {
Bank sbiBank = new SBI();
Bank iciciBank = new ICICI();
Bank axisBank = new AXIS();
float principal = Float.parseFloat(args[0]);
int time = Integer.parseInt(args[1]);
System.out.println("SBI rate of interest = " +
sbiBank.calculateInterest(principal, time));
System.out.println("ICICI rate of interest = " +
iciciBank.calculateInterest(principal, time));
System.out.println("AXIS rate of interest = " +
axisBank.calculateInterest(principal, time));
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
SBI rate of interest = 1804.9608
ICICI rate of interest = 1938.6616
AXIS rate of interest = 2055.65

Test Case - 2

User Output

Page No: 43
SBI rate of interest = 540.0
ICICI rate of interest = 580.0
AXIS rate of interest = 615.0

ID: 23CSC25
Test Case - 3

User Output
SBI rate of interest = 2149.3447
ICICI rate of interest = 2308.5554
AXIS rate of interest = 2447.8647

Test Case - 4

User Output

2023-27-CSE-C
SBI rate of interest = 648.0
ICICI rate of interest = 696.0
AXIS rate of interest = 738.0

Test Case - 5

BNM Institute Of Technology


User Output
SBI rate of interest = 75600.0
ICICI rate of interest = 81200.0
AXIS rate of interest = 86100.0
Exp. Name: Write a Java program to implement
S.No: 19 Date: 2024-09-20
Method overloading

Aim:

Page No: 44
Write a Java program with a class name Addition with the methods add(int, int) , add(int, float) ,
add(float, float) and add(float, double, double) to add values of different argument types.

Write the main(String[]) method within the class and assume that it will always receive a total of 6 command line

ID: 23CSC25
arguments at least, such that the first 2 are int, next 2 are float and the last 2 are of type double.

If the main() is provided with arguments : 1, 2, 1.5f, 2.5f, 1.0, 2.0 then the program should print the output as:

Sum of 1 and 2 : 3
Sum of 1.5 and 2.5 : 4.0
Sum of 2 and 2.5 : 4.5
Sum of 1.5, 1.0 and 2.0 : 4.5

Note: Please don't change the package name.

2023-27-CSE-C
Source Code:

q11266/Addition.java

BNM Institute Of Technology


package q11266;
public class Addition{
static int add(int a, int b){
return a + b;
}

Page No: 45
static float add(int a, float b){
return a + b;
}

ID: 23CSC25
static float add(float a, float b){
return a + b;
}

static double add(float a, double b, double c){


return a + b + c;
}

public static void main(String[] args){


int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
float c = Float.parseFloat(args[2]);

2023-27-CSE-C
float d = Float.parseFloat(args[3]);
double e = Double.parseDouble(args[4]);
double f = Double.parseDouble(args[5]);

System.out.println("Sum of " + a + " and " + b + " : " + add(a, b));


System.out.println("Sum of " + c + " and " + d + " : " + add(c, d));

BNM Institute Of Technology


System.out.println("Sum of " + b + " and " + d + " : " + add(b, d));
System.out.println("Sum of " + c + ", " + e + " and " + f + " : " + add(c,
e, f));
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Sum of 2 and 1 : 3
Sum of 5.0 and 3.6 : 8.6
Sum of 1 and 3.6 : 4.6
Sum of 5.0, 9.2 and 5.26 : 19.46
S.No: 20 Exp. Name: A Book information Date: 2024-09-22

Aim:
Create a class called Book to represent a book. A Book should include four pieces of information as instance

Page No: 46
variables‐a book name, an ISBN number, an author name, and a publisher. Your class should have a constructor
that initializes the four instance variables. Provide a mutator method and accessor method (query method) for
each instance variable. In addition, provide a method named getBookInfo that returns the description of the
book as a String (the description should include all the information about the book). You should use this keyword
in member methods and constructors. Write a test application named BookTest to create an array of objects for

ID: 23CSC25
N elements for class Book to demonstrate the class Book's capabilities.
Source Code:

BookTest.java

2023-27-CSE-C
BNM Institute Of Technology
import java.util.Scanner;

class Book {
String Book, Auth, Pub;
int ISBN;

Page No: 47
Book(String Book, String Auth, String Pub, int ISBN){
this.Book = Book;
this.Auth = Auth;
this.ISBN = ISBN;

ID: 23CSC25
this.Pub = Pub;
}

void setBook(String Book){


this.Book = Book;
}

void setAuth(String Auth){


this.Auth = Auth;
}

void setPub(String Pub){

2023-27-CSE-C
this.Pub = Pub;
}

void setISBN(int ISBN){


this.ISBN = ISBN;
}

BNM Institute Of Technology


String getBook(){
return this.Book;
}

String Auth(){
return this.Auth;
}

String getPub(){
return this.Pub;
}

int getISBN(){
return this.ISBN;
}

void getBookInfo(){
System.out.println("Book Name: " + this.Book);
System.out.println("ISBN: " + this.ISBN);
System.out.println("Author Name: " + this.Auth);
System.out.println("Publisher: " + this.Pub);
}
}

public class BookTest {


public static void main(String[] args){
System.out.print("Number of books (N): ");
int N = sc.nextInt();
sc.nextLine();
Book[] arr = new Book[N];

Page No: 48
for(int i = 0; i < N; i++){
System.out.println("Details for Book " + (i+1) + ":");

System.out.print("Book Name: ");


String n = sc.nextLine();

ID: 23CSC25
System.out.print("ISBN: ");
int I = sc.nextInt();
sc.nextLine();
System.out.print("Author Name: ");
String a = sc.nextLine();
System.out.print("Publisher: ");
String p = sc.nextLine();

arr[i] = new Book(n, a, p, I);


}

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

2023-27-CSE-C
System.out.println("Book " + (i+1) + " Information:");
arr[i].getBookInfo();
}

BNM Institute Of Technology


}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Number of books (N):
3
Details for Book 1:
Book Name:
Atomic Habits
ISBN:
1232
Author Name:
John Clear
Publisher:
ANM publications
Details for Book 2:
Book Name:
One Arranged Murder
ISBN:
8596
Author Name:
Chetan Bhagat
Publisher:
Google publishers
Details for Book 3:

Page No: 49
Book Name:
I too had a success
ISBN:
1232

ID: 23CSC25
Author Name:
Swathi Chilla
Publisher:
Suguna publishers
Book 1 Information:
Book Name: Atomic Habits
ISBN: 1232
Author Name: John Clear
Publisher: ANM publications
Book 2 Information:
Book Name: One Arranged Murder

2023-27-CSE-C
ISBN: 8596
Author Name: Chetan Bhagat
Publisher: Google publishers
Book 3 Information:
Book Name: I too had a success

BNM Institute Of Technology


ISBN: 1232
Author Name: Swathi Chilla
Publisher: Suguna publishers
Exp. Name: Even number or not Using a Functional
S.No: 21 Date: 2024-09-22
Interface

Aim:

Page No: 50
Write a Java Code to implement whether a given number is an even number or not Using a Functional Interface
Note: Functional Interface Consists of only one method
Source Code:

q18038/Main.java

ID: 23CSC25
package q18038;
import java.util.Scanner;
interface EvenChecker {
int check(int x);
}

public class Main {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


// Create a lambda expression to implement the EvenChecker functional interface

2023-27-CSE-C
int n = sc.nextInt();

EvenChecker evenChecker = (int x) -> x%2;

if (evenChecker.check(n) == 1){
System.out.println(n + " is an odd number");

BNM Institute Of Technology


}else{
System.out.println(n + " is an even number");
}

}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
5 is an odd number

Test Case - 2

User Output
16
16 is an even number
S.No: 22 Exp. Name: Write the code Date: 2024-09-22

Aim:
Write a Java Program to Create an interface Drawable with a method draw() that prints "Drawing a square."

Page No: 51
Note: Here user will Instantiate n Square objects and call accordingly.
Source Code:

q18037/Main.java

ID: 23CSC25
package q18037;
import java.util.*;

interface Drawable{
void draw();
}

class Square implements Drawable {


public void draw(){
System.out.println("Drawing a square.");
}
}

2023-27-CSE-C
public class Main {
public static void main(String[] args) {
// Create an array of Drawable objects
Scanner s = new Scanner(System.in);
int n = s.nextInt();
Drawable[] squares = new Square[n];

BNM Institute Of Technology


s.nextLine();

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


squares[i] = new Square();
}
for(int i = 0; i < n; i++){
squares[i].draw();
}
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
2
Drawing a square.
Drawing a square.

Test Case - 2

User Output
Drawing a square.
Drawing a square.
Drawing a square.
Drawing a square.
Drawing a square.

Page No: 52
ID: 23CSC25
2023-27-CSE-C
BNM Institute Of Technology
S.No: 23 Exp. Name: Calculator interface Date: 2024-09-22

Aim:
Design an interface named Calculator that includes essential methods of type double for basic arithmetic

Page No: 53
operations, namely add, subtract, multiply, and divide. Also, create a class BasicCalculator that implements the
interface and overrides each method in the interface with the required functionality.

Note:
The main class has been provided to you in the editor.

ID: 23CSC25
Sample input:
5
10
Sample output:
Addition: 15
Subtraction: -5
Multiplication: 50
Division: 0
Source Code:

q18023/Calc.java

2023-27-CSE-C
BNM Institute Of Technology
package q18023;
import java.util.*;

interface Calculator{
double add(double a, double b);

Page No: 54
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
}

ID: 23CSC25
class BasicCalculator implements Calculator {
public double add(double a, double b){
return a + b;
}

public double subtract(double a, double b){


return a - b;
}

public double multiply(double a, double b){


return a * b;
}

2023-27-CSE-C
public double divide(double a, double b){
return a / b;
}
}
public class Calc {

BNM Institute Of Technology


public static void main(String[] args) {
Calculator calculator = new BasicCalculator();
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
double result1 = calculator.add(a, b);
double result2 = calculator.subtract(a, b);
double result3 = calculator.multiply(a, b);
double result4 = calculator.divide(a, b);

System.out.println("Addition: " + result1);


System.out.println("Subtraction: " + result2);
System.out.println("Multiplication: " + result3);
System.out.println("Division: " + result4);

}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
5
Addition: 15.0
Subtraction: -5.0
Multiplication: 50.0
Division: 0.5

Page No: 55
Test Case - 2

User Output
10

ID: 23CSC25
20
Addition: 30.0
Subtraction: -10.0
Multiplication: 200.0
Division: 0.5

2023-27-CSE-C
BNM Institute Of Technology
Exp. Name: Exception Handling in Division and
S.No: 24 Date: 2024-09-22
Array Indexing

Aim:

Page No: 56
You are tasked with implementing a program that performs division and array indexing, handling exceptions for
potential errors. The program takes user input for the number of test cases and performs the specified operations
for each case.

Input:

ID: 23CSC25
• The first line contains an integer n (1 ≤ n ≤ 100), representing the number of test cases.
• For each test case, there are two integers num1 and num2 on a new line, where num1 represents the
divisor for division, and num2 represents the index for array access.

Array Information:
The array used in each test case consists of three elements: 1, 2, and 3.

 utput::
O
For each test case, the program should output the following:
• If division is successful, print "Result of division: result," where "result" is the result of dividing 10 by num1.
• If array indexing is successful, print "Element at index num2: element," where "element" is the value at the
specified index in the array.

2023-27-CSE-C
• If any exception occurs during the operations, catch and handle it, printing an error message in the format
"Error: error_message."

Constraints:
• The divisor (num1) for division is an integer (-10^9 ≤ num1 ≤ 10^9), and it should not be zero.
• The index (num2) for array access is an integer (0 ≤ num2 < array_length).

BNM Institute Of Technology


• The length of the array is fixed at 3 for each test case.
• The program should handle exceptions using appropriate error messages for division by zero and array
index out of bounds.
• The input is well-formed, and you can assume that the given test cases will follow the specified format.

Note: Refer to the visible sample test cases for your reference
Source Code:

q18015/Basic.java
/* Partial code given for your reference */
package q18015;
import java.util.*;

public class Basic {

Page No: 57
static int[] arr = {1, 2, 3};

static void func(int a, int b) {


try {
try{

ID: 23CSC25
int A = divide(a);
System.out.println("Result of division: " + A);
}catch(ArithmeticException e){
System.out.println("Invalid input: " + e.getMessage());
return;
}

try{
int B = getElement(arr, b);
System.out.println("Element at index " + b + ": " + B);
}catch (IndexOutOfBoundsException e){
System.out.println("Invalid input: " + e.getMessage());

2023-27-CSE-C
}
}catch(IllegalArgumentException e){
System.out.println("Error: " + e.getMessage());
}
}

BNM Institute Of Technology


static int divide(int a) throws ArithmeticException{
if(a == 0){
throw new ArithmeticException("Cannot divide by zero");
}else{
return 10/a;
}
}

static int getElement(int[] arr, int index) throws IndexOutOfBoundsException {


if(index > 2){
throw new IndexOutOfBoundsException("Array index out of bounds");
}else{
return arr[index];
}
}

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 0; i < n; i++) {
if(i==0){in.nextLine();}

try{

String[] s = in.nextLine().split("\\s");
int n1 = Integer.parseInt(s[0]);
int n2 = Integer.parseInt(s[1]);
}catch(IllegalArgumentException e){
System.out.println("Error: " + e.getMessage());
}
}
in.close();

Page No: 58
}
}

ID: 23CSC25
Execution Results - All test cases have succeeded!
Test Case - 1

User Output
2
12
Result of division: 10
Element at index 2: 3
34

2023-27-CSE-C
Result of division: 3
Invalid input: Array index out of bounds

Test Case - 2

User Output

BNM Institute Of Technology


3
21
Result of division: 5
Element at index 1: 2
01
Invalid input: Cannot divide by zero
23
Result of division: 5
Invalid input: Array index out of bounds
Exp. Name: Interface - Area of a rectangle and
S.No: 25 Date: 2024-09-30
circle

Aim:

Page No: 59
Define an interface called Shape with two abstract methods: void getData() and void Display().

Implement a class called Rectangle that implements the Shape interface. This class should have to:
• Implement the getData method to read the length and width of the rectangle from the user.
• Implement the Display method to calculate and display the area of the rectangle.

ID: 23CSC25
Implement a class called Circle that also implements the Shape interface. This class should have to:
• Implement the getData method to read the radius of the circle from the user.
• Implement the Display method to calculate and display the area of the circle.

Note:
• The main function is provided to you in the editor.
• Take the pi value as 3.14.
Source Code:

AreaOfShape.java

2023-27-CSE-C
BNM Institute Of Technology
import java.util.*;
interface Shape {
void getData();
void Display();
}

Page No: 60
class AreaOfShape {
public static void main(String arg[]) {
Circle c = new Circle();
c.getData();

ID: 23CSC25
c.Display();
Rectangle r = new Rectangle();
r.getData();
r.Display();
}
}

class Circle implements Shape{


double r;

public void getData(){


Scanner sc = new Scanner(System.in);

2023-27-CSE-C
r = sc.nextDouble();
}

public void Display(){


double a = r*3.14*r;
System.out.println("Area of Circle: " + a);

BNM Institute Of Technology


}
}

class Rectangle implements Shape{


double l, b;

public void getData(){


Scanner sc = new Scanner(System.in);
l = sc.nextDouble();
b = sc.nextDouble();
}

public void Display(){


double a = l * b;
System.out.println("Area of Rectangle: " + a);
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
10
Area of Circle: 314.0
12 13
Area of Rectangle: 156.0

Test Case - 2

Page No: 61
User Output
7
Area of Circle: 153.86
23.2 12.03

ID: 23CSC25
Area of Rectangle: 279.096

2023-27-CSE-C
BNM Institute Of Technology
S.No: 26 Exp. Name: Write the code Date: 2024-09-22

Aim:
Develop a Java program that takes two integers as input and print sum, handles an InputMismatchException if the

Page No: 62
input is not an integer.
Source Code:

q18033/InputMismatchExceptionExample.java

ID: 23CSC25
package q18033;
import java.util.*;

public class InputMismatchExceptionExample{


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

try {
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a+b);
} catch (InputMismatchException e) {

2023-27-CSE-C
// Handle the InputMismatchException
System.out.println("Error: Input must be valid integers.");
}
}
}

BNM Institute Of Technology


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
10
20
30

Test Case - 2

User Output
11
5a
Error: Input must be valid integers.

Test Case - 3

User Output
g2
Error: Input must be valid integers.
S.No: 27 Exp. Name: Throw an Exception Date: 2024-09-22

Aim:
Modify the withdraw() method of the Account class such that this method should throw “Insufficient Fund

Page No: 63
Exception” if the account holder tries to withdraw an amount that leads to a condition where the current balance
becomes less than the minimum balance otherwise allow the account holder to withdraw and update the balance
accordingly. Prompt the user to enter account number (n), initial balance (b), withdrawal amount (w)
Note:
• Consider the MINIMUM_BALANCE as 100.0

ID: 23CSC25
Constraint:
• 1 ≤ n ≤ 1010
• 0 ≤ b ≤ 107
• 0 ≤ w ≤ 107

Input Format:
• The first line of the input consists of the account number (integer).
• The next line of input consists of the initial balance (double).
• The next line of the input consists of the withdrawal amount (double).

Output Format:

2023-27-CSE-C
• If there are insufficient funds, the output displays the error message as shown in displayed test cases.
• Otherwise, the first line represents the withdrawn amount and the second line represents the new balance.
Source Code:

q17209/Main.java

BNM Institute Of Technology


package q17209;
import java.util.*;

class InsufficientFundException extends Exception{


InsufficientFundException(String message){

Page No: 64
super(message);
}
}

class BankAccount{

ID: 23CSC25
int account;
double balance;
final double MINIMUM_BALANCE = 100.0;

BankAccount(int account, double balance){


this.account = account;
this.balance = balance;
}

void withdraw(double amount) throws InsufficientFundException{


if ((balance - amount) < MINIMUM_BALANCE){
throw new InsufficientFundException("Error:Insufficient Fund

2023-27-CSE-C
Exception");
}else{
balance -= amount;
System.out.println("Withdrawn:" + amount);
System.out.println("New Balance:" + balance);
}

BNM Institute Of Technology


}
}

public class Main{


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

System.out.print("Enter account number:");


int acc = sc.nextInt();
sc.nextLine();
System.out.print("Enter initial balance:");
double bal = sc.nextDouble();
sc.nextLine();
System.out.print("Enter withdrawal amount:");
double wit = sc.nextDouble();
sc.nextLine();

BankAccount account = new BankAccount(acc, bal);

try{
account.withdraw(wit);
}catch(InsufficientFundException e){
System.out.println(e.getMessage());
}
}
}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 65
Enter account number:
568459
Enter initial balance:
50000

ID: 23CSC25
Enter withdrawal amount:
600000
Error:Insufficient Fund Exception

Test Case - 2

User Output
Enter account number:
698744165
Enter initial balance:

2023-27-CSE-C
600000
Enter withdrawal amount:
1000
Withdrawn:1000.0
New Balance:599000.0

BNM Institute Of Technology


S.No: 28 Exp. Name: Handling exceptions - String to integer Date: 2024-09-22

Aim:
Write a Java program that takes the string from the user. The program attempts to convert the user-given string

Page No: 66
to an integer, displays the twice of the integer and handles a NumberFormatException if the string is not a valid
integer.
Source Code:

q18190/StringToInt.java

ID: 23CSC25
package q18190;
import java.util.Scanner;
public class StringToInt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
String input = scanner.nextLine();
int num = Integer.parseInt(input);
System.out.println(num*2);
} catch (NumberFormatException e) {

2023-27-CSE-C
System.out.println("Error: The input is not a valid integer");
}
}
}

BNM Institute Of Technology


Execution Results - All test cases have succeeded!
Test Case - 1

User Output
10
20

Test Case - 2

User Output
23 2
Error: The input is not a valid integer

Test Case - 3

User Output
232
464
S.No: 29 Exp. Name: Customized Exception Date: 2024-09-22

Aim:
Write a Java program that takes the age as input from the user, creates an exception called InvalidAgeException,

Page No: 67
and throws it when the age is not within a valid range (i.e., between 0 and 150 years).
Source Code:

q18191/AgeBasic.java

ID: 23CSC25
package q18191;
import java.util.*;
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}

public class AgeBasic {


static void checkAge(int age) throws InvalidAgeException{
if(age < 0 || age > 150){
throw new InvalidAgeException("Invalid age");

2023-27-CSE-C
}else{
System.out.println("Valid age: " + age + " years");
}
}
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);

BNM Institute Of Technology


int age = sc.nextInt();
checkAge(age);
} catch (InvalidAgeException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
35
Valid age: 35 years

Test Case - 2

User Output
178
Error: Invalid age
-23
User Output

Error: Invalid age


Test Case - 3

BNM Institute Of Technology 2023-27-CSE-C ID: 23CSC25 Page No: 68


Exp. Name: Area of rectangle and circle using
S.No: 30 Date: 2024-09-22
interface

Aim:

Page No: 69
Write a Java program to find the area of the Rectangle and circle. Use Interface with the following instructions.
• Create interface Shape and declare functions getData() and Display()
• Implement Shape in Rectangle and Circle and override the function appropriately.

Note:

ID: 23CSC25
8. Print the output by rounding it to 1 decimal place.
9. Use PI = 3.14 for calculation.
Source Code:

Area.java

2023-27-CSE-C
BNM Institute Of Technology
import java.util.*;

interface Shape{
void getData();
void display();

Page No: 70
}

class Circle implements Shape{


double r, a;

ID: 23CSC25
public void getData(){
Scanner sc = new Scanner(System.in);
r = sc.nextDouble();
}

public void display(){


a = 3.14 * r * r;
System.out.printf("Area of Circle is %.1f\n", a);
}
}

class Rectangle implements Shape{

2023-27-CSE-C
double l, b, a;

public void getData(){


Scanner sc = new Scanner(System.in);
l = sc.nextDouble();
b = sc.nextDouble();

BNM Institute Of Technology


}

public void display(){


a = l * b;
System.out.printf("Area of Rectangle is %.1f\n", a);
}
}

class Area {
public static void main(String arg[]) {
Circle c = new Circle();
c.getData();
c.display();

Rectangle r = new Rectangle();


r.getData();
r.display();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
3
5

10
Area of Circle is 78.5

Area of Rectangle is 30.0

BNM Institute Of Technology 2023-27-CSE-C ID: 23CSC25 Page No: 71


S.No: 31 Exp. Name: Synchronizing threads Date: 2024-10-01

Aim:
Write a Java program on synchronizing threads.

Page No: 72
Note: Please don't change the package name.

Source Code:

ID: 23CSC25
q29800/Synch1.java

2023-27-CSE-C
BNM Institute Of Technology
package q29800;

class printer{
final Object lock = new Object();
int count = 0;

Page No: 73
public void printH(){
synchronized(lock){
System.out.println("[Hello]");
count++;

ID: 23CSC25
lock.notifyAll();
}
}

public void printW(){


synchronized(lock){
while (count < 1){
try{
lock.wait();
}catch(InterruptedException e){
System.out.println("Error: " + e.getMessage());
}

2023-27-CSE-C
}
System.out.println("[World]");
count++;
lock.notifyAll();
}
}

BNM Institute Of Technology


public void printS(){
synchronized(lock){
while (count < 2){
try{
lock.wait();
}catch(InterruptedException e){
System.out.println("Error: " + e.getMessage());
}
}
System.out.println("[Synchronized]");
count++;
lock.notifyAll();
}
}
}

public class Synch1{


public static void main(String[] args){

printer print = new printer();

Thread t1 = new Thread(print::printH);


Thread t2 = new Thread(print::printW);
Thread t3 = new Thread(print::printS);

t1.start();
try{
t1.join();
t2.join();
t3.join();

Page No: 74
}catch(Exception e){
System.out.println("Error: " + e);
}
}
}

ID: 23CSC25
Execution Results - All test cases have succeeded!
Test Case - 1

User Output
[Hello]
[World]
[Synchronized]

2023-27-CSE-C
BNM Institute Of Technology
Exp. Name: Print even and odd numbers using
S.No: 32 Date: 2024-10-03
threads

Aim:

Page No: 75
Define two threads such that one thread should print even numbers and another thread should print odd
numbers.

Note: Add a sleep duration of 100 for both threads and refer to the visible test cases for input and output
formats

ID: 23CSC25
Source Code:

q17210/Main.java

2023-27-CSE-C
BNM Institute Of Technology
package q17210;
import java.util.*;

class evep extends Thread{


int max;

Page No: 76
evep(int max){
this.max = max;
}

@Override

ID: 23CSC25
public void run(){
for(int i = 2; i <= max; i += 2){
System.out.println("Even:" + i);
}
}
}

class oddp extends Thread{


int max;

oddp(int max){
this.max = max;

2023-27-CSE-C
}

@Override
public void run(){
for(int i = 1; i <= max; i+=2){
System.out.println("Odd:" + i);

BNM Institute Of Technology


}
}
}

public class Main{


public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the maximum even number:");
int e = sc.nextInt();
System.out.print("Enter the maximum odd number:");
int o = sc.nextInt();

Thread t1 = new evep(e);


Thread t2 = new oddp(o);

t1.start();
t2.start();

try{
t1.join();
t2.join();
}catch(Exception ex){
System.out.println("Error: " + ex.getMessage());
}
}
}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 77
Enter the maximum even number:
24
Enter the maximum odd number:
13

ID: 23CSC25
Odd:1
Even:2
Odd:3
Even:4
Odd:5
Even:6
Odd:7
Even:8
Odd:9
Even:10
Odd:11

2023-27-CSE-C
Even:12
Odd:13
Even:14
Even:16
Even:18
Even:20

BNM Institute Of Technology


Even:22
Even:24

Test Case - 2

User Output
Enter the maximum even number:
10
Enter the maximum odd number:
9
Even:2
Odd:1
Even:4
Odd:3
Odd:5
Even:6
Odd:7
Even:8
Odd:9
Even:10
Exp. Name: Print all numbers below N that are both
S.No: 33 Date: 2024-10-09
prime and Fibonacci number

Aim:

Page No: 78
Write a multi-threaded Java program to print all numbers below N that are both prime and Fibonacci number
(some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers below N and writes them into
a pipe. Design another thread that generates Fibonacci numbers and writes them to another pipe. The main
thread should read both the pipes to identify numbers common to both.
Source Code:

ID: 23CSC25
Main.java

2023-27-CSE-C
BNM Institute Of Technology
import java.io.*;
import java.util.*;
class PrimeThread extends Thread {

private DataOutputStream out;

Page No: 79
private int N;

public PrimeThread(int N, PipedOutputStream out){


this.N = N;
this.out = new DataOutputStream(out);

ID: 23CSC25
}

private boolean isPrime(int x){


if(x <= 1) return false;

for(int i = 2; i <= Math.sqrt(x); i++){


if (x % i == 0){
return false;
}
}
return true;
}

2023-27-CSE-C
@Override
public void run(){
try{
for(int i = 2; i < N; i++){
if(isPrime(i)){

BNM Institute Of Technology


out.writeInt(i);
}
}
out.writeInt(-1);
out.close();
}catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
}
}

class FibonacciThread extends Thread {

private DataOutputStream out;


private int N;

public FibonacciThread(int N, PipedOutputStream out){


this.N = N;
this.out = new DataOutputStream(out);
}

@Override
public void run(){
try{
int a = 0, b = 1;
while(a < N){
out.writeInt(a);
b = c;
}
out.writeInt(-1);
out.close();
}catch(IOException ex){

Page No: 80
System.out.println("Error: " + ex.getMessage());
}
}

ID: 23CSC25
public class Main {

public static void main(String[] args) throws IOException, InterruptedException{

Scanner sc = new Scanner(System.in);


System.out.print("Enter the value of N: ");
int N = sc.nextInt();

PipedOutputStream primeOut = new PipedOutputStream();


PipedInputStream primeIn = new PipedInputStream(primeOut);

2023-27-CSE-C
PipedOutputStream fibOut = new PipedOutputStream();
PipedInputStream fibIn = new PipedInputStream(fibOut);

PrimeThread primeThread = new PrimeThread(N, primeOut);


FibonacciThread fibThread = new FibonacciThread(N, fibOut);

BNM Institute Of Technology


primeThread.start();
fibThread.start();

List<Integer> primeNumbers = new ArrayList<>();


List<Integer> fibNumbers = new ArrayList<>();

Thread primeReader = new Thread(() -> {


try{
DataInputStream primeStream = new DataInputStream(primeIn);
int num;
while((num = primeStream.readInt()) != -1){
primeNumbers.add(num);
}
}catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
});

Thread fibReader = new Thread(() -> {


try{
DataInputStream fibStream = new DataInputStream(fibIn);
int num;
while((num = fibStream.readInt()) != -1){
fibNumbers.add(num);
}
}catch(IOException e){
System.out.println("Error: " + e.getMessage());
System.out.println("Numbers that are both prime and Fibonacci:");

primeReader.start();
fibReader.start();

Page No: 81
primeThread.join();
fibThread.join();
primeReader.join();
fibReader.join();

ID: 23CSC25
List<Integer> common = new ArrayList<>();
for(int prime: primeNumbers){
if(fibNumbers.contains(prime)){
common.add(prime);
}
}

System.out.println(common);
}
}

2023-27-CSE-C
Execution Results - All test cases have succeeded!
Test Case - 1

BNM Institute Of Technology


User Output
Enter the value of N:
10
Numbers that are both prime and Fibonacci:
[2, 3, 5]

Test Case - 2

User Output
Enter the value of N:
1000
Numbers that are both prime and Fibonacci:
[2, 3, 5, 13, 89, 233]
Exp. Name: Implement a multi-threaded
S.No: 34 Date: 2024-11-17
application that has three threads

Aim:

Page No: 82
Write a Java program that implements a multi-threaded application that has three threads. The first thread
generates a random integer every 1 second and if the value is even, the second thread computes the square of
the number and prints. If the value is odd, the third thread will print the value of the cube of the number.

Note: Set the seed value to 50 for consistency

ID: 23CSC25
Source Code:

ClassMthread.java

2023-27-CSE-C
BNM Institute Of Technology
import java.util.Random;
class RandomNumberThread extends Thread {
public void run() {
Random random = new Random();
random.setSeed(50);

Page No: 83
for(int i = 0; i < 3; i++){
int num = random.nextInt(100);
System.out.println("Random Integer generated : " + num);

ID: 23CSC25
if(num % 2 == 0){
SquareThread squareThread = new SquareThread(num);
squareThread.start();
}else{
CubeThread cubeThread = new CubeThread(num);
cubeThread.start();
}
}
}
}

class SquareThread extends Thread {

2023-27-CSE-C
private int num;
SquareThread(int num){
this.num = num;
}

BNM Institute Of Technology


public void run(){
System.out.println("Square of " + num + " = " + (num * num));
}

class CubeThread extends Thread {

private int num;


CubeThread(int num){
this.num = num;
}

public void run(){


System.out.println("Cube of " + num + " = " + (num*num*num));
}
}

public class ClassMthread {

public static void main(String[] args){


RandomNumberThread randomThread = new RandomNumberThread();
randomThread.start();
}

}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 84
Random Integer generated : 17
Cube of 17 = 4913
Random Integer generated : 88
Square of 88 = 7744
Random Integer generated : 93

ID: 23CSC25
Cube of 93 = 804357

2023-27-CSE-C
BNM Institute Of Technology
S.No: 35 Exp. Name: Suspending and resuming threads. Date: 2024-11-14

Aim:
Write a Java program on suspend and resume threads.

Page No: 85
Note: Please don't change the package name.

Source Code:

ID: 23CSC25
q29801/SuspendResume.java

2023-27-CSE-C
BNM Institute Of Technology
package q29801;

class Custom extends Thread{


String s;
Custom(String s){

Page No: 86
this.s = s;
}

@Override
public void run(){

ID: 23CSC25
System.out.printf("New thread: Thread[%s,5,main]\n", s);
for(int i = 15; i >= 1; i--){
System.out.printf("%s: %d\n", s, i);
}
System.out.printf("%s exiting.\n", s);
}
}

public class SuspendResume{


public static void main(String[] args){
Custom t1 = new Custom("One");
Custom t2 = new Custom("Two");

2023-27-CSE-C
t1.start();
t2.start();

System.out.println("Suspending thread One");


t1.suspend();

BNM Institute Of Technology


System.out.println("Suspending thread Two");
t2.suspend();

System.out.println("Waiting for threads to finish.");

System.out.println("Resuming thread One");


t1.resume();
System.out.println("Resuming thread Two");
t2.resume();

/*
try{
Thread.sleep(1000);
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
System.out.println("Waiting for threads to finish.");
*/

try{
//System.out.println("Waiting for threads to finish.");
t1.join();
t2.join();
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}

System.out.printf("Main thread exiting.\n");


}
}

Page No: 87
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

ID: 23CSC25
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
Two: 15
One: 15
Two: 14
One: 14
Suspending thread One
Two: 13
Resuming thread One
One: 13

2023-27-CSE-C
Suspending thread Two
One: 12
Resuming thread Two
Waiting for threads to finish.
Two: 12
One: 11

BNM Institute Of Technology


Two: 11
One: 10
Two: 10
One: 9
Two: 9
One: 8
Two: 8
One: 7
Two: 7
One: 6
Two: 6
One: 5
Two: 5
One: 4
Two: 4
One: 3
Two: 3
One: 2
Two: 2
One: 1
Two: 1
One exiting.
Two exiting.
Main thread exiting.
Exp. Name: Printing tables using synchronization
S.No: 36 Date: 2024-10-09
and threads

Aim:

Page No: 88
Create a Java program that utilizes multi-threading to generate multiplication tables.

Define a class TablePrinter that implements the Runnable interface. This class should have the following
characteristics:
• It should have a private instance variable tableNumber to represent the multiplication table number it's

ID: 23CSC25
responsible for.
• Implement the run() method to generate and print the multiplication table for its assigned tableNumber
from 1 to 10. Ensure there's a small delay (100 milliseconds) between each multiplication operation for
better visualization.

In the Main class:


• Create an instance of Scanner to take user input.
• Prompt the user to enter the number n of multiplication tables they want to generate.
• Create an array of Thread objects to manage the threads that will run the TablePrinter instances.
• Start all the threads to begin generating the tables concurrently.
• Use the join() method to wait for all threads to finish executing before proceeding.

2023-27-CSE-C
Ensure that the program handles any potential exceptions that might occur during execution, such as
InterruptedException.

Constraint:
• 0 ≤ n ≤ 10

BNM Institute Of Technology


Input Format:
• The input consists of a number (integer).

Output Format:
• The output represents the tables as per the input.
Source Code:

q18198/Main.java
package q18198;
import java.util.Scanner;

class TablePrinter implements Runnable {


private int tableNumber;

Page No: 89
public TablePrinter(int tableNumber) {
this.tableNumber = tableNumber;
}

ID: 23CSC25
@Override
public void run(){
for(int i = 1; i <= 10; i++){
System.out.println(tableNumber + " * " + i + " = " + (tableNumber *
i));

/*
try{
Thread.sleep(100);
}catch(InterruptedException e){
System.out.println("Error : " + e.getMessage());
}

2023-27-CSE-C
*/
}
}

BNM Institute Of Technology


public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of tables:");
int numTables = scanner.nextInt();
Thread[] threads = new Thread[numTables];

for(int i = 1; i <= numTables; i++){


Runnable r = new TablePrinter(i);
Thread t = new Thread(r);
threads[i-1] = t;
t.start();
}

try{
for(int i = 0; i < threads.length; i++){
threads[i].join();
}
}catch(InterruptedException e){
System.out.println("Error: " + e.getMessage());
}

}
}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 90
Enter the number of tables:
2
1 * 1 = 1
2 * 1 = 2

ID: 23CSC25
1 * 2 = 2
2 * 2 = 4
1 * 3 = 3
2 * 3 = 6
1 * 4 = 4
2 * 4 = 8
1 * 5 = 5
2 * 5 = 10
1 * 6 = 6
2 * 6 = 12
1 * 7 = 7

2023-27-CSE-C
2 * 7 = 14
1 * 8 = 8
2 * 8 = 16
1 * 9 = 9
2 * 9 = 18
1 * 10 = 10

BNM Institute Of Technology


2 * 10 = 20

Test Case - 2

User Output
Enter the number of tables:
3
3 * 1 = 3
2 * 1 = 2
1 * 1 = 1
3 * 2 = 6
2 * 2 = 4
1 * 2 = 2
3 * 3 = 9
2 * 3 = 6
1 * 3 = 3
3 * 4 = 12
2 * 4 = 8
1 * 4 = 4
3 * 5 = 15
2 * 5 = 10
1 * 5 = 5
3 * 6 = 18
2 * 6 = 12
1 * 6 = 6
3 * 7 = 21
2 * 7 = 14
1 * 7 = 7
2 * 8 = 16
1 * 8 = 8

Page No: 91
3 * 8 = 24
2 * 9 = 18
1 * 9 = 9
3 * 9 = 27
2 * 10 = 20

ID: 23CSC25
1 * 10 = 10
3 * 10 = 30

2023-27-CSE-C
BNM Institute Of Technology
S.No: 37 Exp. Name: Producer Consumer Problem Date: 2024-11-14

Aim:
Write a Java program that correctly implements the producer – consumer problemusing the concept of inter

Page No: 92
thread communication.
Source Code:

q36394/ProdCons.java

ID: 23CSC25
2023-27-CSE-C
BNM Institute Of Technology
package q36394;

import java.util.*;

/*

Page No: 93
package q36394;
class ProdCons
{
public static void main(String args[])
{

ID: 23CSC25
Product p=new Product();
new Producer(p);
new Consumer(p);
}
}
*/

class ProdCons{
public static void main(String[] args){
Product product = new Product(5);
Thread producer = new Thread(new Producer(product));
Thread consumer = new Thread(new Consumer(product));

2023-27-CSE-C
producer.start();
consumer.start();
}
}

/*

BNM Institute Of Technology


class Product
{
*/

class Product{
Queue<Integer> q;
Integer capacity;

Product(Integer capacity){
q = new LinkedList<>();
this.capacity = capacity;
}

public void publish(Integer msg){


if(q.size() == capacity){
return;
}
q.add(msg);
System.out.println("PUT:" + msg);
}

public void consume(){


if(q.size() == 0){
return;
}
Integer msg = q.poll();
System.out.println("GET:" + msg);
/*
}
class Producer implements Runnable
{

Page No: 94
*/

class Producer implements Runnable{


Product product;
public Producer(Product product){

ID: 23CSC25
this.product = product;
}

@Override
public void run(){
Integer i = 0;
try{
while(i<=5){
product.publish(i);
i++;
}
}catch(Exception e){

2023-27-CSE-C
System.out.println("Error: " + e.getMessage());
}
}
}

/*

BNM Institute Of Technology


}
class Consumer implements Runnable
{
*/

class Consumer implements Runnable{


Product product;
public Consumer(Product product){
this.product = product;
}

@Override
public void run(){
Integer i = 0;
try{
while(i<=5){
product.consume();
i++;
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
}
}

/*
}
*/
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 95
PUT:0
GET:0
PUT:1
GET:1
PUT:2

ID: 23CSC25
GET:2
PUT:3
GET:3
PUT:4
GET:4
PUT:5
GET:5

2023-27-CSE-C
BNM Institute Of Technology
S.No: 38 Exp. Name: Assigning priority to threads Date: 2024-09-30

Aim:
Write a Java program on assigning priority to threads.

Page No: 96
Note: Please don't change the package name.

Source Code:

ID: 23CSC25
q29797/priority.java

package q29797;

class custom extends Thread{


String s = new String();
Integer p;
custom(String s, Integer p){
this.s = s;
this.p = p;
}

2023-27-CSE-C
@Override
public void run(){
System.out.printf("Thread name : Thread%s\n", s);
System.out.printf("Thread Priority : %d\n", p);
}
}

BNM Institute Of Technology


public class priority{
public static void main(String[] args){

System.out.printf("Main Thread : Thread[main,10,main]\n");


Thread main = Thread.currentThread();
main.setPriority(Thread.MAX_PRIORITY);

Thread t1 = new custom("1", 7);


Thread t2 = new custom("2", 3);

t1.setPriority(7);
t2.setPriority(3);

t1.run();
t2.run();
System.out.printf("Main Thread Priority : 10\n");

try{
t1.join();
t2.join();
}catch(Exception e){
System.out.println("Error: " + e);
}
}
}
Execution Results - All test cases have succeeded!
Test Case - 1

User Output

Page No: 97
Thread name : Thread1
Main Thread : Thread[main,10,main]
Thread name : Thread2
Thread Priority : 7
Main Thread Priority : 10

ID: 23CSC25
Thread Priority : 3

2023-27-CSE-C
BNM Institute Of Technology
S.No: 39 Exp. Name: Creating multiple threads Date: 2024-09-30

Aim:
Write a Java program on creating multiple threads.

Page No: 98
Note: Please don't change the package name.

Source Code:

ID: 23CSC25
q29796/MultiThreadDemo.java

package q29796;

class custom extends Thread{


String s = new String();
custom(String s){
this.s = s;
}

@Override

2023-27-CSE-C
public void run(){
System.out.printf("New thread: Thread[%s,5,main]\n", s);
for(int i = 5; i >= 1; i--){
System.out.printf("%s:%d\n", s, i);
}
System.out.printf("%s exiting\n", s);
}

BNM Institute Of Technology


}

public class MultiThreadDemo{


public static void main(String[] args){
custom t1 = new custom("One");
custom t2 = new custom("Two");
custom t3 = new custom("Three");

t1.start();
t2.start();
t3.start();

try{
t1.join();
t2.join();
t3.join();
}catch(Exception e){
System.out.println("Error: " + e);
}

System.out.printf("Main thread exiting.\n");


}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]

Page No: 99
New thread: Thread[Three,5,main]
Two:5
One:5
Three:5

ID: 23CSC25
Main thread exiting.
Two:4
One:4
Three:4
Two:3
One:3
Three:3
Two:2
One:2
Three:2
Two:1

2023-27-CSE-C
One:1
Three:1
Two exiting
One exiting
Three exiting

BNM Institute Of Technology


Exp. Name: Create multiple threads to access the
S.No: 40 Date: 2024-09-28
contents of a stack

Aim:

Page No: 100


Create multiple threads to access the contents of a stack. Synchronize thread to prevent simultaneous access to
push and pop operations.

Note: Please don't change the package name.

ID: 23CSC25
Source Code:

q29795/StackThreads.java

2023-27-CSE-C
BNM Institute Of Technology
package q29795;
import java.util.*;

class sync{
Stack<Integer> stack = new Stack<>();

Page No: 101


public synchronized void push(int val){
stack.push(val);
}

public synchronized Integer pop(){

ID: 23CSC25
if(!stack.isEmpty()){
return stack.pop();
}
return -1;
}

class Pusher implements Runnable{


sync myS;
int n;

2023-27-CSE-C
Pusher(sync ob, int n){
this.myS = ob;
this.n = n;
}

BNM Institute Of Technology


@Override
public void run(){
for(int i = n; i > 0; i--){
myS.push(i);
}
}
}

class Popper implements Runnable{


sync myS;
int n;

Popper(sync ob, int n){


this.myS = ob;
this.n = n;
}

@Override
public void run(){
for(int i = 0; i < n; i++){
System.out.println(myS.pop());
}
}
}

public class StackThreads{


public static void main(String[] args){
int n = sc.nextInt();

sync S = new sync();


Runnable pusher = new Pusher(S, n);

Page No: 102


Runnable popper = new Popper(S, n);

Thread t1 = new Thread(pusher);


Thread t2 = new Thread(popper);

t1.start();

ID: 23CSC25
t2.start();

try{
t1.join();
t2.join();
}
catch(Exception e){
System.out.println("Thread was interrupted! ");
}

2023-27-CSE-C
/*
for(int i = 1; i <= n; i++){
System.out.println(i);
}
*/
}

BNM Institute Of Technology


}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Enter the size of the stack
4
1
2
3
4

Test Case - 2

User Output
Enter the size of the stack
9
1
2
3
4
9
8
7
6
5

BNM Institute Of Technology 2023-27-CSE-C ID: 23CSC25 Page No: 103


BNM Institute Of Technology 2023-27-CSE-C ID: 23CSC25 Page No: 104

You might also like