JAVA Codes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

PRIME NUMBERS. Scanner scanner = new Scanner(System.

in);
import java.util.Scanner; System.out.print("Enter the starting number (m): ");
int m = scanner.nextInt();
public class PrimeNumbers {
public static void main(String[] args) { System.out.print("Enter the ending number (n): ");
Scanner scanner = new Scanner(System.in); int n = scanner.nextInt();
System.out.print("Enter the starting number (m): "); for (int i = m; i <= n; i++) {
int m = scanner.nextInt(); int num = i;
int sum = 0;
System.out.print("Enter the ending number (n): "); int digits = String.valueOf(i).length();
int n = scanner.nextInt();
while (num != 0) {
for (int i = m; i <= n; i++) { int remainder = num % 10;
if (i <= 1) continue; sum += Math.pow(remainder, digits);
boolean isPrime = true; num /= 10;
}
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) { if (sum == i) {
isPrime = false; System.out.println(i);
break; }
} }
}
scanner.close();
if (isPrime) { }
System.out.println(i); }
}
}
Calculate the Volume of a Sphere
import java.util.*;
scanner.close();
} import java.math.*;
}
class Main
PERFECT NUMBERS.
{
import java.util.Scanner;
public static void main(String args[])
public class PerfectNumbers { {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); Scanner abc=new Scanner(System.in);
float r=abc.nextFloat();
System.out.print("Enter the starting number (m): ");
int m = scanner.nextInt(); double v=(4f/3f)* Math.PI*Math.pow(r,3);
System.out.print(String.format("%.2f",v));
System.out.print("Enter the ending number (n): ");
int n = scanner.nextInt(); }

for (int i = m; i <= n; i++) { }


int sum = 0; read size of two dimensional array (A) as M,N. read
for (int j = 1; j <= i / 2; j++) {
(M-1)*(N-1) elements e.
if (i % j == 0) { import java.util.Scanner;
sum += j;
} public class two_d_array_sum {
} public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if (sum == i) {
System.out.println(i); System.out.print("Enter the number of rows (M): ");
} int M = scanner.nextInt();
} System.out.print("Enter the number of columns (N): ");
int N = scanner.nextInt();
scanner.close();
} int[][] array = new int[M][N];
} System.out.println("Enter " + (M - 1) * (N - 1) + " elements:");
ARMSTRONG NUMBERS. for (int i = 0; i < M - 1; i++) {
import java.util.Scanner; for (int j = 0; j < N - 1; j++) {
array[i][j] = scanner.nextInt();
public class ArmstrongNumbers { }
public static void main(String[] args) { }
public static int getMaxFrequency(int[] ages) {
for (int i = 0; i < M - 1; i++) { HashMap<Integer, Integer> ageFrequency = new
int rowSum = 0; HashMap<>();
for (int j = 0; j < N - 1; j++) { for (int age : ages) {
rowSum += array[i][j]; ageFrequency.put(age, ageFrequency.getOrDefault(age, 0)
} + 1);
array[i][N - 1] = rowSum; }
}
int maxFrequency = 0;
for (int j = 0; j < N; j++) { for (int freq : ageFrequency.values()) {
int colSum = 0; if (freq > maxFrequency) {
for (int i = 0; i < M - 1; i++) { maxFrequency = freq;
colSum += array[i][j]; }
} }
array[M - 1][j] = colSum; return maxFrequency;
} }
}
int totalSum = 0;
for (int i = 0; i < M; i++) { write a java program to calculate the following series
totalSum += array[i][N - 1]; 1+x+x2/2!+x3/3!+………..+xn/n!
}
array[M - 1][N - 1] = totalSum; import java.util.Scanner;

System.out.println("Resultant Matrix:"); public class SeriesCalculation {


for (int i = 0; i < M; i++) { public static void main(String[] args) {
for (int j = 0; j < N; j++) { Scanner scanner = new Scanner(System.in);
System.out.print(array[i][j] + " ");
} System.out.print("Enter the value of x: ");
System.out.println(); double x = scanner.nextDouble();
} System.out.print("Enter the value of n: ");
} int n = scanner.nextInt();
}
double result = calculateSeries(x, n);
write a java program to print 1 if maximum number of times System.out.println("The result of the series is: " + result);
repeated girls age is equal to the maximum number of times }
repeated boys , other wise print 0.
public static double calculateSeries(double x, int n) {
import java.util.HashMap; double sum = 1; // Start with the first term (1)
import java.util.Scanner; double term = 1; // This will store each term in the series

public class repeated_ages { for (int i = 1; i <= n; i++) {


public static void main(String[] args) { term *= x / i; // Update the term (x^i / i!)
Scanner scanner = new Scanner(System.in); sum += term; // Add the term to the sum
}
System.out.print("Enter the number of girls (N): ");
int N = scanner.nextInt(); return sum;
System.out.print("Enter the number of boys (M): "); }
int M = scanner.nextInt(); }

int[] girlsAges = new int[N]; b) write a java program to implement access specifiers with the
int[] boysAges = new int[M]; help of packages.

System.out.println("Enter the ages of girls:"); Step 1: Create the com.company package with a class Employee.
for (int i = 0; i < N; i++) {
girlsAges[i] = scanner.nextInt(); package com.company;
}
public class Employee {
System.out.println("Enter the ages of boys:"); public int employeeId;
for (int i = 0; i < M; i++) { public String employeeName;
boysAges[i] = scanner.nextInt();
} private double salary;

int maxGirlsFrequency = getMaxFrequency(girlsAges); protected String department;


int maxBoysFrequency = getMaxFrequency(boysAges);
String address;
System.out.println(maxGirlsFrequency ==
maxBoysFrequency ? 1 : 0); public Employee(int employeeId, String employeeName, double
} salary, String department, String address) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.salary = salary; class PerfectNumber {
this.department = department; public boolean isPerfect(int num) {
this.address = address; int sum = 0;
} for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
public double getSalary() { sum += i;
return salary; }
} }
return sum == num;
public void displayEmployeeDetails() { }
System.out.println("Employee ID: " + employeeId);
System.out.println("Employee Name: " + employeeName); public void printPerfectNumbers(int start, int end) {
System.out.println("Department: " + department); System.out.println("Perfect numbers in the range " + start + "
System.out.println("Address: " + address); to " + end + ":");
} for (int i = start; i <= end; i++) {
} if (isPerfect(i)) {
Step 2: Create another class EmployeeTest in the com.test System.out.print(i + " ");
package to test the Employee class. }
java }
Copy code System.out.println();
}
package com.test; }

import com.company.Employee; public class PrimePerfectTest {


public static void main(String[] args) {
public class EmployeeTest { PrimeNumber primeNumber = new PrimeNumber();
public static void main(String[] args) { primeNumber.printPrimes(1, 100); // Find prime numbers
Employee emp = new Employee(1, "John Doe", 50000, "HR", between 1 and 100
"123 Main St");
PerfectNumber perfectNumber = new PerfectNumber();
System.out.println("Employee ID: " + emp.employeeId); perfectNumber.printPerfectNumbers(1, 100); // Find perfect
System.out.println("Employee Name: " + numbers between 1 and 100
emp.employeeName); }
}
System.out.println("Salary: " + emp.getSalary());
write a java program to implement multiple inheritance using
System.out.println("Department: " + emp.department); packages.

emp.displayEmployeeDetails(); 1. Create a Package with Interfaces:


} package com.vehicle;
}
public interface Vehicle {
void start();
write a java program to find prime numbers and perfect void stop();
numbers in the given range using two different classes. }

