Java CodeTantra
Java CodeTantra
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 .
q29544/BitwiseXOR.java
package q29544;
2023-27-CSE-C
int num3 = num1 ^ num2;
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:
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;
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;
}
}
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
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();
2023-27-CSE-C
}
for(int k = 0; k <= i; k++){
System.out.print(s.charAt(k) + " ");
}
System.out.println(" ");
}
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
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){
2023-27-CSE-C
for(int i = half; i < len; i++){
char ch = s.charAt(i);
System.out.print(ch);
}
System.out.println();
}
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
q10894/NumberPalindrome.java
package q10894;
2023-27-CSE-C
public void isNumberPalindrome(int number) {
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");
}
}
}
2023-27-CSE-C
Test Case - 1
User Output
333 is a palindrome
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
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){
2023-27-CSE-C
c++;
}
}
System.out.println("Capital letters: " + c);
}
}
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");
}
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.*;
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;
}
}
}
}
2023-27-CSE-C
sc.nextLine();
System.out.print("Enter array elements: ");
String s = sc.nextLine();
String sa[] = s.split("\\s");
bubblesort(arr);
System.out.println("Minimum element in array is: " + arr[0]);
System.out.println("Maximum element in array is: " + arr[arr.length - 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);
}
}
2023-27-CSE-C
}
resistor1.giveData(resistance1);
resistor2.giveData(resistance2);
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
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.
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).
q17207/ExecuteMain.java
package q17207;
import java.util.*;
interface GSI{
void area();
Page No: 23
void perimeter();
}
ID: 23CSC25
Triangle(String[] sa){
l = Integer.parseInt(sa[0]);
b = Integer.parseInt(sa[1]);
h = Integer.parseInt(sa[2]);
}
2023-27-CSE-C
public void perimeter(){
double p = (double) l + b + h;
System.out.println("Perimeter of Triangle:" + p);
}
}
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();
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:
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");
}
}
}
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
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:
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.
2023-27-CSE-C
Source Code:
ExecuteAccount.java
class BankAccount {
String name, type;
double balance;
Page No: 28
int account;
ID: 23CSC25
balance = b;
account = a;
}
BankAccount(){
name = "None";
type = "savings";
balance = 0;
account = 0;
}
2023-27-CSE-C
balance += am;
System.out.println("Deposit successful. New balance: " + 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){
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");
}
2023-27-CSE-C
account.displayAccountDetails();
}
}
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
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:
}
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);
}
}
void area(){
double a = (double) b * h;
2023-27-CSE-C
System.out.println("Area of rectangle: " + a);
}
}
void area(){
double a = (double) (b * h)/2;
System.out.println("Area of triangle: " + a);
}
}
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:
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
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);
}
2023-27-CSE-C
Square(int s){
this.s = s;
}
void area(){
int a = s*s;
void area(){
int a = (b*h)/2;
System.out.println("Area of triangle:" + a);
}
}
class Calculation {
public static void main(String args[]) {
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:
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.
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;
}
}
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:
2023-27-CSE-C
AXIS rate of interest = 615.0
q11271/TestOverriding.java
package q11271;
class Bank {
float calculateInterest(float principal, int time) {
return 0;
}
Page No: 42
}
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;
}
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
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
2023-27-CSE-C
Source Code:
q11266/Addition.java
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;
}
2023-27-CSE-C
float d = Float.parseFloat(args[3]);
double e = Double.parseDouble(args[4]);
double f = Double.parseDouble(args[5]);
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;
}
2023-27-CSE-C
this.Pub = Pub;
}
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);
}
}
Page No: 48
for(int i = 0; i < N; i++){
System.out.println("Details for Book " + (i+1) + ":");
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();
2023-27-CSE-C
System.out.println("Book " + (i+1) + " Information:");
arr[i].getBookInfo();
}
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
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);
}
2023-27-CSE-C
int n = sc.nextInt();
if (evenChecker.check(n) == 1){
System.out.println(n + " is an odd number");
}
}
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();
}
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];
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;
}
2023-27-CSE-C
public double divide(double a, double b){
return a / b;
}
}
public class Calc {
}
}
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).
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.*;
Page No: 57
static int[] arr = {1, 2, 3};
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());
}
}
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
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();
}
}
2023-27-CSE-C
r = sc.nextDouble();
}
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.*;
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.");
}
}
}
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
Page No: 64
super(message);
}
}
class BankAccount{
ID: 23CSC25
int account;
double balance;
final double MINIMUM_BALANCE = 100.0;
2023-27-CSE-C
Exception");
}else{
balance -= amount;
System.out.println("Withdrawn:" + amount);
System.out.println("New Balance:" + balance);
}
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
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");
}
}
}
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);
}
}
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);
User Output
35
Valid age: 35 years
Test Case - 2
User Output
178
Error: Invalid age
-23
User Output
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
}
ID: 23CSC25
public void getData(){
Scanner sc = new Scanner(System.in);
r = sc.nextDouble();
}
2023-27-CSE-C
double l, b, a;
class Area {
public static void main(String arg[]) {
Circle c = new Circle();
c.getData();
c.display();
User Output
3
5
10
Area of Circle is 78.5
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();
}
}
2023-27-CSE-C
}
System.out.println("[World]");
count++;
lock.notifyAll();
}
}
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.*;
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);
}
}
}
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);
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
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 {
Page No: 79
private int N;
ID: 23CSC25
}
2023-27-CSE-C
@Override
public void run(){
try{
for(int i = 2; i < N; i++){
if(isPrime(i)){
@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 {
2023-27-CSE-C
PipedOutputStream fibOut = new PipedOutputStream();
PipedInputStream fibIn = new PipedInputStream(fibOut);
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
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.
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();
}
}
}
}
2023-27-CSE-C
private int num;
SquareThread(int num){
this.num = num;
}
}
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;
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);
}
}
2023-27-CSE-C
t1.start();
t2.start();
/*
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());
}
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
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.
2023-27-CSE-C
Ensure that the program handles any potential exceptions that might occur during execution, such as
InterruptedException.
Constraint:
• 0 ≤ n ≤ 10
Output Format:
• The output represents the tables as per the input.
Source Code:
q18198/Main.java
package q18198;
import java.util.Scanner;
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
*/
}
}
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
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();
}
}
/*
class Product{
Queue<Integer> q;
Integer capacity;
Product(Integer capacity){
q = new LinkedList<>();
this.capacity = capacity;
}
Page No: 94
*/
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());
}
}
}
/*
@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;
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);
}
}
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;
@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);
}
t1.start();
t2.start();
t3.start();
try{
t1.join();
t2.join();
t3.join();
}catch(Exception e){
System.out.println("Error: " + e);
}
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
Aim:
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<>();
ID: 23CSC25
if(!stack.isEmpty()){
return stack.pop();
}
return -1;
}
2023-27-CSE-C
Pusher(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());
}
}
}
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);
}
*/
}
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