class BankAccount { double balance; double AccountNo;
public BankAccount(double AccountNo,double balance) { this.AccountNo = AccountNo; this.balance = balance; }
void getBalance() { System.out.println("Balance"+balance); }
void deposit(double amount) { balance = balance + amount; System.out.println("Amount deposited: "+balance); }
void withdraw(double amount) { balance = balance - amount; System.out.println("Amount withdrawn: "+balance); } }
class CheckAccount extends BankAccount {
double MonthlyFee; double TransFee;
public CheckAccount(double AccountNo, double balance){ super(AccountNo, balance); }
void chargeMonthlyFee(double MonthlyFee) { balance = balance - MonthlyFee; System.out.println("Monthly fee charged now your Balance: "+balance); }
void changeTransFee(double TransFee) { balance = balance - TransFee; System.out.println("Transaction fee charged you Balance: "+balance); } }
class SavingAccount extends BankAccount { double rate; public SavingAccount(double AccountNo, double balance){ super(AccountNo,balance); }
void depositeInterest(double rate) { balance = (balance + (balance * rate)/100); System.out.println("Interest deposited"+balance); } void checkBalanceLimit() { if(balance < 1000){ System.out.println("balance limit reached"); } else{ System.out.println("balance limite not reached"); } } }
class Q1{ public static void main(String args[]){ BankAccount ba = new BankAccount(11223, 10000); ba.getBalance(); ba.deposit(500); ba.withdraw(500);
CheckAccount ca = new CheckAccount(11223, 10000); ca.chargeMonthlyFee(100); ca.changeTransFee(100);
SavingAccount sa = new SavingAccount(11223,10000); sa.depositeInterest(10); sa.checkBalanceLimit();
} }
|
2) Create an interface “Drawable” with method draw.Create 3 classes “Rectangle” , “Circle” , “Triangle” inheriting from the interface. Re-Define the method in subclasses to print an appropriate message.
interface Drawable { void draw();
}
class Rectangle implements Drawable { public void draw() { System.out.println("drawing rectangle"); }
}
class Circle implements Drawable { public void draw() { System.out.println("drawing circle"); } }
class Triangle implements Drawable { public void draw() { System.out.println("drawing triangle"); } }
public class Q2 { public static void main(String[] args) { Rectangle r = new Rectangle(); r.draw(); Circle c = new Circle(); c.draw(); Triangle t = new Triangle(); t.draw();
} }
|
3) Create an abstract method drive() in class “Vehicle”. Create subclasses “Car” and “Bus” to override the method. Print appropriate messages in methods of subclass.
import java.lang.*; import java.util.*;
abstract class Vehicle{ abstract void drive(); }
class Car extends Vehicle{ public void drive(){ System.out.println("Car is being driven"); } }
class Bus extends Vehicle{ public void drive(){ System.out.println("Bus is being driven"); } }
public class Q3{ public static void main(String[] args){ Car c = new Car(); c.drive();
Bus b = new Bus(); b.drive(); } }
|
4) Define an exception “NoMatchException” that is thrown when a string is not equal to “India”. WAP that uses this exception
import java.util.Scanner;
class NoMatchException extends Exception { NoMatchException() { System.out.println("String is not equal to 'India'"); } }
class Q4 { public static void main(String[] args) {
try {
Scanner s = new Scanner(System.in); String input = s.nextLine();
if (input == "India") { System.out.println("text matched"); } else { throw new NoMatchException(); }
} catch (NoMatchException e) { System.out.println(e); }
} }
|
5) Write a program to throw an exception if any input is beyond range 1-10. Demonstrate the use of try, catch
import java.util.Scanner;
class RangeException extends Exception { public RangeException(String str) { super(str); } }
class Q5 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter Number"); int input = sc.nextInt(); try { if (input > 1 && input < 10) { System.out.println("Input Accepted"); } else { throw new RangeException("Error! Number is not in range"); } } catch (RangeException str) { System.out.println(str); }
}
}
|
6) WAP to create two separate threads. Threads prints the number from 1- 10. Demonstrate both techniques of creating threads.
class Thread1 extends Thread { public void run() { int i; for (i = 1; i <= 10; i++) { System.out.println(i); } } } class Thread2 implements Runnable{ public void run(){ for(int i=1;i<=10;i++){ System.out.println(i); } } } public class Q6{ public static void main(String[] args) { Thread1 th1 = new Thread1(); Thread2 th2 = new Thread2();
Thread t1 = new Thread(th1); Thread t2 = new Thread(th2);
t1.run(); t2.run();
} } |
7) WAP that reads internal and external marks for a student. The condition is -internal marks should always be less than 40 and external marks should be less than 60. Raise a user defined exception is condition is violated in input. Else calculate total marks and display.
import java.util.*;
class InternalMarksException extends Exception { public InternalMarksException(String str1) { super(str1); } }
class ExternalMarksException extends Exception { public ExternalMarksException(String str2) { super(str2); } }
class Marks { public void check() throws InternalMarksException, ExternalMarksException{ Scanner sc = new Scanner(System.in);
System.out.println("Enter external"); int external = sc.nextInt(); System.out.println("Enter internal"); int internal = sc.nextInt();
if(internal < 0 || internal > 40){ throw new InternalMarksException("invalid internal marks"); } else if(external < 0 || external > 60){ throw new ExternalMarksException("invalid external marks"); } else{ int total = internal + external; System.out.println("Total: "+total); } } }
class Q7 { public static void main(String args[]) throws InternalMarksException, ExternalMarksException { Marks m = new Marks(); m.check(); } }
|
8) Write a program to create two threads, one thread will print odd numbers and second thread will print even numbers between 1 to 20 numbers. Both the threads should print the result alternately. Also display the thread id
import java.lang.*; import java.util.*;
class Q8{ int i = 1; static int n;
public void oddNumber(){ synchronized(this){ while(i < n){ while(i % 2 == 0){ try{ wait(); } catch(InterruptedException e){ e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+": "+i); i++; notify(); } } } public void evenNumber(){ synchronized(this){ while(i < n){ while(i % 2 == 1){ try{ wait(); } catch(InterruptedException e){ e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+": "+ i); i++; notify(); } } }
public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("enter a number:"); n = sc.nextInt(); Q8 t = new Q8(); Thread t1 = new Thread(new Runnable(){ public void run(){ t.evenNumber(); } });
Thread t2 = new Thread(new Runnable(){ public void run(){ t.oddNumber(); } });
t1.start(); t2.start(); } }
|

import java.lang.*; import java.util.*; import java.io.*;
interface Loader{ public void loadOS(); }
class Device{ String vendorName; int ramSize; double OSVersion;
public Device(String vendorName, int ramSize, double OSVersion){ this.vendorName = vendorName; this.ramSize = ramSize; this.OSVersion = OSVersion; }
public void getData(){ System.out.println("Vendor Name:" + vendorName); System.out.println("RAM Size:" + ramSize); System.out.println("OS Version:" + OSVersion); } }
class Mobile extends Device implements Loader{ public Mobile(String vendorName, int ramSize, double OSVersion) { super(vendorName, ramSize, OSVersion); }
public void loadOS(){ System.out.println("Loading the OS for mobile: " + vendorName); } }
class Q9{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Enter Vendor Name:"); String vendorName = sc.nextLine(); System.out.println("Enter RAM Size:"); int ramSize = sc.nextInt(); System.out.println("Enter OS Version:"); double OSVersion = sc.nextDouble();
Mobile m = new Mobile(vendorName, ramSize, OSVersion);
m.getData(); m.loadOS(); } } |
10) Create an abstract class 'Bank' with an abstract method 'getBalance'. $100, $150 and $200 are deposited in banks A, B and C respectively. 'BankA', 'BankB' and 'BankC' are subclasses of class 'Bank', each having a method named 'getBalance'. Call this method by creating an object of each of the three classes.
import java.lang.*; import java.util.*;
abstract class Bank{ abstract void getBalance(double amount); }
class BankA extends Bank{ double accountno; double balance;
public BankA(double accountno, double balance){ this.accountno = accountno; this.balance = balance; } public void getBalance(double amount){ balance = balance + amount; System.out.println("Account No:" + accountno +" Balance:" + balance); } }
class BankB extends Bank{ double accountno; double balance;
public BankB(double accountno, double balance){ this.accountno = accountno; this.balance = balance; } public void getBalance(double amount){ balance = balance + amount; System.out.println("Account No:" + accountno +" Balance:" + balance); } }
class BankC extends Bank{ double accountno; double balance;
public BankC(double accountno, double balance){ this.accountno = accountno; this.balance = balance; } public void getBalance(double amount){ balance = balance + amount; System.out.println("Account No:" + accountno +" Balance:" + balance); } }
public class Q10{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Account no. for Bank A:"); int accA = sc.nextInt(); System.out.println("enter balance:"); int bA = sc.nextInt(); System.out.println("enter amount to be deposited:"); double dA = sc.nextDouble();
System.out.println("Account no. for Bank B:"); int accB = sc.nextInt(); System.out.println("enter balance:"); int bB = sc.nextInt(); System.out.println("enter amount to be deposited:"); double dB = sc.nextDouble();
System.out.println("Account no. for Bank C:"); int accC = sc.nextInt(); System.out.println("enter balance:"); int bC = sc.nextInt(); System.out.println("enter amount to be deposited:"); double dC = sc.nextDouble();
BankA a = new BankA(accA,bA); a.getBalance(dA);
BankB b = new BankB(accB, bB); b.getBalance(dB);
BankC c = new BankC(accC, bC); c.getBalance(dC); } }
|
11) It also has a method named 'printSalary' which prints the salary of the members. Two classes 'Employee' and 'Manager' inherits the 'Member' class. The 'Employee' and 'Manager' classes have data members 'specialization' and 'department' respectively. Now, assign name, age, phone number,address and salary to an employee and a manager by making an object of both of these classes and print the same.
import java.lang.*; import java.util.*;
class Member{ String name; int age; String phoneNo; String address; Double salary;
public Member(String name, int age, String phoneNo, String address, Double salary){ this.name = name; this.age = age; this.phoneNo = phoneNo; this.address = address; this.salary = salary; }
public void printSalary(){ System.out.println("NAME: " + name + "\tSALARY:" + salary); } }
class Employee extends Member{ String specialization; public Employee(String name, int age, String phoneNo, String address, Double salary, String specialization){ super(name, age, phoneNo, address, salary); this.specialization = specialization; } }
class Manager extends Member{ String department; public Manager(String name, int age, String phoneNo, String address, Double salary, String department){ super(name, age, phoneNo, address, salary); this.department = department; } }
public class Q11{ public static void main(String[] args){ Employee e = new Employee("June", 27, "9876543210","xyz place", 10000.0, "Cloud"); e.printSalary();
Manager m = new Manager("Tom", 52, "9998887776", "abc place", 500000.0, "IT"); m.printSalary(); } }
|
12) WAP to generate 3 different types of exceptions in your program and handle it using try-catch-finally technique
import java.lang.*; import java.util.*;
class NegativeNumberException extends Exception{ public NegativeNumberException(String str1){ super(str1); } }
class BigNumberException extends Exception{ public BigNumberException(String str2){ super(str2); } }
class NotANumberException extends Exception{ public NotANumberException(String str3){ super(str3); } }
class Q12{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Enter a number in range:"); String x = sc.nextLine(); try{ double n = Double.parseDouble(x); if(n < 0){ throw new NegativeNumberException("Error Negative number entered"); } else if(n > 1000){ throw new BigNumberException("Error Number not in Range"); } else{ System.out.println("You entered a valid number: " + x); } } catch(NumberFormatException e){ try{ throw new NotANumberException("Input is not a valid number."); } catch (NotANumberException str3){ System.out.println("Caught NotANumberException: " + str3.getMessage()); } } catch(NegativeNumberException str1){ System.out.println("Caught NotANumberException: " + str1.getMessage()); } catch(BigNumberException str2){ System.out.println("Caught NotANumberException: " + str2.getMessage()); } finally{ System.out.println("All errors handled"); } } }
|
13) Description: Write a program to display a different quote each day of the year as the Thought of the day. The program should pick a random quote from an array of Quotes you provide and display it with the current date.
import java.lang.*; import java.util.*; import java.text.*;
public class Q13 { public static void main(String[] args) { String quotes[] = { "Life is what happens when you're busy making other plans. - John Lennon", "The only limit to our realization of tomorrow will be our doubts of today. - Franklin D. Roosevelt", "The way to get started is to quit talking and begin doing. - Walt Disney", "Success is not final, failure is not fatal: It is the courage to continue that counts. - Winston Churchill", "The only thing necessary for the triumph of evil is for good men to do nothing. - Edmund Burke" };
Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); String currentDate = df.format(c.getTime());
Random r = new Random(); int quoteIndex = r.nextInt(quotes.length); String selectedQuote = quotes[quoteIndex];
System.out.println("Date: " + currentDate); System.out.println("Thought of the Day: " + selectedQuote); } }
|
14) Description: WAP to read term number. Write a function in the program to generate and print the fibonacci term.
import java.lang.*; import java.util.*;
class Fibo{ public void fibo(int x){ int n1 = 0; int n2 = 1; int n3 = 1; int i;
for(i=0; i < x; i++){ System.out.println(""+n1); n1 = n2; n2 = n3; n3 = n1 + n2; } } }
public class Q14{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Enter number of terms:"); int x = sc.nextInt();
Fibo f1 = new Fibo(); f1.fibo(x); } }
|
15) Based on String - WAP to count number of alphabets, numbers, spaces and special symbols in given input.
import java.lang.*; import java.util.*; import java.io.*;
class Q15{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter a String:"); String str = sc.nextLine(); int upper = 0; int lower = 0; int number = 0; int special = 0;
for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= 'A' && c <= 'Z'){ upper++; } else if (c >= 'a' && c <= 'z') { lower++; } else if (c >= '0' && c <= '9') { number++; } else { special++; } } System.out.println("Lower case letters : " + lower); System.out.println("Upper case letters : " + upper); System.out.println("Number : " + number); System.out.println("Special characters : " + special); } }
|
16) WAP to demonstrate method overloading by creating area () to calculate area of circle, rectangle and triangle.
import java.lang.*; import java.util.*;
class Shape{ static final double PI = Math.PI; void Area(double a) { double A = PI * a * a; System.out.println("Area of the Circle: " + A); }
void Area(int a, int b) { double A = a * b; System.out.println("Area of the Rectangle: " + A); }
void Area(double c, double d) { double A = 0.5 * c * d; System.out.println("Area of the Triangle: " + A); } }
class Q16{ public static void main(String[] args){ Shape obj = new Shape(); obj.Area(2.5); obj.Area(4,5); obj.Area(2.5, 8.0); } }
|
17) Write a menu driven java program which will read a number and implement the following methods.
a. Palindrome
b. Fibonacci
import java.lang.*; import java.util.*;
class Palindrome{ public void palindrome(int x){ String str = Integer.toString(x); int n = str.length(); for(int i = 0; i < (n/2); ++i){ if(str.charAt(i) != str.charAt(n-i-1)){ System.out.println("Number is not a Palindrome"); } else{ System.out.println("Number is a Palindrome"); } } } }
class Fibonacci{ public void fibonacci(int x){ int n1 = 0; int n2 = 1; int n3 = 1; int i;
for(i=0; i < x; i++){ System.out.println(""+n1); n1 = n2; n2 = n3; n3 = n1 + n2; } } }
public class Q17{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); Palindrome p = new Palindrome(); Fibonacci f = new Fibonacci();
System.out.println("Choose an opperation:"); System.out.println("1. Check if number is a Palindrome"); System.out.println("2. Find Fibonacci series of the term");
int choice = sc.nextInt();
switch(choice){ case 1: System.out.println("Enter a number to check for palindrome:"); int a = sc.nextInt(); p.palindrome(a); break;
case 2: System.out.println("Enter the number of terms:"); int b= sc.nextInt(); f.fibonacci(b); break;
default: System.out.println("Invalid choice"); break; } } }
|
18) Write a program to input 2 strings using command line.
the use of following StringBuffer methods.
a. append() , b. insert() , c. replace() , d. delete() , e. reverse() , f. length()
public class StringBufferExample { public static void main(String[] args) { if (args.length < 2) { System.out.println("Please provide two strings as command line arguments."); return; }
String str1 = args[0]; String str2 = args[1];
StringBuffer stringBuffer = new StringBuffer(str1);
// Append stringBuffer.append(str2); System.out.println("After appending: " + stringBuffer);
// Insert stringBuffer.insert(2, "INSERTED"); System.out.println("After inserting: " + stringBuffer);
// Replace stringBuffer.replace(2, 9, "REPLACED"); System.out.println("After replacing: " + stringBuffer);
// Delete stringBuffer.delete(2, 9); System.out.println("After deleting: " + stringBuffer);
// Reverse stringBuffer.reverse(); System.out.println("After reversing: " + stringBuffer);
// Length int length = stringBuffer.length(); System.out.println("Length of the string: " + length); } }
|
19) Write a class “UtoL” with method to convert string from upper case to lower
case. Write another class “Array” with method to check if array is symmetric. Include both the classes in a package named “Utility” . Demonstrate how to use these classes in another package.
UtoL.java
package Utility;
public class UtoL { public String convertToLower(String input) { return input.toLowerCase(); } }
|
Array.java
package Utility;
public class Array { public boolean isSymmetric(int[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) { if (arr[i] != arr[n - 1 - i]) { return false; } } return true; } }
|
Main.java
package Demo;
import Utility.UtoL; import Utility.Array;
public class Main { public static void main(String[] args) { UtoL utoL = new UtoL(); String input = "HELLO"; System.out.println("Converted to lower case: " + utoL.convertToLower(input));
Array array = new Array(); int[] symmetricArray = {1, 2, 3, 3, 2, 1}; int[] nonSymmetricArray = {1, 2, 3, 4, 5}; System.out.println("Is symmetric? " + array.isSymmetric(symmetricArray)); // true System.out.println("Is symmetric? " + array.isSymmetric(nonSymmetricArray)); // false } }
|
20) Write a class “Point” with members x and y.
Write a default and parametrized constructor to set x n y.
Write display function to display x and y
Write a class “Line” with members are 2 point objects.
Write a method to find length of line and display it.
Write a class “Triangle” with members as 3 Line objects.
Write a method to find perimeter of triangle and display it.
import java.lang.*; import java.util.*;
class Point{ private double x; private double y;
public Point(){ x = 0; y = 0; }
public Point(double x, double y){ this. x = x; this.y = y; }
public void display(){ System.out.println("("+x+","+y+")"); }
public double getX() { return x; }
public double getY() { return y; } }
class Line{ private Point p1; private Point p2;
public Line(Point p1, Point p2){ this.p1 = p1; this.p2 = p2; }
public double length(){ double dx = p2.getX() - p1.getX(); double dy = p2.getY() - p1.getY(); double l = Math.sqrt(dx*dx + dy*dy); return l; }
public void displayLength(){ System.out.println("Length of the line is: "+ length()); } }
class Triangle{ private Line l1; private Line l2; private Line l3;
public Triangle(Line l1, Line l2, Line l3){ this.l1 = l1; this.l2 = l2; this.l3 = l3; }
public double getPerimeter(){ double p = l1.length() + l2.length() + l3.length(); return p; }
public void displayPerimeter(){ System.out.println("Perimeter of the triangle is: " + getPerimeter()); } }
public class Q20{ public static void main(String[] args){ Point a = new Point(12,4); Point b = new Point(8,0); Point c = new Point(12,0);
Line ab = new Line(a,b); Line bc = new Line(b,c); Line ca = new Line(c,a);
Triangle t = new Triangle(ab, bc, ca);
a.display(); b.display(); c.display();
ab.displayLength(); bc.displayLength(); ca.displayLength();
t.displayPerimeter(); } }
|
21) A publishing company that markets both book and audiocassette versions of its works. Create a class publication that stores the title (a string) and price (type float) of a publication. From this class derive two classes: book, which adds a page count (type int), and tape, which adds a playing time in minutes (type float). Each of these three classes should have a getdata() function to get its data from the user at the keyboard, and a putdata() function to display its data. Write a main() program to test the book and tape classes by creating instances of them, asking the user to fill in data with getdata(), and then displaying the data with putdata().
import java.util.Scanner;
class Publication { String title; float price;
void getData() { Scanner sc = new Scanner(System.in); System.out.print("Enter title: "); title = sc.nextLine(); System.out.print("Enter price: "); price = sc.nextFloat(); }
void putData() { System.out.println("Title: " + title); System.out.println("Price: $" + price); } }
class Book extends Publication { int pageCount;
@Override void getData() { super.getData(); Scanner sc = new Scanner(System.in); System.out.print("Enter page count: "); pageCount = sc.nextInt(); }
@Override void putData() { super.putData(); System.out.println("Page Count: " + pageCount); } }
class Tape extends Publication { float playingTime;
@Override void getData() { super.getData(); Scanner sc = new Scanner(System.in); System.out.print("Enter playing time in minutes: "); playingTime = sc.nextFloat(); }
@Override void putData() { super.putData(); System.out.println("Playing Time: " + playingTime + " minutes"); } }
public class Main { public static void main(String[] args) { System.out.println("Enter details for Book:"); Book book = new Book(); book.getData(); System.out.println("\nEnter details for Tape:"); Tape tape = new Tape(); tape.getData();
System.out.println("\nBook Details:"); book.putData();
System.out.println("\nTape Details:"); tape.putData(); } }
|
22) Simulate the simultaneous transactions on ‘withdraw’ and ‘deposit’ on bank account. Demonstrate using multithreading.
class BankAccount { private int balance = 1000;
public synchronized void deposit(int amount) { System.out.println("Depositing: " + amount); balance += amount; }
public synchronized void withdraw(int amount) { if (balance >= amount) { System.out.println("Withdrawing: " + amount); balance -= amount; } else { System.out.println("Insufficient balance for withdrawal."); } }
public void displayBalance() { System.out.println("Current balance: " + balance); } }
class Transaction implements Runnable { private final BankAccount account; private final boolean isDeposit; private final int amount;
public Transaction(BankAccount account, boolean isDeposit, int amount) { this.account = account; this.isDeposit = isDeposit; this.amount = amount; }
public void run() { if (isDeposit) { account.deposit(amount); } else { account.withdraw(amount); } } }
public class Main { public static void main(String[] args) { BankAccount account = new BankAccount(); System.out.println("Initial Balance:"); account.displayBalance();
Thread depositThread = new Thread(new Transaction(account, true, 500)); Thread withdrawThread = new Thread(new Transaction(account, false, 300));
depositThread.start(); withdrawThread.start();
try { depositThread.join(); withdrawThread.join(); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println("\nFinal Balance:"); account.displayBalance(); } } |
23) Create GUI containing Name, email ID, Phone Number. For invalid password and user id print message on Dialogue box.
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
public class GUIExample { public static void main(String[] args) { JFrame frame = new JFrame("User Information"); JPanel panel = new JPanel(); JLabel nameLabel = new JLabel("Name:"); JTextField nameField = new JTextField(20); JLabel emailLabel = new JLabel("Email ID:"); JTextField emailField = new JTextField(20); JLabel phoneLabel = new JLabel("Phone Number:"); JTextField phoneField = new JTextField(20); JButton submitButton = new JButton("Submit");
submitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String name = nameField.getText(); String email = emailField.getText(); String phone = phoneField.getText();
if (name.isEmpty() || email.isEmpty() || phone.isEmpty()) { JOptionPane.showMessageDialog(frame, "Please fill in all fields."); } else { if (!email.contains("@") || !email.contains(".")) { JOptionPane.showMessageDialog(frame, "Invalid Email ID."); } else if (!phone.matches("\\d{10}")) { JOptionPane.showMessageDialog(frame, "Invalid Phone Number. Please enter 10 digits."); } else { JOptionPane.showMessageDialog(frame, "Name: " + name + "\nEmail ID: " + email + "\nPhone Number: " + phone); } } } });
panel.add(nameLabel); panel.add(nameField); panel.add(emailLabel); panel.add(emailField); panel.add(phoneLabel); panel.add(phoneField); panel.add(submitButton); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); frame.add(panel); frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
|
24) Write a Java program to create and start multiple threads that increment a shared counter variable concurrently.
public class SharedCounterExample { public static void main(String[] args) { SharedCounter sharedCounter = new SharedCounter();
// Creating and starting multiple threads for (int i = 0; i < 5; i++) { Thread thread = new Thread(new CounterThread(sharedCounter)); thread.start(); } } }
class SharedCounter { private int count = 0;
public synchronized void increment() { count++; System.out.println("Count is: " + count + " - Thread ID: " + Thread.currentThread().getId()); } }
class CounterThread implements Runnable { private final SharedCounter sharedCounter;
public CounterThread(SharedCounter sharedCounter) { this.sharedCounter = sharedCounter; }
@Override public void run() { for (int i = 0; i < 5; i++) { sharedCounter.increment(); try { Thread.sleep(100); // Adding a small delay to simulate concurrent access } catch (InterruptedException e) { e.printStackTrace(); } } } } |
25) Write a Java program to create a producer-consumer scenario using the wait() and notify() methods for thread synchronization.
import java.util.LinkedList;
public class ProducerConsumerExample { public static void main(String[] args) { final PC pc = new PC();
// Create a producer thread Thread producerThread = new Thread(() -> { try { pc.produce(); } catch (InterruptedException e) { e.printStackTrace(); } });
// Create a consumer thread Thread consumerThread = new Thread(() -> { try { pc.consume(); } catch (InterruptedException e) { e.printStackTrace(); } });
// Start both threads producerThread.start(); consumerThread.start();
// Wait for both threads to finish try { producerThread.join(); consumerThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } }
static class PC { LinkedList<Integer> list = new LinkedList<>(); int capacity = 2;
public void produce() throws InterruptedException { int value = 0; while (true) { synchronized (this) { while (list.size() == capacity) { wait(); } System.out.println("Producer produced-" + value); list.add(value++); notify(); Thread.sleep(1000); } } }
public void consume() throws InterruptedException { while (true) { synchronized (this) { while (list.size() == 0) { wait(); } int val = list.removeFirst(); System.out.println("Consumer consumed-" + val); notify(); Thread.sleep(1000); } } } } } |
26) Write a Java program to create an abstract class GeometricShape with abstract methods area() and perimeter(). Create subclasses Triangle and Square that extend the GeometricShape class and implement the respective methods to calculate the area and perimeter of each shape.
abstract class GeometricShape { abstract double area(); abstract double perimeter(); }
class Triangle extends GeometricShape { double base; double height; double side1; double side2; double side3;
Triangle(double base, double height, double side1, double side2, double side3) { this.base = base; this.height = height; this.side1 = side1; this.side2 = side2; this.side3 = side3; }
@Override double area() { return 0.5 * base * height; }
@Override double perimeter() { return side1 + side2 + side3; } }
class Square extends GeometricShape { double side;
Square(double side) { this.side = side; }
@Override double area() { return side * side; }
@Override double perimeter() { return 4 * side; } }
public class Main { public static void main(String[] args) { Triangle triangle = new Triangle(6, 4, 5, 4, 3); System.out.println("Area of the Triangle: " + triangle.area()); System.out.println("Perimeter of the Triangle: " + triangle.perimeter());
Square square = new Square(5); System.out.println("Area of the Square: " + square.area()); System.out.println("Perimeter of the Square: " + square.perimeter()); } } |
27) Write a Java program to create an abstract class BankAccount with abstract methods deposit() and withdraw(). Create subclasses:SavingsAccount and CurrentAccount that extend the BankAccount classand implement the respective methods to handle deposits and
withdrawals for each account type.
abstract class BankAccount { abstract void deposit(double amount); abstract void withdraw(double amount); }
class SavingsAccount extends BankAccount { double balance = 0;
@Override void deposit(double amount) { balance += amount; System.out.println("Depositing to savings account: " + amount); System.out.println("Current balance: " + balance); }
@Override void withdraw(double amount) { if (balance >= amount) { balance -= amount; System.out.println("Withdrawing from savings account: " + amount); System.out.println("Current balance: " + balance); } else { System.out.println("Insufficient balance for withdrawal."); } } }
class CurrentAccount extends BankAccount { double balance = 0; double overdraftLimit = 1000;
@Override void deposit(double amount) { balance += amount; System.out.println("Depositing to current account: " + amount); System.out.println("Current balance: " + balance); }
@Override void withdraw(double amount) { if (balance - amount >= overdraftLimit) { balance -= amount; System.out.println("Withdrawing from current account: " + amount); System.out.println("Current balance: " + balance); } else { System.out.println("Withdrawal amount exceeds overdraft limit."); } } }
public class Main { public static void main(String[] args) { SavingsAccount savingsAccount = new SavingsAccount(); savingsAccount.deposit(1000); savingsAccount.withdraw(500);
CurrentAccount currentAccount = new CurrentAccount(); currentAccount.deposit(2000); currentAccount.withdraw(3000); } } |
28) Write a Java program that reads a floating-point number. If the number is zero it prints “zero” otherwise, print “positive” or “negative”. Add “small” if the absolute value of the number is less than 1, or “large” if it exceeds 1,000,000.
Test Data
Input a number: -2534
Expected Output :
Negative
import java.util.Scanner;
public class NumberChecker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Input a number: "); float number = scanner.nextFloat();
if (number == 0) { System.out.println("Zero"); } else if (number > 0) { System.out.print("Positive "); } else { System.out.print("Negative "); }
if (Math.abs(number) < 1) { System.out.println("small"); } else if (Math.abs(number) > 1000000) { System.out.println("large"); } } }
|
29) Write a program that accepts three numbers from the user and prints
“increasing” if the numbers are in increasing order, “decreasing” if the
numbers are in decreasing order, and “Neither increasing or decreasing
order” otherwise.
Test Data
Input first number: 1524
Input second number: 2345
Input third number: 3321
Expected Output :
Increasing order
import java.util.Scanner;
public class NumberOrderChecker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Input first number: "); int firstNumber = scanner.nextInt(); System.out.print("Input second number: "); int secondNumber = scanner.nextInt(); System.out.print("Input third number: "); int thirdNumber = scanner.nextInt();
if (firstNumber < secondNumber && secondNumber < thirdNumber) { System.out.println("Increasing order"); } else if (firstNumber > secondNumber && secondNumber > thirdNumber) { System.out.println("Decreasing order"); } else { System.out.println("Neither increasing nor decreasing order"); } } }
|
30) Write a Java method that accepts three integers and checks whether they
are consecutive or not. Returns true or false.
Expected Output:
Input the first number: 15
Input the second number: 16
Input the third number: 17
Check whether the three said numbers are consecutive or not!true
import java.util.Scanner;
public class ConsecutiveChecker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Input the first number: "); int num1 = scanner.nextInt(); System.out.print("Input the second number: "); int num2 = scanner.nextInt(); System.out.print("Input the third number: "); int num3 = scanner.nextInt();
System.out.println("Check whether the three said numbers are consecutive or not! " + areConsecutive(num1, num2, num3)); }
public static boolean areConsecutive(int num1, int num2, int num3) { if (num2 == num1 + 1 && num3 == num2 + 1) { return true; } else if (num1 == num2 + 1 && num2 == num3 + 1) { return true; } else if (num1 == num2 - 1 && num2 == num3 - 1) { return true; } else if (num2 == num1 - 1 && num3 == num2 - 1) { return true; } else { return false; } } }
|
Comments
Post a Comment