class PrimeNumber { package com.machine;


public boolean isPrime(int num) {
if (num <= 1) return false; public interface Machine {
for (int i = 2; i <= Math.sqrt(num); i++) { void operate();
if (num % i == 0) { void shutdown();
return false; }
} 2. Create a Class Implementing Both Interfaces:
} package com.factory;
return true;
} import com.vehicle.Vehicle;
import com.machine.Machine;
public void printPrimes(int start, int end) {
System.out.println("Prime numbers in the range " + start + " to public class Robot implements Vehicle, Machine {
" + end + ":"); public void start() {
for (int i = start; i <= end; i++) { System.out.println("Vehicle started");
if (isPrime(i)) { }
System.out.print(i + " ");
} public void stop() {
} System.out.println("Vehicle stopped");
System.out.println(); }
}
} public void operate() {
System.out.println("Machine is operating"); }
}
NumberFormatException
public void shutdown() { import java.util.Scanner;
System.out.println("Machine is shutting down");
} public class BMICalculator {
} public static void main(String[] args) {
3. Main Class to Test the Implementation: Scanner scanner = new Scanner(System.in);
import com.factory.Robot;
double weight = 0;
public class Main { double height = 0;
public static void main(String[] args) {
Robot robot = new Robot(); while (true) {
System.out.print("Enter weight in kilograms: ");
robot.start(); // From Vehicle interface String weightInput = scanner.nextLine();
robot.operate(); // From Machine interface try {
robot.shutdown(); // From Machine interface weight = Double.parseDouble(weightInput);
robot.stop(); // From Vehicle interface if (weight <= 0) {
} System.out.println("Please enter a positive number for
} weight.");
continue;
}
OverFlow exception break; // valid input
} catch (NumberFormatException e) {
class OverFlowException extends Exception { System.out.println("Invalid input. Please enter a valid
public OverFlowException(String message) { number for weight.");
super(message); }
} }
}
while (true) {
class Room { System.out.print("Enter height in meters: ");
String roomName; String heightInput = scanner.nextLine();
int capacity; try {
int currentCount; height = Double.parseDouble(heightInput);
if (height <= 0) {
public Room(String roomName, int capacity, int currentCount) { System.out.println("Please enter a positive number for
this.roomName = roomName; height.");
this.capacity = capacity; continue;
this.currentCount = currentCount; }
} break; // valid input
} catch (NumberFormatException e) {
public void addMembers(int members) throws System.out.println("Invalid input. Please enter a valid
OverFlowException { number for height.");
if (currentCount + members > capacity) { }
throw new OverFlowException("No space in the room: " + }
roomName);
} else { double bmi = weight / (height * height);
currentCount += members; System.out.println("Your BMI is: " + bmi);
System.out.println("Added " + members + " members to " +
roomName + ". Current count: " + currentCount); if (bmi < 18.5) {
} System.out.println("BMI Category: Underweight");
} } else if (bmi >= 18.5 && bmi <= 24.9) {
} System.out.println("BMI Category: Normal weight");
} else if (bmi >= 25 && bmi <= 29.9) {
public class Building { System.out.println("BMI Category: Overweight");
public static void main(String[] args) { } else {
Room r1 = new Room("r1", 30, 20); System.out.println("BMI Category: Obesity");
Room r2 = new Room("r2", 40, 25); }
Room r3 = new Room("r3", 50, 45); }
}
try {
r1.addMembers(10); access modifiers with the help of packages.
r2.addMembers(20); Step 1: Define the Person class in the person package:
r3.addMembers(10); package person;
} catch (OverFlowException e) {
System.out.println(e.getMessage()); public class Person {
} private String name;
} private int age;
import java.util.*;
public Person(String name, int age) {
class Main
this.name = name;
this.age = age; {
}
public static void main(String args[])
public void displayDetails() { {
System.out.println("Name: " + name);
System.out.println("Age: " + age); int p,r,t;
} Scanner atz=new Scanner(System.in);

public String getName() { p=atz.nextInt();


return name; t=atz.nextInt();
}
r=atz.nextInt();
public int getAge() { System.out.print((p*t*r)/100);
return age;
} }
}
public void setName(String name) {
this.name = name; Sum of Two Numbers (handle both positive and
} negative integers, as well as zero)
public void setAge(int age) { import java.util.*;
this.age = age;
class Main
}
} {
Step 2: Define the TestPerson class in the test package:
public static void main(String args[])
package test; {

import person.Person; int a,b;


Scanner sc=new Scanner(System.in);
public class TestPerson {
public static void main(String[] args) { a=sc.nextInt();
Person person = new Person("John Doe", 25); b=sc.nextInt();

person.displayDetails(); System.out.print(a+b);
}
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge()); }
}
} Time taken for one harmonic motion
import java.util.*;
program that calculates the displacement (s) import java.math.*;
import java.util.*; class Main
class Main {
{ public static void main(String args[])
public static void main(String args[]) {
{ Scanner atz=new Scanner(System.in);
float u,a,t; double g=9.8;
Scanner atz=new Scanner(System.in); double L=atz.nextDouble();
u=atz.nextFloat(); double t=2 * Math.PI * Math.sqrt(L/g);
a=atz.nextFloat(); System.out.printf("%.2f",t);
t=atz.nextFloat(); }
float s=(u*t)+(0.5f *a*(t*t)); }
System.out.print(s);
electricity bill (taking input from the keyboard)
}
import java.util.*;
}
class Main
Simple Interest {
public static void main(String args[]) System.out.print("Hot Weather");
{ }
Scanner sc=new Scanner(System.in); else if(n>=40)
double b=0d; {
int id=sc.nextInt(); System.out.print("Very hot Weather");
int u=sc.nextInt(); }
if(u<=199)
b=u*1.20; else{
else if(u>=200 && u<=399) System.out.print("Invalid input");
b=u*1.50; }
else if(u>=400 && u<=599) scn.close();
b=u*1.80; }
else }
b=u*2.00; Arithmetic Progression(taking input from the
if(b>400) keyboard)
b+=(0.15*b); import java.util.*;
if(b<100) class Main
b=100; {
System.out.print(b); public static void main(String args[])
} {
} Scanner scn=new Scanner(System.in);

