Professional Documents
Culture Documents
Chit
Chit
// Convert input character to lowercase to handle both cases (upper and lower)
ch = Character.toLowerCase(ch);
scanner.close();
}
}
System.out.print("a = ");
double a = scanner.nextDouble();
System.out.print("b = ");
double b = scanner.nextDouble();
System.out.print("c = ");
double c = scanner.nextDouble();
// Calculate discriminant
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
} else if (discriminant == 0) {
} else {
scanner.close();
System.out.println(base + " raised to the power of " + exponent + " is: " + result);
scanner.close();
}
System.out.println("Armstrong numbers between " + lower + " and " + upper + ":");
if (isArmstrong(num)) {
scanner.close();
int n = numberOfDigits(number);
originalNumber = number;
while (originalNumber != 0) {
originalNumber /= 10;
if (result == number) {
return true;
} else {
return false;
int count = 0;
while (number != 0) {
number /= 10;
count++;
}
return count;
25. Write a Java Program to Display Prime Numbers Between Intervals Using Function
import java.util.Scanner;
System.out.println("Prime numbers between " + lower + " and " + upper + ":");
if (isPrime(num)) {
scanner.close();
if (number <= 1) {
if (number == 2) {
if (number % 2 == 0) {
// Check for odd divisors from 3 up to the square root of the number
if (number % i == 0) {
26. Write a Java Program to Display Armstrong Numbers Between Intervals Using Function
import java.util.Scanner;
System.out.println("Armstrong numbers between " + lower + " and " + upper + ":");
if (isArmstrong(num)) {
}
scanner.close();
originalNumber = number;
while (originalNumber != 0) {
originalNumber /= 10;
if (result == number) {
return true;
} else {
return false;
1. Write a Java program to find the sum of even numbers in an integer array
public class SumOfEvenNumbers {
public static void main(String[] args) {
// Sample array
int[] array = {2, 5, 8, 3, 10, 6, 7, 1};
// Initialize sum
int sum = 0;
// Iterate through the array
for (int i = 0; i < array.length; i++) {
// Check if the current element is even
if (array[i] % 2 == 0) {
sum += array[i]; // Add even number to sum
}
}
3. Write a Java program to find duplicate elements in a 1D array and find their frequency of occurrence.
import java.util.HashMap;
import java.util.Map;
ThreeD Class
// ThreeD class
class ThreeD {
private static final double PI = 3.14159; // Constant PI value
System.out.println("Sphere:");
System.out.println("Radius: " + sphereRadius);
System.out.println("Volume: " + sphereVolume);
System.out.println("Surface Area: " + sphereSurfaceArea);
System.out.println();
// Calculate volume and surface area of a cone with radius 3.0 and slant height 4.0
double coneRadius = 3.0;
double coneHeight = 4.0;
double coneVolume = shape.volume(coneRadius, coneHeight);
double coneSurfaceArea = shape.surfaceArea(coneRadius, coneHeight);
System.out.println("Cone:");
System.out.println("Radius: " + coneRadius);
System.out.println("Height: " + coneHeight);
System.out.println("Volume: " + coneVolume);
System.out.println("Surface Area: " + coneSurfaceArea);
System.out.println();
// Calculate volume and surface area of a cylinder with radius 2.0 and height 6.0
double cylinderRadius = 2.0;
double cylinderHeight = 6.0;
String cylinderType = "cylinder";
double cylinderVolume = shape.volume(cylinderRadius, cylinderHeight, cylinderType);
double cylinderSurfaceArea = shape.surfaceArea(cylinderRadius, cylinderHeight,
cylinderType);
System.out.println("Cylinder:");
System.out.println("Radius: " + cylinderRadius);
System.out.println("Height: " + cylinderHeight);
System.out.println("Volume: " + cylinderVolume);
System.out.println("Surface Area: " + cylinderSurfaceArea);
}
}
Computer Class
// Computer class
class Computer {
private static int nextModelNo = 1; // Auto-generated model number
private int model_no;
private int RAM_size;
private String Processor_name;
private double Price;
// Parameterized constructor
public Computer(int RAM_size, String Processor_name, double Price) {
this.model_no = nextModelNo++;
this.RAM_size = RAM_size;
this.Processor_name = Processor_name;
this.Price = Price;
}
// Non-parameterized constructor
public Computer() {
this.model_no = nextModelNo++;
this.RAM_size = 0;
this.Processor_name = "Unknown";
this.Price = 0.0;
}
System.out.println("Computer 2:");
comp2.display();
System.out.println();
6. Create a class Box . The class should have volume() and surfaceArea() to calculate volume and surface
area of a box. Must apply the concept of overloading .
Box Class
// Box class
class Box {
// Method to calculate volume of a cube
public double volume(double side) {
return side * side * side;
}
// Calculate volume and surface area of a rectangular box with dimensions 3.0 x 4.0 x
5.0
double length = 3.0;
double width = 4.0;
double height = 5.0;
double rectangularVolume = box.volume(length, width, height);
double rectangularSurfaceArea = box.surfaceArea(length, width, height);
System.out.println("Rectangular Box - Dimensions: " + length + " x " + width + " x " +
height);
System.out.println("Rectangular Box - Volume: " + rectangularVolume);
System.out.println("Rectangular Box - Surface Area: " + rectangularSurfaceArea);
}
}
7. Create a class Circle with properties radius. PI value should be declare as constant and shared mode.
The class should have method Area(), Perimeter() and display(). display() will show the value of
radius,area and perimeter. Only display() is accessible through object.
Circle Class
// Circle class
class Circle {
private double radius;
private static final double PI = 3.14159; // Constant PI value
8. Write a class, Commission, which has an instance variable, sales; an appropriate constructor; and a
method, commission() that returns the commission. Now write a demo class to test the Commission
class by reading a sale from the user, using it to create a Commission object after validating that the
value is not negative. Finally, call the commission() method to get and print the commission. If the sales
are negative, your demo should print the message “Invalid Input”.
Commission Class
// Commission class
class Commission {
private double sales;
// Constructor
public Commission(double sales) {
this.sales = sales;
}
CommissionDemo Class
import java.util.Scanner;
// Demo class to test Commission classpublic class CommissionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if (commission == -1) {
System.out.println("Invalid Input");
} else {
System.out.println("Commission: $" + commission);
}
}
scanner.close();
}
}
1. Write a Java program to create a class called Vehicle with a method called drive(). Create a subclass
called Car that overrides the drive() method to print "Repairing a car".
// Base class Vehicle
class Vehicle {
// Method to drive (to be overridden)
public void drive() {
System.out.println("Driving a vehicle");
}
}
2. Write a Java program to create a class called Shape with a method called getArea(). Create a subclass
called Rectangle that overrides the getArea() method to calculate the area of a rectangle.
// Base class Shape
class Shape {
// Method to calculate area (to be overridden)
public double getArea() {
return 0; // Default implementation returns 0
}
}
// Constructor
public Employee(double salary) {
this.salary = salary;
}
System.out.println();
4. Write a Java program to create a class known as "BankAccount" with methods called deposit() and
withdraw(). Create a subclass called SavingsAccount that overrides the withdraw() method to prevent
withdrawals if the account balance falls below one hundred.
// Base class BankAccount
class BankAccount {
protected double balance;
// Constructor
public BankAccount() {
this.balance = 0;
}
5. Write a Java program to create a class called Shape with methods called getPerimeter() and getArea().
Create a subclass called Circle that overrides the getPerimeter() and getArea() methods to calculate the
area and perimeter of a circle.
// Base class Shape
class Shape {
// Method to get the perimeter (to be overridden)
public double getPerimeter() {
return 0;
}
6. Write a Java program that creates a class hierarchy for employees of a company. The base class
should be Employee, with subclasses Manager, Developer, and Programmer. Each subclass should have
properties such as name, address, salary, and job title. Implement methods for calculating bonuses,
generating performance reports, and managing projects.
public Manager(String name, String address, double salary, String jobTitle, String department) {
super(name, address, salary, jobTitle);
this.department = department;
}
@Override
public double calculateBonus() {
return salary * 0.15; // Managers get a 15% bonus
}
@Override
public String generatePerformanceReport() {
return "Performance report for Manager " + name + " in " + department + ": Excellent leadership and
management skills.";
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Department: " + department);
}
}
public Developer(String name, String address, double salary, String jobTitle, String
programmingLanguage) {
super(name, address, salary, jobTitle);
this.programmingLanguage = programmingLanguage;
}
@Override
public double calculateBonus() {
return salary * 0.12; // Developers get a 12% bonus
}
@Override
public String generatePerformanceReport() {
return "Performance report for Developer " + name + ": Outstanding coding and development skills.";
}
public void developSoftware(String softwareName) {
System.out.println("Developer " + name + " is developing the software: " + softwareName + " using " +
programmingLanguage);
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Programming Language: " + programmingLanguage);
}
}
public Programmer(String name, String address, double salary, String jobTitle, String[] projects) {
super(name, address, salary, jobTitle);
this.projects = projects;
}
@Override
public double calculateBonus() {
return salary * 0.10; // Programmers get a 10% bonus
}
@Override
public String generatePerformanceReport() {
return "Performance report for Programmer " + name + ": Highly efficient in multiple projects.";
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Projects: " + String.join(", ", projects));
}
}
System.out.println("Manager Info:");
manager.displayInfo();
System.out.println("Bonus: " + manager.calculateBonus());
System.out.println(manager.generatePerformanceReport());
((Manager) manager).manageProject("ProjectX");
System.out.println();
System.out.println("Developer Info:");
developer.displayInfo();
System.out.println("Bonus: " + developer.calculateBonus());
System.out.println(developer.generatePerformanceReport());
((Developer) developer).developSoftware("SoftwareY");
System.out.println();
System.out.println("Programmer Info:");
programmer.displayInfo();
System.out.println("Bonus: " + programmer.calculateBonus());
System.out.println(programmer.generatePerformanceReport());
((Programmer) programmer).writeCode("ProjectB");
}
}
7. Create a general class ThreeDObject and derive the classes Box, Cube, Cylinder and Cone from it. The
class ThreeDObject has methods wholeSurfaceArea ( ) and volume ( ). Override these two methods in
each of the derived classes to calculate the volume and whole surface area of each type of three-
dimensional objects. The dimensions of the objects are to be taken from the users and passed through
the respective constructors of each derived class. Write a main method to test these classes.
import java.util.Scanner;
// Base class ThreeDObject
abstract class ThreeDObject {
abstract double wholeSurfaceArea();
abstract double volume();
}
@Override
double wholeSurfaceArea() {
return 2 * (length * width + width * height + height * length);
}
@Override
double volume() {
return length * width * height;
}
}
@Override
double wholeSurfaceArea() {
return 6 * side * side;
}
@Override
double volume() {
return side * side * side;
}
}
@Override
double wholeSurfaceArea() {
return 2 * Math.PI * radius * (radius + height);
}
@Override
double volume() {
return Math.PI * radius * radius * height;
}
}
@Override
double wholeSurfaceArea() {
double slantHeight = Math.sqrt(radius * radius + height * height);
return Math.PI * radius * (radius + slantHeight);
}
@Override
double volume() {
return (1.0 / 3) * Math.PI * radius * radius * height;
}
}
// Main class to test the implementation
public class ThreeDObjectTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the dimensions for the Box (length, width, height): ");
double length = scanner.nextDouble();
double width = scanner.nextDouble();
double height = scanner.nextDouble();
ThreeDObject box = new Box(length, width, height);
System.out.println("Box Surface Area: " + box.wholeSurfaceArea());
System.out.println("Box Volume: " + box.volume());
scanner.close();
}
8. An educational institution maintains a database of its employees. The database is divided into a
number of classes whose hierarchical relationships are shown below. Write all the classes and define the
methods to create the database and retrieve individual information as and when needed. Write a driver
program to test the classes. Staff (code, name) Teacher (subject, publication) is a Staff Officer (grade) is a
Staff Typist (speed) is a Staff RegularTypist (remuneration) is a Typist CasualTypist (daily wages) is a
Typist.
// Base class Staff
class Staff {
private int code;
private String name;
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Subject: " + subject + ", Publication: " + publication);
}
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Grade: " + grade);
}
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Speed: " + speed + " wpm");
}
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Remuneration: " + remuneration);
}
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Daily Wages: " + dailyWages);
}
}
// Driver class to test the classes
public class EducationalInstitution {
public static void main(String[] args) {
Staff staff1 = new Teacher(101, "Alice", "Mathematics", "OUP");
Staff staff2 = new Officer(102, "Bob", "A");
Staff staff3 = new RegularTypist(103, "Charlie", 70, 3000.0);
Staff staff4 = new CasualTypist(104, "David", 60, 200.0);
staff1.displayInfo();
System.out.println();
staff2.displayInfo();
System.out.println();
staff3.displayInfo();
System.out.println();
staff4.displayInfo();
}
}
1. Write a Java program to create an interface Shape with the getArea(), getPerimeter() method. Create
three classes Rectangle, Circle, and Triangle that implement the Shape interface. Implement the
getArea() method for each of the three classes.
// Define the Shape interface
interface Shape {
double getArea();
double getPerimeter();
this.radius = radius;
@Override
}
@Override
this.length = length;
this.width = width;
@Override
@Override
this.side2 = side2;
this.side3 = side3;
@Override
@Override
}
2. Write a Java programming to create a banking system with interface Account and classes
SavingsAccount, and CurrentAccount. The bank should have a list of accounts and methods for adding
them. Accounts should be an interface with methods to deposit, withdraw, calculate interest, and view
balances. SavingsAccount and CurrentAccount should implement the Account interface and have their
own unique methods.
import java.util.ArrayList;
import java.util.List;
interface Account {
double calculateInterest();
double getBalance();
void viewBalance();
this.balance = initialBalance;
this.interestRate = interestRate;
@Override
if (amount > 0) {
balance += amount;
@Override
public void withdraw(double amount) {
balance -= amount;
} else {
System.out.println("Insufficient funds.");
@Override
@Override
return balance;
@Override
this.balance = initialBalance;
this.overdraftLimit = overdraftLimit;
}
@Override
if (amount > 0) {
balance += amount;
@Override
balance -= amount;
} else {
@Override
return 0;
@Override
return balance;
@Override
}
// Implement the Bank class
class Bank {
public Bank() {
accounts.add(account);
System.out.println("Account added.");
account.viewBalance();
bank.addAccount(savingsAccount);
bank.addAccount(currentAccount);
savingsAccount.deposit(500);
savingsAccount.withdraw(200);
currentAccount.withdraw(700);
currentAccount.withdraw(200);
bank.viewAllBalances();
3. Write a Java program to create an interface Sortable with a method sort() that sorts an array of
integers in ascending order. Create two classes BubbleSort and SelectionSort that implement the
Sortable interface and provide their own implementations of the sort() method.
package Assinment4;
@Override
public int[] sort(int[] a) {
// TODO Auto-generated method stub
int n = a.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 1; j < n; j++) {
if (a[j-1] > a[j]) {
// swap arr[j] and arr[j+1]
int temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
return a;
}
package Assinment4;
}
package Assinment4;
import java.util.Scanner;
4. Write a program to check if the letter 'e' is present in the word 'Umbrella'.
package Assinment4;
}
5. Write a program that takes your full name as input and displays the abbreviations of the first and
middle names except the last name which is displayed as it is. For example, if your name is Robert Brett
Roser, then the output should be R.B.Roser.
package Assinment4;
import java.util.Scanner;
6. Write a Java program to compare a given string to the specified character sequence
class HelloWorld {
public static void main(String[] args) {
String s1="today is good day";
String s2="days";
boolean f=false;
for(int i=0;i<s1.length()-s2.length();i++){
if(s1.substring(i,i+s2.length()).equals(s2)){
f=true;
break;
}
}
if(f){
System.out.println("found");
}
else{
System.out.println("not found");
}
}
}
7. Write a Java program to Swap Two Strings without Third String Variable.
package Assinment4;
import java.util.Scanner;
import java.util.Scanner;
if (maxLength == 1) {
return ""; // No palindromic substring found
}
Ass 5
1. Write a Java program to create a method that takes a string as input and throws an exception if the
string does not contain vowels.
public class MyException extends Exception{
String str1;
MyException(String str2){
str1=str2;
}
public String toString(){
return ("Exception occured: "+str1);
}
}
package College;
import java.util.Scanner;
package College;
}
}
public void withdraw(double amount)throws MyException{
if(amount<0){
throw new MyException("Negative amount is not
valid");
}
else{
if(amount>balance){
throw new MyException("Not allowed!! amount
is greater than balance");
}
else if(balance<=1000){
throw new MyException("Not allowed!! Balance
should be minimum 1000 rs.");
}
else{
balance-=amount;
System.out.println(amount+" amount
withdrawn!");
// System.out.println("Account ID "+acc_id);
// System.out.println("Customer name "+C_name);
// System.out.println("Current balance
"+balance);
}
}
}
public void display_details() {
System.out.println("Customer ID: "+acc_id+" Customer
Name: "+C_name+" BanK Balance: "+balance);
}
package College;
import java.util.Scanner;
if(ch==1){
System.out.println("Enter amount for
deposit");
double amount=sc.nextDouble();
ob.deposit(amount);
}
else if(ch==2){
System.out.println("Enter amount for
withdraw:");
double amount=sc.nextDouble();
ob.withdraw(amount);
}
else if(ch==3){
ob.display_details();
}
else{
System.out.println("End of program....");
break;
}
}
}catch(Exception exp){
System.out.println(exp);
}
3. Write a program called Factorial.java that computes factorials and catches the result in an array of
type long for reuse.
The long type of variable has its own range. For example 20! Is as high as the range of long type. So check
the argument passes and “throw an exception”,
if it is too big or too small.
If x is less than 0 throw an IllegalArgumentException with a message “Value of x must be positive”.
If x is above the length of the array throw an IllegalArgumentException with a message “Result will
overflow”. Here x is the value for which we want to find the factorial.
import java.util.Scanner;
public class Main {
public static long factorials[]=new long[20+1];
public static long factorialcheck(int x){
if(x<0){
throw new IllegalArgumentException("Value of x must be positive");
}
if(x>20){
throw new IllegalArgumentException("Result will overflow");
}
if(x ==0 || x==1){
return factorials[x]=1;
}
else{
factorials[x]=x*factorialcheck(x-1);
}
return factorials[x];
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of terms:");
int terms=sc.nextInt();
int arr[]=new int[terms];
for(int i=0;i<terms;i++){
arr[i]=sc.nextInt();
}
for( int i:arr){
try{
System.out.println("factorial:"+factorialcheck(i));
}catch(IllegalArgumentException e){
System.out.println("Error:"+e);
}
}
}
}
4. Write a Java program to get following informations of the current executing thread :
the thread's name, ID, priority, state, daemon status, liveness, and interruption status
public class CurrentThreadInfo
{
public static void main(String[] args)
{
// Get the current executing thread
Thread currentThread = Thread.currentThread();
// Print thread information
System.out.println("Thread Name : " + currentThread.getName());
System.out.println("Thread ID : " + currentThread.getId());
System.out.println("Thread Priority : " + currentThread.getPriority());
System.out.println("Thread State : " + currentThread.getState());
System.out.println("Thread is Daemon : " + currentThread.isDaemon());
System.out.println("Thread is Alive : " + currentThread.isAlive());
System.out.println("Thread is Interrupted : " +currentThread.isInterrupted());
}}
5. Write a Java program in which total 4 threads should run. Set different priorities to the thread.
public class ThreadDemo extends Thread {
public void run()
{
System.out.println("Inside run method");
}
public static void main(String[] args)
{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
System.out.println("t1 thread priority : "+ t1.getPriority());
System.out.println("t2 thread priority : "+ t2.getPriority());
System.out.println("t3 thread priority : "+ t3.getPriority());
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
System.out.println("t1 thread priority : "+ t1.getPriority());
System.out.println("t2 thread priority : "+ t2.getPriority());
System.out.println("t3 thread priority : "+ t3.getPriority());
System.out.println("Currently Executing Thread : "+ Thread.currentThread().getName());
System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());
}
}
6. Write a Java program to create and start multiple threads that increment a shared counter variable
concurrently.
class IncrementThread extends Thread {
private Counter counter;
private int incrementsPerThread;
public IncrementThread(Counter counter, int incrementsPerThread) {
this.counter = counter;
this.incrementsPerThread = incrementsPerThread;
}
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
class Buffer {
private Queue<Integer> queue = new LinkedList<>();
private int capacity;
queue.add(value);
System.out.println("Produced: " + value);
notifyAll();
}
notifyAll();
return value;
}
}
@Override
public void run() {
int value = 0;
while (true) {
try {
buffer.produce(value++);
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}
@Override
public void run() {
while (true) {
try {
buffer.consume();
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}
producerThread.start();
consumerThread.start();
}
}
Prevention:
public class TestDeadlock{
public static void main(String args[]){
final String r1="Printer";
final String r2="Speaker";
//t1 tries to lock r1 then r2
Thread t1=new Thread(){
public void run(){
synchronized(r1){
System.out.println("Thread1:locked resource1");
try{Thread.sleep(100);}catch(Exception e){}
}
synchronized(r2){
System.out.println("Thread1:locked resource2");
try{Thread.sleep(100);}catch(Exception e){}
}
}
};
//t2 tries to lock r2 then r1
Thread t2=new Thread(){
public void run(){
synchronized(r2){
System.out.println("Thread2:locked resource2");
try{Thread.sleep(100);}catch(Exception e){}
}
synchronized(r1){
System.out.println("Thread2:locked resource1");
try{Thread.sleep(100);}catch(Exception e){}
}
}
};
t1.start();
t2.start();
}
}
Test.java
class Customer{
int amount=10000;
}}