0% found this document useful (0 votes)
4 views19 pages

java_2LabCycle

The document consists of multiple Java programs demonstrating various concepts such as interfaces, inheritance, exception handling, and package creation. Programs include defining shapes with area and perimeter calculations, managing a bank account with interest calculations, converting temperatures, managing inventory, handling division and array exceptions, and implementing age restrictions for book purchases. Each program includes user input, method implementations, and outputs relevant results based on the operations performed.

Uploaded by

t20655234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views19 pages

java_2LabCycle

The document consists of multiple Java programs demonstrating various concepts such as interfaces, inheritance, exception handling, and package creation. Programs include defining shapes with area and perimeter calculations, managing a bank account with interest calculations, converting temperatures, managing inventory, handling division and array exceptions, and implementing age restrictions for book purchases. Each program includes user input, method implementations, and outputs relevant results based on the operations performed.

Uploaded by

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

Program No: 9

Date: 01-05-2024
Aim: Define an interface called Shape with methods calculateArea() and calculatePerimeter().
Create classes Circle, Rectangle, and Triangle that implement the Shape interface and provide
implementations for these methods.
Program:
import java.util.*;
interface shape {
void Area(int v1, int v2);
void Perimeter(int v1, int v2, int v3);
}
class circle implements shape {
int r;
public void Area(int r, int x) {
System.out.println("\nArea of circle: " + 3.14 * r * r);
}
public void Perimeter(int r, int x, int x1) {
System.out.println("\nPerimeter of circle: " + 2 * 3.14 * r);
}
}
class rectangle implements shape {
int l, b1;
public void Area(int l, int b1) {
System.out.println("\nArea of rectangle: " + l * b1);
}
public void Perimeter(int l, int b, int x) {
System.out.println("\nPerimeter of rectangle: " + 2 * (l + b1));
}
}
class triangle implements shape {
int h, b2, s1, s2, s3;
public void Area(int b2, int h) {
System.out.println("\nArea of triangle: " + 0.5 * b2 * h);
}
public void Perimeter(int s1, int s2, int s3) {
System.out.println("\nPerimeter of triangle: " + (s1 + s2 + s3));
}
}
class Shapes {
public static void main(String args[]) {
int r;
int l, b1, s1, s2, s3, b2, h;
System.out.println("Enter the radius of circle: ");
Scanner sc = new Scanner(System.in);
r = sc.nextInt();
System.out.println("Enter the length of rectangle: ");
l = sc.nextInt();
System.out.println("Enter the breadth of rectangle: ");
b1 = sc.nextInt();
System.out.println("Enter the base of triangle: ");
b2 = sc.nextInt();
System.out.println("Enter the height of triangle: ");
h = sc.nextInt();
System.out.println("Enter first side of the triangle: ");
s1 = sc.nextInt();
System.out.println("Enter second side of the triangle: ");
s2 = sc.nextInt();
System.out.println("Enter third side of the triangle: ");
s3 = sc.nextInt();
shape obj = new circle();
obj.Area(r, 0);
obj.Perimeter(r, 0, 0);
shape obj1 = new rectangle();
obj1.Area(l, b1);
obj1.Perimeter(l, b1, 0);
shape obj2 = new triangle();
obj2.Area(b2, h);
obj2.Perimeter(s1, s2, s3);
}
}
Output:

Enter the radius of circle: 3