weather condition (reads the temperature in int n;


degrees centigrade from the user and displays a int n1=scn.nextInt();
message) int n2=scn.nextInt();
import java.util.*; int n3=scn.nextInt();
class Main n=(n2*(2*n1+(n2-1)*n3))/2;
{ System.out.print(n);
public static void main(String args[]) scn.close();
{ }
Scanner scn=new Scanner(System.in); }
int n=scn.nextInt();
Atm Operations(taking input from the
if(n<0) keyboard)
{ import java.util.*;
System.out.print("Freezing Weather"); class Main
} {
else if(n>=0 && n<10) public static void main(String args[])
{ {
System.out.print("Very Cold Weather"); Scanner sc=new Scanner(System.in);
} int b=10000;
else if(n>=20 && n<30) boolean contbank=true;
{ while(contbank)
System.out.print("Normal Weather"); {
} int v=sc.nextInt();
else if(n>=30 && n<40) switch(v)
{ {
case 1: for(i=1;i<n;i++)
int wd=sc.nextInt(); {
if(wd>b) if(max<t[i])
System.out.print("Insufficient Balance"); max=t[i];
else{ }
b=b-wd; double min=t[0];
System.out.print("Withdraw Success, Your for(i=1;i<n;i++)
account balance is : "+b);
{
}
if(min>t[i])
break;
min=t[i];
case 2:
}
int dm=sc.nextInt();
double avg=sum/7;
b+=dm;
System.out.printf("Highest Temperature: %.1f\n",max);
System.out.print("Deposit Success, Your Current
Balance is : "+b); System.out.printf("Lowest Temperature: %.1f\n",min);

break; System.out.printf("Average Temperature: %.2f",avg);

case 3: }

System.out.print("Your Account Balance is: "+b); }

break; Grade-wise Student List (Use two-dimensional


array to hold student's)
case 4: import java.util.*;

contbank=false; public class Main

break; {

default: public static void main(String args[])

System.out.print("Invalid Choice"); {

} Scanner s=new Scanner(System.in);

} int i,n=s.nextInt();

sc.close(); String[][] arr=new String[n][2];

} for(i=0;i<n;i++)

} {
arr[i][0]=s.next();
Weekly Temperature Analysis (storing arrays)
arr[i][1]=s.next();
import java.util.*;
}
class Main
char[] grades={'A','B','C','D','E'};
{
for(char grade:grades)
public static void main(String args[])
{
{
System.out.println("");
int n=7,i;
System.out.print(grade+":");
double[] t=new double[7];
for(i=0;i<n;i++)
double sum=0.00;
{
Scanner s=new Scanner(System.in);
boolean first=true;
for(i=0;i<n;i++)
if(arr[i][1].charAt(0)==grade)
{
{
t[i]=s.nextDouble();
if(!first)
sum+=t[i];
System.out.print(" ");
}
System.out.print(" "+arr[i][0]);
double max=t[0];
first=false; }
} }
} Employee details (Creating Class & Creating
} ,Implementing Method)
} import java.util.*;
}

Employee Login System(storing details in class Main


arrays) {
import java.util.Scanner; public static void main(String args[])
public class Main {
{ Scanner s=new Scanner(System.in);
public static void main(String[] args) int i;
{ int[] eid=new int[10];
Scanner s=new Scanner(System.in); String[] en=new String[15];
try int[] ea=new int[10];
{ String[] ed=new String[15];
int n=Integer.parseInt(s.nextLine().trim()); double[] es=new double[10];
String[][] employees=new String[n][3]; for(i=0;i<1;i++)
for(int i=0;i<n;i++) {
{ eid[i]=s.nextInt();
String[] input=s.nextLine().trim().split(" ",3); s.nextLine();
if(input.length!=3) en[i]=s.nextLine();
throw new IllegalArgumentException("Invalid ea[i]=s.nextInt();
input format");
s.nextLine();
employees[i]=input;
ed[i]=s.nextLine();
}
es[i]=s.nextDouble();
String id=s.nextLine().trim();
}
String password=s.nextLine().trim();
for(i=0;i<1;i++)
boolean isLoggedIn=false;
System.out.println("Employee ID: "+eid[i]+", Name:
for(String[] employee:employees) "+en[i]+", Age: "+ea[i]+", Department: "+ed[i]+", Salary: "+es[i]);
{ s.close();
}
if(employee[0].equals(id)&&employee[2].equals(password))
}
{
Searching Record (Creating Class & Creating
System.out.println("Welcome "+employee[1]);
,Implementing Method)
isLoggedIn=true;
import java.util.*;
break;
}
public class Main
}
{
if(!isLoggedIn)
static String cn;
System.out.println("Failed to login");
static int ns;
}
static int[] rn;
catch(Exception e){
static String[] name;
System.out.println("Invalid input");}
static int[] marks;
finally{
s.close();}
public static void find_rn(int rollno) if(totalstock==0)
{ throw new
ArithmeticException("Cannot calculate stock percentage. No stock
boolean found=false; available.");
for(int i=0;i<ns;i++) double
{ stockpercentage=(double)itemsold/totalstock*100;

if(rn[i]==rollno) System.out.print("Stock
Percentage:"+stockpercentage+"%");
{
}
System.out.println("Roll Number: "+rn[i]+", Name:
"+name[i]+", Marks: "+marks[i]); catch(ArithmeticException e){

found=true; System.out.print(e.getMessage());

break; }

} }

} }

if(!found) Array Index OutOfBounds Exception


System.out.println("Record Does Not Exist"); import java.util.Scanner;
} public class Main
{
public static void main(String args[]) public static void main(String args[])
{ {
Scanner s=new Scanner(System.in); int[] scores={85, 90, 78, 92, 88};
cn=s.nextLine(); Scanner s=new Scanner(System.in);
ns=s.nextInt(); System.out.print("Enter the index of the student's score you
want to retrieve: ");
rn=new int[ns];
int in=s.nextInt();
name=new String[ns];
System.out.print(scores.length);
marks=new int[ns];
System.out.println();
for(int i=0;i<ns;i++)
try{
{
if(in<0 || in>=scores.length)
rn[i]=s.nextInt();
throw new
s.nextLine();
ArrayIndexOutOfBoundsException("Invalid index. Please enter a
name[i]=s.nextLine(); valid index between 0 and "+(scores.length-1));
marks[i]=s.nextInt(); System.out.print("Student's score: "+scores[in]);
} }
int rollno=s.nextInt(); catch(ArrayIndexOutOfBoundsException e){
find_rn(rollno); System.out.println("Error: "+e.getMessage());
} }
} s.close();

Handling ArithmeticException in Inventory }


Management System }
public class Main Throw keyword Exception Example code
{ import java.util.*;
public static void main(String args[])
{ class wle extends Exception{
int itemsold=10; public wle(String msg)
int totalstock=0; {
try { super(msg);
} }
} if (!found)
class Main throw new empnfexp("Employee Missing..");
{ else
private static final int mw=15; System.out.println("Employee " + eid + " found.");
public static void luggagecheckin(int w) throws wle{ }
if(w>mw) }
throw new wle((w-mw)+" kg :"+"
WeightLimitExceeded");
public class Main
else
{
System.out.println("You are ready to fly!");
public static void main(String[] args)
}
{
public static void main(String args[])
String eid = "e7";
{
empnfexp empcheck = new empnfexp("");
Scanner s=new Scanner(System.in);
try
for(int i=0;i<2;i++){
{
int w=s.nextInt();
empcheck.empfind(eid);
try{
}
luggagecheckin(w);
catch (empnfexp e)
}
{
catch(wle e){
System.out.println(e.getMessage());
System.out.println(e.getMessage());
}
}
}
}
}
}
Banking System (class with synchronized
}
methods)
custom exception or user-defined exception class BankAccount
import java.io.*;
{
private int bal;
class empnfexp extends Exception
public BankAccount(int initbal) {
{
this.bal = initbal;
public empnfexp(String message) {
}
super(message);
public synchronized void deposit(int amount, String
}
acholdername) {
public void empfind(String eid) throws empnfexp
if (amount > 0) {
{
bal += amount;
String[] empids = {"e1", "e3", "e5"};
System.out.println(acholdername + " deposited " +
boolean found = false; amount + ", Current Balance: " + bal);
for (String id : empids)
}
{
}
if (id.equals(eid))
public synchronized void withdraw(int amount, String
{ acholdername) {
found = true; if (amount > 0 && amount <= bal) {
break;
bal -= amount;
}
System.out.println(acholdername + " withdrew " +
amount + ", Current Balance: " + bal);
try {
} else {
user1.start();
System.out.println(acholdername + " attempted to
withdraw " + amount + " but insufficient funds."); user1.join();

} user2.start();

} user2.join();
user3.start();

public int getbalance() { user3.join();

return bal; }

} catch (InterruptedException e) {

} e.printStackTrace();
}

class User implements Runnable { }

private BankAccount acc; }

private int depositamt; Producer-Consumer Problem (Food Delivery


Simulation) ( shared OrderQueue)
private int withdrawamt;
class Order {
private String acholdername;
private static int idCounter = 0;
private final int id;
public User(BankAccount acc, int depositamt, int
withdrawamt, String acholdername) {
this.acc = acc; public Order() {
this.depositamt = depositamt; this.id = ++idCounter;
this.withdrawamt = withdrawamt; }
this.acholdername = acholdername; public int getid() {
} return id;
}
@Override }
public void run() {
acc.deposit(depositamt, acholdername); class OrderQueue {
acc.withdraw(withdrawamt, acholdername); public synchronized void placeOrder() {
} Order order = new Order();
} System.out.println("Restaurant placed order " +
order.getid());
deliverOrder(order);
public class Main{
}
public static void main(String[] args) {
BankAccount sharedac = new BankAccount(1000);
private void deliverOrder(Order order) {
System.out.println("Delivery driver delivered order "
Thread user1 = new Thread(new User(sharedac, 200, + order.getid());
500, "User1"));
}
Thread user2 = new Thread(new User(sharedac, 200,
500, "User2")); }
Thread user3 = new Thread(new User(sharedac, 200,
500, "User3"));
public class Main {
public static void main(String[] args) { System.out.println(userName + ": Seat " +
seatNumber + " already booked.");
OrderQueue order = new OrderQueue();
}
catch (Exception e)
for (int i = 0; i < 5; i++) {
{
try{
System.out.println("Error: " + e.getMessage());
order.placeOrder();
}
}
}
catch(Exception e){
}
System.out.print("Error occured in the main
process"+e.getMessage());
} class User implements Runnable
} {
} private final SeatManager seatManager;
} private final int seatNumber;
private final String userName;
Ticket Booking System (class with synchronized
methods) public User(SeatManager seatManager, String
userName, int seatNumber)
{
class SeatManager {
this.seatManager = seatManager;
private final boolean[] seats;
this.userName = userName;
public SeatManager(int totalSeats)
this.seatNumber = seatNumber;
{
}
seats = new boolean[totalSeats];
}
@Override
public void run()
public synchronized void bookSeat(String userName,
int seatNumber) {
{ seatManager.bookSeat(userName, seatNumber);
try { }
if (seatNumber < 1 || seatNumber > seats.length) }
{
System.out.println(userName + ": Invalid seat public class Main {
number " + seatNumber);
public static void main(String[] args)
return;
{
}
SeatManager seatManager = new SeatManager(10);
int seatIndex = seatNumber - 1;
Thread user1 = new Thread(new User(seatManager,
if (!seats[seatIndex]) "User1", 2));
{ Thread user2 = new Thread(new User(seatManager,
"User2", 2));
seats[seatIndex] = true;
Thread user3 = new Thread(new User(seatManager,
System.out.println(userName + " booked seat " "User3", 1));
+ seatNumber);
try {
}
user1.start();
else
user1.join();
user2.start(); for (String message : messagesToSend)
user2.join(); {
user3.start(); chatRoom.sendMessage(userName, message);
user3.join(); try {
} Thread.sleep(100);
catch (InterruptedException e) { }
System.out.println("Thread interrupted: " + catch (InterruptedException e) {
e.getMessage());
System.out.println("Thread interrupted: " +
} e.getMessage());
} }
} }
Multithreaded Chat Application }
import java.util.ArrayList; }
import java.util.List;
public class Main {
class ChatRoom { public static void main(String[] args) {
private final List<String> messages = new ChatRoom chatRoom = new ChatRoom();
ArrayList<>(); String[] messages = {"Hello!", "How's it going?"};
public synchronized void sendMessage(String Thread user1 = new Thread(new User(chatRoom,
userName, String message) "Aarya", messages));
{ Thread user2 = new Thread(new User(chatRoom,
String formattedMessage = "New Message: " + "Charan", messages));
userName + ": " + message; Thread user3 = new Thread(new User(chatRoom,
messages.add(formattedMessage); "Kiran", messages));
System.out.println(formattedMessage);
} try {
} user1.start();
user1.join();
class User implements Runnable { user2.start();
private final ChatRoom chatRoom; user2.join();
private final String userName; user3.start();
private final String[] messagesToSend; user3.join();
}
public User(ChatRoom chatRoom, String userName, catch (InterruptedException e) {
String[] messagesToSend) System.out.println("Thread interrupted: " +
{ e.getMessage());
this.chatRoom = chatRoom; }
this.userName = userName; }
this.messagesToSend = messagesToSend; }
} Counting Lines, Words, and
Characters(BufferedReader & FileReader)
@Override import java.io.BufferedReader;

public void run() import java.io.FileReader;

{ import java.io.IOException;
outputStream.write(byteData);
public class Main { }
public static void main(String[] args) { System.out.println("File Copied Successfully");
String filePath = "input.txt"; }
int lineCount = 0; catch (IOException e) {
int wordCount = 0; System.out.println("Error: " + e.getMessage());
int charCount = 0; }
}
try (BufferedReader reader = new }
BufferedReader(new FileReader(filePath))) {
reads a file and displays the file on the screen
String line; (BufferedReader)
while ((line = reader.readLine()) != null) { import java.io.BufferedReader;
lineCount++; import java.io.FileReader;
charCount += line.replaceAll("\\s", "").length(); import java.io.IOException;
String[] words = line.trim().split("\\s+");
wordCount += words.length; public class Main {
} public static void main(String[] args) {
System.out.println("Lines: " + lineCount); String filePath = "input.txt";
System.out.println("Words: " + wordCount); try (BufferedReader reader = new
System.out.println("Characters: " + charCount); BufferedReader(new FileReader(filePath))) {
} String line;
catch (IOException e) { int lineNumber = 1;
System.out.println("Error reading file: " + while ((line = reader.readLine()) != null) {
e.getMessage()); System.out.println(lineNumber + ": " + line);
} lineNumber++;
} }
} }
Copying File Contents (FileInputStream & catch (IOException e) {
FileOutputStream)
System.out.println("Error reading file: " +
import java.io.FileInputStream; e.getMessage());
import java.io.FileOutputStream; }
import java.io.IOException; }
}
public class Main { Calculator Using Swings
public static void main(String[] args) { import javax.swing.*;
String sourceFile = "source.txt"; import java.awt.*;
String destinationFile = "destination.txt"; class Main {
public static void main(String[] args) {
try (FileInputStream inputStream = new JFrame frame = new JFrame("Calculator");
FileInputStream(sourceFile);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL
FileOutputStream outputStream = new OSE);
FileOutputStream(destinationFile)) {
frame.setSize(300, 400);
int byteData;
JPanel panel = new JPanel();
while ((byteData = inputStream.read()) != -1) {
panel.setLayout(new GridLayout(4, 4, 5, 5)); genderGroup.add(femaleButton);
String[] buttons = {
"7", "8", "9", "*", gbc.gridx = 0; gbc.gridy = 0; formPanel.add(new
JLabel("Name:"), gbc);
"4", "5", "6", "/",
gbc.gridx = 1; formPanel.add(nameField, gbc);
"1", "2", "3", "+",
gbc.gridx = 0; gbc.gridy = 1; formPanel.add(new
"0", ".", "=", "-" JLabel("Address:"), gbc);
}; gbc.gridx = 1; formPanel.add(addressField, gbc);
for (String text : buttons) { gbc.gridx = 0; gbc.gridy = 2; formPanel.add(new
JButton button = new JButton(text); JLabel("Gender:"), gbc);
panel.add(button); gbc.gridx = 1; formPanel.add(new JPanel(new
FlowLayout(FlowLayout.LEFT)) {{
}
add(maleButton); add(femaleButton);
frame.add(panel);
}}, gbc);
frame.setVisible(true);
}
add(formPanel, BorderLayout.CENTER);
}
Student details using swings
JPanel buttonPanel = new JPanel();
import javax.swing.*;
JButton saveButton = new JButton("Save"),
import java.awt.*; cancelButton = new JButton("Cancel");
buttonPanel.add(saveButton);
public class Main extends JFrame { buttonPanel.add(cancelButton);
public Main() { add(buttonPanel, BorderLayout.SOUTH);
setTitle("Student Detail");
setSize(300, 200); saveButton.addActionListener(e ->
setDefaultCloseOperation(EXIT_ON_CLOSE); JOptionPane.showMessageDialog(null,

setLocationRelativeTo(null); "Saved details:\nName: " + nameField.getText()


+ "\nAddress: " + addressField.getText() +
setLayout(new BorderLayout());
"\nGender: " + (maleButton.isSelected() ?
"Male" : "Female")));
add(new JLabel("Student Detail", JLabel.CENTER), cancelButton.addActionListener(e -> {
BorderLayout.NORTH);
nameField.setText("");
addressField.setText("");
JPanel formPanel = new JPanel(new
GridBagLayout()); genderGroup.clearSelection();

GridBagConstraints gbc = new });


GridBagConstraints(); }
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL; public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new
JTextField nameField = new JTextField(15), Main().setVisible(true));
addressField = new JTextField(15); }
JRadioButton maleButton = new }
JRadioButton("Male"), femaleButton = new
JRadioButton("Female"); Employee Grading (Class with different
ButtonGroup genderGroup = new ButtonGroup();
members, different methods)
genderGroup.add(maleButton); import java.util.*;
System.out.println("Employee Name="+e.ename);
class Employee System.out.println("Designation="+e.edesig);
{ System.out.println("Salary="+e.esal);
int eid; }
String ename;
String edesig; public static void main(String args[])
int esal; {
char grade; Employee emp=new Employee();
} getemployee(emp);
showgrade(emp);
class Main showemployee(emp);
{ }
public static void getemployee(Employee e) }
{ Fan (Default constructor & Parameterized
Scanner s=new Scanner(System.in); constructor)
e.eid=s.nextInt(); import java.util.*;
s.nextLine();
e.ename=s.nextLine(); public class Main
e.edesig=s.nextLine(); {
e.esal=s.nextInt(); static class fan
} {
private int speed;
public static void showgrade(Employee e) private boolean fon;
{ private int radius;
if(e.esal>-1 && e.esal<20001) private String color;
e.grade='D';
else if(e.esal>20000 && e.esal<=50000) public fan()
e.grade='C'; {
else if(e.esal>50000 && e.esal<=100000) this.speed=1;
e.grade='B'; this.fon=false;
else if(e.esal>100000) this.radius=4;
e.grade='A'; this.color="blue";
else }
System.out.println("Invalid Output");
} public fan(int speed,boolean fon,int radius,String
color)
{
public static void showemployee(Employee e)
this.speed=speed;
{
this.fon=fon;
System.out.println("Employee grade is:");
this.radius=radius;
System.out.println(e.grade+" Grade");
this.color=color;
System.out.println("Employee details are:");
}
System.out.println("Employee ID="+e.eid);
public void updatefan(String color,int radius,boolean import java.util.*;
fon,int speed)
{
public class Main
this.color=color;
{
this.radius=radius;
static class prod
this.fon=fon;
{
this.speed=speed;
int id;
}
String name;
String cat;
public void display()
float price;
{
if(fon)
public void getprod()
System.out.println("ON "+speed+" "+color+"
"+""+radius); {

else Scanner s=new Scanner(System.in);


id=s.nextInt();
System.out.println("OFF "+color+"
"+""+radius); s.nextLine();
} name=s.nextLine();
} cat=s.nextLine();
price=s.nextFloat();
public static void main(String args[]) }
{
Scanner s=new Scanner(System.in); public void showdisc()
int c=s.nextInt(); {
String color=s.next(); System.out.println("Product discount is:");
int radius=s.nextInt(); if(price>=0 && price<51)
boolean ison=s.nextBoolean(); System.out.println("No Discount");
int speed=s.nextInt(); else if(price>50 && price<101)
fan f; System.out.println("10% Off");
if(c==1) else if(price>100 && price<201)
{ System.out.println("20% Off");
f=new fan(); else if(price>200 && price<501)
f.updatefan(color,radius,ison,speed); System.out.println("30% Off");
} else
else System.out.println("40% Off");
f=new fan(speed,ison,radius,color); }
f.display();
s.close(); public void showprod()
} {
} System.out.println("Product details are:");
Product (Class with different members, System.out.println("Product ID="+id);
different methods) System.out.println("Product Name="+name);
System.out.println("Category="+cat);
System.out.printf("Price=%.2f",price); public void showfueleff()
} {
} System.out.println("Vehicle fuel efficiency is:");
if(mil>=0 && mil<16)
public static void main(String args[]) System.out.println("Poor");
{ else if(mil>15 && mil<26)
prod p=new prod(); System.out.println("Average");
p.getprod(); else if(mil>25 && mil<36)
p.showdisc(); System.out.println("Good");
p.showprod(); else if(mil>35 && mil<51)
} System.out.println("Very Good");
} else
Vehicle(Class with different members, different System.out.println("Excellent");
methods) }

import java.util.*; public void showdep()


{
public class Main System.out.println("Vehicle depreciation status
is:");
{
if(year>=0 && year<6)
static class vehicle
System.out.println("New");
{
else if(year>5 && year<11)
int id;
System.out.println("Slightly Used");
String name;
else if(year>10 && year<21)
String type;
System.out.println("Used");
float mil;
else
int year;
System.out.println("Old");
double price;
}

public void getveh()


public void showveh()
{
{
Scanner s=new Scanner(System.in);
System.out.println("Vehicle details are:");
id=s.nextInt();
System.out.println("Vehicle ID="+id);
s.nextLine();
System.out.println("Model Name="+name);
name=s.nextLine();
System.out.println("Type="+type);
type=s.nextLine();
System.out.println("Mileage="+mil);
mil=s.nextFloat();
System.out.println("Year="+year);
s.nextLine();
System.out.printf("Price=%.2f",price);
year=s.nextInt();
}
s.nextLine();
}
price=s.nextDouble();
}
public static void main(String args[])
{
vehicle v=new vehicle(); String
p=String.format("%.1f",Math.floor(this.price*10)/10);
v.getveh();
System.out.println("Book"+n+" Price: "+p);
v.showfueleff();
}
v.showdep();
}
v.showveh();
}
public class Main
}
{
default constructor and two parameterized
constructors: public static void main(String args[])

import java.util.*; {
Book b1=new Book();

class Book b1.display(1);

{ Book b2=new Book("Amatka","Karin Tidbeck");

private String title; b2.display(2);

private String author; Book b3=new Book("Altered Carbon","Richard K.


Morgan",18.99);
private Double price;
b3.display(3);
}
public Book()
}
{
abstract class & abstract methods
this.title="Unknown";
import java.util.*;
this.author="Unknown";
this.price=0.0;
abstract class Geo
}
{
abstract double area();
public Book(String title,String author)
abstract double perimeter();
{
}
this.title=title;
this.author=author;
class triangle extends Geo
this.price=0.0;
{
}
private double s1,s2,s3;
public triangle(double s1,double s2,double s3)
public Book(String title,String author,double price)
{
{
this.s1=s1;
this.title=title;
this.s2=s2;
this.author=author;
this.s3=s3;
this.price=price;
}
}
public double area()
{
public void display(int n)
double s=(s1+s2+s3)/2;
{
return Math.sqrt(s*(s-s1)*(s-s2)*(s-s3));
System.out.println("Book"+n+" Title: "+this.title);
}
System.out.println("Book"+n+" Author:
"+this.author);
public double perimeter() protected double b;
{ public BankAccount(double initialBalance)
return s1+s2+s3; {
} this.b = initialBalance;
} }
public void deposit(double amount)
class square extends Geo {
{ b += amount;
private double s; }
public square(double s) public void withdraw(double amount)
{ {
this.s=s; if (amount <= b)
} b -= amount;
}
public double area()
{ public double getBalance()
return s*s; {
} return b;
}
public double perimeter() }
{
return 4*s; class SavingsAccount extends BankAccount
} {
} private double withdrawLimit;
public SavingsAccount(double initialBalance, double
withdrawLimit)
public class Main
{
{
super(initialBalance);
public static void main(String args[])
this.withdrawLimit = withdrawLimit;
{
}
Geo t=new triangle(4,5,6);
System.out.println("Triangle Area: "+t.area());
public void withdraw(double amount)
System.out.println("Triangle Perimeter:
"+t.perimeter()); {
if (amount <= withdrawLimit)
Geo s=new square(6); super.withdraw(amount);
System.out.println("Square Area: "+s.area()); else
System.out.println("Square Perimeter: System.out.println("Exceeds withdrawal limit for
"+s.perimeter()); SavingsAccount.");
} }
} }
Override
class CheckingAccount extends BankAccount
class BankAccount { {
private double overdraftFee; private String lname;
public CheckingAccount(double initialBalance, double
overdraftFee)
public Person(String fname,String lname)
{
{
super(initialBalance);
this.fname=fname;
this.overdraftFee = overdraftFee;
this.lname=lname;
}
}
public void withdraw(double amount)
{
public String f_name()
if (amount <= getBalance())
{
super.withdraw(amount);
return fname;
else
}
super.withdraw(amount + overdraftFee);
}
public String l_name()
}
{
return lname;
public class Main
}
{
}
public static void withdrawFromAccount(BankAccount
account, double amount)
{
account.withdraw(amount); class Employee extends Person

} {
private int eid;

public static void main(String[] args) private String job;

{ public Employee(String fname,String lname,int


eid,String job)
SavingsAccount sa = new SavingsAccount(2000,
650); {

CheckingAccount ca = new CheckingAccount(1000, super(fname,lname);


100); this.eid=eid;
withdrawFromAccount(sa, 300); this.job=job;
withdrawFromAccount(ca, 250); }
System.out.println("Savings Account Balance: " + public int e_id()
sa.getBalance());
{
System.out.println("Checking Account Balance: " +
ca.getBalance()); return eid;

} }

} public String e_job()


{
Private and override code
return job;
import java.util.*;
}
@Override
class Person
public String toString()
{
{
private String fname;
return f_name()+" "+l_name()+", "+job+"
"+"("+eid+")";
for(i=0;i<c;i++)
}
{
}
for(j=0;j<r;j++)
{
public class Main
System.out.print(tran[i][j]+" ");
{
}
public static void main(String args[])
System.out.println();
{
}
Employee p1=new Employee("Kranthi", "Kiran",
4451, "HR Manager"); s.close();

Employee p2=new Employee("Junior", "Shilpa", }


4452, "Software Manager"); }
System.out.println(p1); Employees of a company (inheritance,
System.out.print(p2); encapsulation, polymorphism, overriding,
} constructors, abstraction, hierarchy, OOP
principles, dynamic dispatch, method
} overloading, encapsulation of behavior, instance
Tranpose of Matrix variables, default implementations, object
import java.util.*;
creation, code reusability, and method
visibility.)
class Employee {
class Main
private String name, address, jobTitle;
{
private double salary;
public static void main(String args[])
{
public Employee(String name, String address, double
Scanner s=new Scanner(System.in); salary, String jobTitle) {
int i,j,r=3,c=3; this.name = name; this.address = address; this.salary
int[][] arr=new int[r][c]; = salary; this.jobTitle = jobTitle;

for(i=0;i<r;i++) }

{
for(j=0;j<c;j++) public String getName() {

{ return name;

arr[i][j]=s.nextInt(); }

} public double getSalary() {

} return salary;
}

int[][] tran=new int[r][c];


for(i=0;i<r;i++) public double calculateBonus() {

{ return 0.0;

for(j=0;j<c;j++) }

{ public String generatePerformanceReport() {

tran[j][i]=arr[i][j]; return "No performance";

} }

} }
public Programmer(String name, String address, double
salary, String language) {
class Manager extends Employee {
super(name, address, salary, language);
public Manager(String name, String address, double
salary) { }
super(name, address, salary, "Manager");
} @Override
@Override public double calculateBonus() {
public double calculateBonus() { return getSalary() * 0.12;
return getSalary() * 0.15; }
} @Override
@Override public String generatePerformanceReport() {
public String generatePerformanceReport() { return "Performance report for Programmer " +
getName() + ": Excellent";
return "Performance report for Manager " +
getName() + ": Excellent"; }
} public void debugCode() {
public void manageProject() { System.out.println("Programmer " + getName() + "
is debugging code in Python");
System.out.println("Manager " + getName() + " is
managing a project."); }
} }
}
public class Main {
class Developer extends Employee { public static void main(String[] args) {
private String language; Manager m = new Manager("Raju Dev", "1 ABC St",
80000);
public Developer(String name, String address, double
salary, String language) { Developer d = new Developer("Neeraj Gupta", "2
PQR St", 72000, "Java");
super(name, address, salary, "Developer");
this.language = language; Programmer p = new Programmer("Sujay Raj", "3
ABC St", 76000, "Python");
}
System.out.println("Manager's Bonus: $" +
m.calculateBonus());
@Override public double calculateBonus() { System.out.println("Developer's Bonus: $" +
return getSalary() * 0.10; d.calculateBonus());
} System.out.println("Programmer's Bonus: $" +
p.calculateBonus());
@Override
public String generatePerformanceReport() { System.out.println(m.generatePerformanceReport());
return "Performance report for Developer " + System.out.println(d.generatePerformanceReport());
getName() + ": Good";
System.out.println(p.generatePerformanceReport());
}
m.manageProject();
public void writeCode() {
d.writeCode();
System.out.println("Developer " + getName() + " is
writing code in " + language); p.debugCode();
} }
} }
Parent share to sons and daughter (Inheritance,
class Programmer extends Developer { Encapsulation, Constructor Chaining,
Polymorphism, Aggregation, Arithmetic
Operations, Modularity, Abstraction, Code public Son1(double amt) {
Reusability, Overriding, Scanner, Type Casting, super(amt);
Input Handling, Resource Management, Output }
Formatting, Design Principles.)
}

import java.util.Scanner;
class Son2 extends FM {
public Son2(double amt) {
class FM {
super(amt);
double amt;
}
public FM(double amt) {
this.amt = amt;
public void giveToSister(Daughter daughter) {
}
double toDaughter = this.amt * 0.10;
daughter.addAmount(toDaughter);
public void addAmount(double add) {
this.deductAmount(toDaughter);
this.amt += add;
}
}
}

public void deductAmount(double ded) {


class Daughter extends FM {
this.amt -= ded;
public Daughter(double amt) {
}
super(amt);
}
public double getAmount() {
}
return this.amt;
}
public class Main
}
{
public static void main(String[] args) {
class Father extends FM {
Scanner s = new Scanner(System.in);
public Father(double amt) {
double fatherAmount = s.nextDouble();
super(amt);
double son1Amount = s.nextDouble();
}
double son2Amount = s.nextDouble();
double daughterAmount = s.nextDouble();
public void distributeAmount(Son1 son1, Son2 son2) {
Father f = new Father(fatherAmount);
double toSon1 = this.amt * 0.20;
Son1 s1 = new Son1(son1Amount);
son1.addAmount(toSon1);
Son2 s2 = new Son2(son2Amount);
this.deductAmount(toSon1);
Daughter d = new Daughter(daughterAmount);
f.distributeAmount(s1, s2);
double toSon2 = this.amt * 0.20;
s2.giveToSister(d);
son2.addAmount(toSon2);
System.out.println("FATHER AMOUNT:" + (int)
this.deductAmount(toSon2); f.getAmount());
} System.out.println("SON1 AMOUNT:" + (int)
} s1.getAmount());
System.out.println("SON2 AMOUNT:" + (int)
s2.getAmount());
class Son1 extends FM {
System.out.println("DAUGHTER AMOUNT:" + {
(int) d.getAmount());
n[i]=s.nextInt();
s.close();
}
}
Arrays.sort(n);
}
for(i=0;i<n.length;i++)
all duplicate elements in an array System.out.println(n[i]);
import java.util.*; s.close();
class Main }
{ }
public static void main(String args[])
remove duplicate elements from an array.
{
import java.util.*;
Scanner s=new Scanner(System.in);
int x=7;
class Main
int[] n=new int[x];
{
for(int i=0;i<n.length;i++)
public static void main(String args[])
{
{
n[i]=s.nextInt();
Scanner s=new Scanner(System.in);
}
int i,j=0,x=7;
for(int i=0;i<n.length;i++)
int[] n=new int[x];
{
for(i=0;i<n.length;i++)
for(int j=i+1;j<n.length;j++)
n[i]=s.nextInt();
{
int[] t=new int[x];
if(n[i]==n[j])
for(i=0;i<n.length;i++)
System.out.println(n[j]);
{
}
boolean dup=false;
}
for(int k=0;k<j;k++)
s.close();
{
}
if(n[i]==n[k])
}
{
sort an array of integers in ascending and dup=true;
descending order( with pre bulit array
break;
functions)
}
import java.util.*;
}
import java.util.Arrays;
if(!dup)
n[j++]=n[i];
class Main
}
{
for(i=0;i<j;i++)
public static void main(String args[])
System.out.print(n[i]+" ");
{
s.close();
Scanner s=new Scanner(System.in);
}
int i,x=5;
}
int[] n=new int[x];
for(i=0;i<n.length;i++) vector Collection
import java.util.Vector; productName = sc.nextLine();
reviewerName = sc.nextLine();
public class Main1 { rating = sc.nextInt();
public static void main(String[] args) { sc.nextLine(); // Consume newline
Vector<Integer> vector = new Vector<>(); reviewDate = sc.nextLine();
vector.add(10); comments = sc.nextLine();
vector.add(20); }
vector.add(30); public void showRatingCategory() {
vector.add(40); if (rating == 5) {
System.out.println("Vector elements: " + vector); System.out.println("Review rating
is:\nExcellent");
vector.remove(Integer.valueOf(20));
} else if (rating == 4) {
System.out.println("Vector elements after removal: "
+ vector); System.out.println("Review rating is:\nVery
Good");
int element = vector.get(1);
} else if (rating == 3) {
System.out.println("Element at index 1: " + element);
System.out.println("Review rating is:\nGood");
}
} else if (rating == 2) {
}
System.out.println("Review rating is:\nFair");
Movie_details_week 5_5 (Class, Object,
Attributes, Methods, Encapsulation, Input } else if (rating == 1) {
Handling, Conditional Statements, Scanner, System.out.println("Review rating is:\nPoor");
String Operations, Integer Operations, Code }
Reusability, Modularity, Control Flow,
}
Resource Management, Output Formatting,
Main Method.)
import java.util.Scanner; public void showReview() {
System.out.println("Review details are:");
public class Main { System.out.println("Review ID=" + reviewId);
int reviewId; System.out.println("Product Name=" +
productName);
String productName;
System.out.println("Reviewer Name=" +
String reviewerName; reviewerName);
int rating; System.out.println("Rating=" + rating);
String reviewDate; System.out.println("Review Date=" + reviewDate);
String comments; System.out.println("Comments=" + comments);
}
// Method to get the review details
public void getReview() { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Main review = new Main();
review.getReview();
// Input for review details review.showRatingCategory();
// System.out.print("Enter Review ID: "); review.showReview();
reviewId = sc.nextInt(); }
sc.nextLine(); // Consume newline }
Student_details_7_2 (Class, Object, Attributes,
//System.out.print("Enter Product Name: "); Constructor, Static Variable, Static Method,
Encapsulation, Method Overloading, Code System.out.println("Student Details:");
Reusability, Access Modifiers, Print Statements, s1.displayStudentDetails();
Main Method, Modularity, Parameterized s2.displayStudentDetails();
Constructor, String Handling, Double
Operations.) s3.displayStudentDetails();

public class Main { System.out.println("Total Students: " +


Student.getTotalStudents());
public static class Student {
}
private int rollNumber;
}
private String name;
GeometricShape 8_1_1 (Abstract Class,
private int age;
Abstract Method, Method Overriding,
private String course; Encapsulation, Constructor, Private Attributes,
private double marks; Inheritance, Polymorphism, Area Calculation,
Perimeter Calculation, Main Method, Object
private static int totalStudents = 0;
Creation, Print Statements, Code Reusability,
public Student(int rollNumber, String name, int age, Double Operations, Modularity.)
String course, double marks) {
abstract class geometricshape{
this.rollNumber = rollNumber;
abstract double area();
this.name = name;
abstract double perimeter();
this.age = age;
}
this.course = course;
class triangle extends geometricshape{
this.marks = marks;
private double base;
totalStudents++;
private double height;
}
private double s1;
private double s2;
public static int getTotalStudents() {
private double s3;
return totalStudents;
public triangle(double base,double height,double
} s1,double s2,double s3){
this.base=base;
public void displayStudentDetails() { this.height=height;
System.out.println("Roll Number: " + this.s1=s1;
rollNumber);
this.s2=s2;
System.out.println("Name: " + name);
this.s3=s3;
System.out.println("Age: " + age);
System.out.println("Course: " + course);
}
System.out.println("Marks: " + marks);
System.out.println();
double area(){
}
return 0.5*base*height;
}
}
double perimeter(){
public static void main(String[] args) {
return s1+s2+s3;
Student s1 = new Student(1, "Prabhas Raj", 20,
"Computer Science", 85.5); }
Student s2 = new Student(2, "Vishwa Tej", 22,
"Mechanical Engineering", 90.0); }
Student s3 = new Student(3, "Vishal Shekar", 21,
"Biotechnology", 88.75);
class square extends geometricshape{ public Bank(double amount,double rate){
private double side; this.amount=amount;
this.rate=rate;
public square(double side){ }
this.side=side; @Override
} double fee(){
return (rate/100)*amount;
double area(){ }
return side*side; @Override
} public String details(){
double fee=fee();
double perimeter(){ return String.format("Bank Transfer of %.2f with a
fee rate of %.2f%%. Transaction fee: %.2f ",amount,rate,fee);
return 4*side;
}
}
}
}
class Creditcard extends Financial{
private double amount;
public class Main{
private double fixedfee;
public static void main(String args[]){
private double pfee;
triangle t1=new triangle(5,6,5,4,3);
public Creditcard(double amount,double
fixedfee,double pfee){
System.out.println("Triangle area: "+t1.area()); this.amount=amount;
System.out.println("Triangle perimeter: this.fixedfee=fixedfee;
"+t1.perimeter());
this.pfee=pfee;
}
square s1=new square(4);
@Override
System.out.println("Square area: "+s1.area());
double fee(){
System.out.println("Square perimeter:
"+s1.perimeter()); return fixedfee+(pfee/100)*amount;
} }
} @Override
Bank_Finacial_8_1_2 (Abstract Class, Abstract public String details(){
Method, Method Overriding, Inheritance, double fee=fee();
Constructor, Encapsulation, String Formatting, return String.format("Credit Card Payment of %.2f
Polymorphism, Fee Calculation, Method with a fixed fee of %.2f and percentage fee rate of %.2f%%.
Implementation, Double Operations, Print Total transaction fee: %.2f",amount,fixedfee,pfee,fee);
Statements, Code Reusability, Transaction }
Calculation, Parameters Passing.)
}
abstract class Financial{
public class Main{
abstract double fee();
public static void main(String[] args){
abstract String details();
Bank bank=new Bank(1000.00,1.5);
}
System.out.println(bank.details());
class Bank extends Financial{
System.out.println("Calculated Bank Transfer fee:
private double amount; "+bank.fee());
private double rate; System.out.println();
Creditcard card=new Creditcard(1000.00,2.50,2.0); public class Main {
System.out.println(card.details()); public static void main(String[] args) {
System.out.println("Calculated Credit Card Payment PercentageDiscount percentageDiscount = new
fee: "+card.fee()); PercentageDiscount(10.0);
} double totalAmount1 = 200.00;
}
System.out.println(percentageDiscount.discountDetails());
Abstarct_class_Discount 8_1_3 (Abstract Class,
Abstract Method, Method Overriding, System.out.println("Final amount after discount: $" +
percentageDiscount.applyDiscount(totalAmount1));
Inheritance, Constructor, Encapsulation, String
Formatting, Polymorphism, Discount FixedAmountDiscount fixedAmountDiscount = new
Calculation, Method Implementation, FixedAmountDiscount(30.00);
Parameters Passing, Double Operations, Code double totalAmount2 = 200.00;
Reusability, Print Statements, Tax Calculation.)
abstract class Discount { System.out.println(fixedAmountDiscount.discountDetails());

abstract double applyDiscount(double totalAmount); System.out.println("Final amount after discount: $" +


fixedAmountDiscount.applyDiscount(totalAmount2));
abstract String discountDetails();
}
}
}
class PercentageDiscount extends Discount {
Abstarct_Bank_Account_9_2_1 (Abstract
private double discountRate;
Class, Abstract Method, Inheritance, Method
public PercentageDiscount(double discountRate) { Overriding, Constructor, Encapsulation, String
this.discountRate = discountRate; Formatting, Interest Calculation, Account
}
Types, Polymorphism, Balance Deduction, Fee
Calculation, Print Statements, Overridden
Methods.)
double applyDiscount(double totalAmount) { abstract class BankAccount {
return totalAmount - (totalAmount * (discountRate / protected double balance;
100));
public BankAccount(double balance) {
}
this.balance = balance;
String discountDetails() {
}
return String.format("Percentage Discount of
%.2f%%",discountRate); abstract double calculateInterest();
} abstract String accountDetails();
} }
class FixedAmountDiscount extends Discount { class SavingsAccount extends BankAccount {
private double fixedAmount; private double annualInterestRate;
public FixedAmountDiscount(double fixedAmount) { public SavingsAccount(double balance, double
annualInterestRate) {
this.fixedAmount = fixedAmount;
super(balance);
}
this.annualInterestRate = annualInterestRate;
double applyDiscount(double totalAmount) {
}
return totalAmount - fixedAmount;
@Override
}
double calculateInterest() {
String discountDetails() {
return balance * (annualInterestRate / 100);
return String.format("Fixed Discount of
%.2f",fixedAmount); }
} @Override
} public String accountDetails() {
double interestEarned = calculateInterest(); Return, Conditionals, Load Weight Adjustment,
return String.format("Savings Account\nBalance: Print Statements.)
$%.1f\nAnnual Interest Rate: %.1f%%\nInterest Earned: abstract class Vehicle {
$%.1f",
protected double milesDriven;
balance, annualInterestRate,
interestEarned); protected double fuelUsed;
} public Vehicle(double milesDriven, double fuelUsed) {
} this.milesDriven = milesDriven;
class CheckingAccount extends BankAccount { this.fuelUsed = fuelUsed;
private double monthlyFee; }
public CheckingAccount(double balance, double abstract double calculateFuelEfficiency();
monthlyFee) {
abstract String getVehicleType();
super(balance);
}
this.monthlyFee = monthlyFee;
class Car extends Vehicle {
}
public Car(double milesDriven, double fuelUsed) {
@Override
super(milesDriven, fuelUsed);
double calculateInterest() {
}
return 0.0;
@Override
}
double calculateFuelEfficiency() {
@Override
return milesDriven / fuelUsed;
public String accountDetails() {
}
double finalBalance = balance - monthlyFee;
@Override
return String.format("Checking Account\nBalance:
public String getVehicleType() {
$%.1f\nMonthly Maintenance Fee: $%.1f\nInterest Earned:
$%.1f\nAfter deducting monthly fee: $%.1f", return "Car";
balance, monthlyFee, }
calculateInterest(), finalBalance);
}
}
class Truck extends Vehicle {
}
private double loadWeight;
public class Main {
public Truck(double milesDriven, double fuelUsed,
public static void main(String[] args) { double loadWeight) {
SavingsAccount savingsAccount = new super(milesDriven, fuelUsed);
SavingsAccount(1000.00, 5.0);
this.loadWeight = loadWeight;

System.out.println(savingsAccount.accountDetails()); }

System.out.println(); @Override

CheckingAccount checkingAccount = new double calculateFuelEfficiency() {


CheckingAccount(1500.00, 12.00); double efficiency = milesDriven / fuelUsed;
if (loadWeight > 1000) {
System.out.println(checkingAccount.accountDetails());
efficiency -= efficiency * 0.08;
}
}
}
return efficiency;
Abstarct_class_Vehicle_9_2_2 (Abstract Class, }
Abstract Method, Inheritance, Method
Overriding, Constructor, Polymorphism, Fuel @Override
Efficiency Calculation, Vehicle Types, String public String getVehicleType() {
return "Truck";
} }
} }
public class Main {
public static void main(String[] args) {
Car car = new Car(300.0, 15.0);
System.out.println("Vehicle Type: " +
car.getVehicleType());
System.out.println("Fuel Efficiency: " +
car.calculateFuelEfficiency() + " MPG");
System.out.println();
Truck truck = new Truck(400.0, 20.0, 2000.0);
System.out.println("Vehicle Type: " +
truck.getVehicleType());
System.out.println("Fuel Efficiency: " +
truck.calculateFuelEfficiency() + " MPG");

You might also like