Enter the length of rectangle: 5
Enter the breadth of rectangle: 3
Enter the base of triangle: 3
Enter the height of triangle: 4
Enter first side of the triangle: 2
Enter second side of the triangle: 3
Enter third side of the triangle: 4
Area of circle: 28.259999999999998
Perimeter of circle: 18.84
Area of rectangle: 15
Perimeter of rectangle: 10
Area of triangle: 6.0
Perimeter of triangle: 9
Program No: 10
Date: 21-04-2024
Aim: Create a base class Account with attributes accountNumber, balance, and methods
deposit(double amount) and withdraw(double amount). Extend this class to create a
SavingsAccount class and implement interfaces InterestCalculatable (with method
calculateInterest()) and WithdrawLimitable (with method checkWithdrawLimit()).
Program:
import java.util.Scanner;
interface InterestCalculatable {
double calculateInterest();
}
interface WithdrawLimitable {
boolean checkWithdrawLimit(double Amount);
}
class Account {
protected String accountNumber;
protected double Balance;
public Account(String a, double b) {
accountNumber = a;
Balance = b;
}
public void deposit(double Amount) {
Balance += Amount;
System.out.println("Deposited " + Amount + " into account " + accountNumber);
System.out.println("Balance is :" + Balance);
}
public void withdraw(double Amount) {
if (Amount <= Balance) {
Balance -= Amount;
System.out.println("Withdrawn " + Amount + " from account " + accountNumber);
System.out.println("Balance is :" + Balance);
} else {
System.out.println("Insufficient Balance in account " + accountNumber);
System.out.println("Balance is :" + Balance);
}
}
}
class SavingsAccount extends Account implements InterestCalculatable, WithdrawLimitable {
private double interestRate;
private double withdrawLimit;
public SavingsAccount(String accountNumber, double balance, double interestRate, double
withdrawLimit) {
super(accountNumber, balance);
this.interestRate = interestRate;
this.withdrawLimit = withdrawLimit;
}
public double calculateInterest() {
double interest = Balance * interestRate;
System.out.println("Interest calculated for account " + accountNumber + ": " + interest);
return interest;
}
public boolean checkWithdrawLimit(double Amount) {
if (Amount <= withdrawLimit) {
System.out.println("Withdraw limit check passed for account " + accountNumber);
withdraw(Amount);
return true;
} else {
System.out.println("Withdraw limit exceeded for account " + accountNumber);
return false;
}
}
}
public class Bank1 {
public static void main(String[] args) {
String accno;
double balance, interestRate, withdrawLimit, amt;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Account details ");
System.out.print("Enter the Account number:");
accno = sc.nextLine();
System.out.print("Enter the Balance:");
balance = sc.nextDouble();
System.out.print("Enter the Interest Rate:");
interestRate = sc.nextDouble();
System.out.print("Enter the Withdraw Limit:");
withdrawLimit = sc.nextDouble();
SavingsAccount savingsAccount = new SavingsAccount(accno, balance, interestRate,
withdrawLimit);
System.out.print("Enter the amount to Deposit:");
amt = sc.nextDouble();
savingsAccount.deposit(amt);
System.out.print("Enter the amount to Withdraw:");
amt = sc.nextDouble();
savingsAccount.checkWithdrawLimit(amt);
System.out.print("Enter the amount to Withdraw:");
amt = sc.nextDouble();
savingsAccount.checkWithdrawLimit(amt);
savingsAccount.calculateInterest();
}
}
Output:
Enter the Account details
Enter the Account number:1002
Enter the Balance:45000
Enter the Interest Rate:10
Enter the Withdraw Limit:1500
Enter the amount to Deposit:2000
Deposited 2000.0 into account 1002
Balance is :47000.0
Enter the amount to Withdraw:1600
Withdraw limit exceeded for account 1002
Enter the amount to Withdraw:1000
Withdraw limit check passed for account 1002
Withdrawn 1000.0 from account 1002
Balance is :46000.0
Interest calculated for account 1002: 460000.0
Program No: 11
Date: 21-04-2024
Aim: Develop a package named temperature that contains a class Converter. Implement methods
in the Converter class to convert temperatures between Celsius, Fahrenheit, and Kelvin. Use this
package to convert and display temperatures in different units.
Program:
Temperature/Converter.java
package temperature;
public class Converter {
public double converToFahrenheit(double temperature)
{ temperature = temperature * (9 / 5) + 32;
return temperature;
}
public double convertToKelvin(double temperature)
{ temperature = temperature + 273.5f;
return temperature;}}
Temperature.java
import java.util.Scanner;
import temperature.Converter;
public class Temperature {
public static void main(String[] args)
{ double temperature;
Converter ob = new Converter();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the temperature in Celsius scale:");
temperature = sc.nextDouble();
System.out.println("Temperature in Fahrenheit is: " + ob.converToFahrenheit(temperature) +
"F");
}}
System.out.println("Temperature in Kelvin is: " + ob.convertToKelvin(temperature) + "K");
Output:
Enter the temperature in Celsius scale:39
Temperature in Fahrenheit is: 71.0F
Temperature in Kelvin is: 312.5K
Program No: 12
Date: 21-04-2024
Aim: Design a package named inventory that consists of classes for managing inventory items
like Product, Stock, and Inventory Manager. Implement methods for adding/removing items,
updating stock levels, and generating inventory reports.
Program:
Inventory/Product.java
package inventory; public
class Product {
private String productId;
private String productName;
private float productPrice;
public void setProductID(String id)
{ productId = id;
}
public String getProductID()
{ return productId;
}
public void setProductName(String name)
{ productName = name;
}
public String getProductName()
{ return productName;
}
public void setProductPrice(float p)
{ productPrice = p;
}
public float getProductPrice()
{ return productPrice;
}
}
Inventory/Stock.java
package inventory; public
class Stock {

private Product product; private


int productQuantity;

public void setProduct(Product product)


{ this.product = product;
}
public Product getProduct()
{ return product;
}
public void setProductQuantity(int quan)
{ this.productQuantity = quan;
}
public int getProductQuantity()
{ return productQuantity;}}
Inventory/inventory.java
package inventory;
import java.util.Scanner;
public class Inventory {
private Stock stock[];
private int n;
public void addProduct() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of products to be entered:");
n = sc.nextInt();
stock = new Stock[n];
for (int i = 0; i < n; i++) {
Product product = new Product();
System.out.println("Enter the details of the product " + (i + 1));
System.out.print("Enter product ID:");
sc.nextLine();
product.setProductID(sc.nextLine());
System.out.print("Enter product name:");
product.setProductName(sc.nextLine());
System.out.print("Enter product price:");

product.setProductPrice(sc.nextFloat());

stock[i] = new Stock();

stock[i].setProduct(product);

System.out.print("Enter product quantity:");

stock[i].setProductQuantity(sc.nextInt());

}}
public void displayProducts() {
System.out.println("+----------+----------+----------- +");
System.out.printf("| %-8s | %-8s | %-8s |\n", "Name", "Price", "Quantity");
System.out.println("+----------+----------+-----------+");
for (int i = 0; i < n; i++) {
System.out.printf("| %-8s | %-8.2f | %-8d |\n", stock[i].getProduct().getProductName(),
stock[i].getProduct().getProductPrice(), stock[i].getProductQuantity());}
System.out.println("+----------+----------+----------- +");}
public void updateProducts()
{ String id;
int quan;
Scanner s = new Scanner(System.in);
System.out.print("Enter the product ID to update the stock:");
id = s.nextLine();
System.out.print("Enter the new Quantity:"); quan
= s.nextInt();
for (int i = 0; i < n; i++) {
if (stock[i].getProduct().getProductID().equals(id))
{ stock[i].setProductQuantity(quan);
break;}}
displayProducts();}
public void generateReport()
{ System.out.println("Stock Report!!");
System.out.println("+----------+---------- +");
System.out.printf("| %-8s | %-8s |\n", "Name", "Quantity");
System.out.println("+----------+---------- +");
for (int i = 0; i < n; i++) {
System.out.printf("| %-8s | %-8d |\n", stock[i].getProduct().getProductName(),
stock[i].getProductQuantity());}

System.out.println("+----------+---------- +");
}
}
InventorySystem.java
import inventory.Inventory;
public class InventorySystem {
public static void main(String[] args)
{ Inventory inventory = new Inventory();
inventory.addProduct();
inventory.displayProducts();
inventory.updateProducts();
inventory.generateReport();
}
}
Output:
Enter the number of products to be entered:2
Enter the details of the product 1
Enter product ID:1001 Enter
product name:laptop Enter
product price:10000 Enter
product quantity:5
Enter the details of the product 2
Enter product ID:1002
Enter product name:phone
Enter product price:25000
Enter product quantity:10
Enter the product ID to update the stock:1001
Enter the new Quantity:10
+ + + +
| Name | Price | Quantity |
+ + + +
| laptop | 10000.00 | 5 |
| phone | 25000.00 | 10 |
| Name | Price | Quantity |
+ + + +
| laptop | 10000.00 | 10 |
| phone | 25000.00 | 10 |
+ + + +
Stock Report!!
+ + +
| Name | Quantity |
+ + +
| laptop | 10 |
| phone | 10 |
+ + +
Program No: 13
Date: 26-04-2024
Aim: Write a Java program that takes two integers as input from the user and performs division.
Implement exception handling to catch and handle the Arithmetic Exception that may occur if the
user tries to divide by zero.
Program:
import java.util.Scanner;
public class Division {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a, b;
float result = 0;
System.out.println("Enter two numbers to divide");
a = sc.nextInt();
b = sc.nextInt(); try
{
result = a / b;
} catch (Exception e) {
System.out.println("Exception:" + e);
}
System.out.println("Result: " + result);
}
}
Output:
Enter two numbers to divide
20
Exception:java.lang.ArithmeticException: / by zero
Result: 0.0
Program No: 14
Date: 26-04-2024
Aim: Write a Java program that initializes an array with a fixed size and tries to access an element
at an index outside the array's bounds. Implement exception handling to catch and handle
ArrayIndexOutOfBoundsException.
Program:
import java.util.Scanner; public
class ArrayControl {
public static void main(String[] args) {
int a[]=new int[5];
Scanner sc =new Scanner(System.in);
System.out.println("Enter 5 elements of the array");
for(int i=0;i<5;i++){
a[i]=sc.nextInt();} int
sum = 0;
try {
for (int i = 0; i < 10; i++)
{ System.out.println(i);
sum += a[i];}
} catch (Exception e)
{ System.out.println("Exception:" + e);}
System.out.println("Sum of the elements of the array:" + sum);}}
Output:
Enter 5 elements of the array
34567
0
1
2
3
4
5
Exception:java.lang.ArrayIndexOutOfBoundsException: 5
Sum of the elements of the array:25
Program No: 15
Date: 28-04-2024
Aim: Create a Java program for a bookstore that sells books based on the buyer's age. Implement a
user-defined exception called AgeRestrictionException, which should be thrown if a buyer's age
is below 18 years, as the store only sells books to individuals who are 18 years or older.
Handle this exception appropriately in your program.
Program:
import java.util.Scanner;
class Book {
String title;
double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public double getPrice() {
return price;
}
}
class Books {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter details for Book 1:");
System.out.print("Title: ");
String title1 = sc.nextLine();
System.out.print("Price: ");
double price1 = sc.nextDouble();
sc.nextLine();
System.out.println("Enter details for Book 2:");
System.out.print("Title: ");
String title2 = sc.nextLine();
System.out.print("Price: ");
double price2 = sc.nextDouble();
sc.nextLine();
System.out.println("Enter details for Book 3:");
System.out.print("Title: ");
String title3 = sc.nextLine();
System.out.print("Price: ");
double price3 = sc.nextDouble();
Book b1 = new Book(title1, price1);
Book b2 = new Book(title2, price2);
Book b3 = new Book(title3, price3);
Book[] books = { b1, b2, b3 };
System.out.println("List of Books\n");
System.out.println("1. " + b1.getTitle());
System.out.println("2. " + b2.getTitle());
System.out.println("3. " + b3.getTitle());
System.out.println("Select your choice: ");
int choice = sc.nextInt();
choice--;
try
{
System.out.print("Please enter your age: ");
int age = sc.nextInt();
if (age < 18)
{
throw new Exception(books[choice].getTitle() + " cannot be sold to a buyer younger than 18
years old.");
}
System.out.println("Sold book: " + books[choice].getTitle() + " for Rupees:" +
books[choice].getPrice());
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Enter details for Book 1:
Title: Wings of fire
Price: 350
Enter details for Book 2:
Title: C programming
Price: 590
Enter details for Book 3:
Title: The Hobbit
Price: 250
List of Books

1. Wings of fire
2. C programming
3. The Hobbit
Select your choice: 2
Please enter your age: 22
Sold book: C programming for Rupees:590.0

Enter details for Book 1:


Title: Wings of fire
Price: 350
Enter details for Book 2:
Title: C programming
Price: 590
Enter details for Book 3:
Title: The Hobbit
Price: 250
List of Books

1. Wings of fire
2. C programming
3. The Hobbit
Select your choice: 1
Please enter your age: 16
Error: Wings of fire cannot be sold to a buyer younger than 18 years old.
Program No: 16
Date: 05-05-2024
Aim: Write a Java program that demonstrates the use of threads to perform concurrent tasks.
Create two threads, one to print even numbers from 1 to 10 and another to print odd numbers
from 1 to 10.
Program:
class EvenThread extends Thread {
public void run() {
for (int i = 2; i <= 10; i += 2) {
System.out.println(i);
} }}
class OddThread extends Thread {
public void run() {
for (int i = 1; i <= 10; i += 2) {
System.out.println(i);
}}}
public class ThreadMain {
public static void main(String[] args) {
EvenThread even = new EvenThread();
OddThread odd = new OddThread();
even.start();
odd.start();
}}
Output
1
3
5
7
9
2
4
6
8
10
Program No: 17
Date: 06-05-2024
Aim: Implement the above program with synchronization.
Program:
class EvenOdd {
synchronized public static void printEven() {
for (int i = 2; i <= 10; i += 2) {
System.out.println(i);
} }
synchronized public static void printOdd() {
for (int i = 1; i <= 10; i += 2) {
System.out.println(i);
} }}
class EvenThread extends Thread {
public void run() {
EvenOdd.printEven();
} }
class OddThread extends Thread {
public void run() {
EvenOdd.printOdd();
}
}
public class ThreadSync {
public static void main(String[] args) {
EvenThread even = new EvenThread();
OddThread odd = new OddThread();
even.start();
odd.start();
}}

Output:
2
4
6
8
10
1
3
5
7
9

You might also like