Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Manual 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

Java Manual

Q1) Create Account with 1000 Rs Minimum Balance, Deposit Amount, Withdraw Amount and Also
Throws LessBalanceException. It has a Class Called LessBalanceException Which returns the
Statement that Says WithDraw Amount(_Rs) is Not
Valid. It has a Class Which Creates 2 Accounts, Both Account Deposite Money and One Account Tries
to WithDraw more Money Which Generates a LessBalanceException Take Appropriate Action for the
Same.
*/
// Custom exception class for insufficient balance
class LessBalanceException extends Exception {
public LessBalanceException(String message) {
super(message);
}
}

// Bank Account class


class Account {
private String accountHolderName;
private double balance;
private static final double MINIMUM_BALANCE = 1000.0;

// Constructor to create an account with an initial deposit


public Account(String accountHolderName, double initialDeposit) {
this.accountHolderName = accountHolderName;
if (initialDeposit >= MINIMUM_BALANCE) {
this.balance = initialDeposit;
} else {
this.balance = MINIMUM_BALANCE; // Ensuring minimum balance is maintained
System.out.println("Initial deposit less than minimum balance. Setting balance to Rs. " +
MINIMUM_BALANCE);
}
}

// Method to deposit money


public void deposit(double amount) {
balance += amount;
System.out.println("Rs. " + amount + " deposited. New balance: Rs. " + balance);
}

// Method to withdraw money


public void withdraw(double amount) throws LessBalanceException {
if (balance - amount < MINIMUM_BALANCE) {
throw new LessBalanceException("Withdraw amount Rs. " + amount + " is not valid. Minimum
balance of Rs. " + MINIMUM_BALANCE + " must be maintained.");
} else {
balance -= amount;
System.out.println("Rs. " + amount + " withdrawn. New balance: Rs. " + balance);
}
}
// Method to display the balance
public void displayBalance() {
System.out.println(accountHolderName + "'s Account Balance: Rs. " + balance);
}
}

// Main class to demonstrate account operations


public class BankApplicationMain {
public static void main(String[] args) {
// Creating two accounts
Account account1 = new Account("Alice", 5000); // Valid initial deposit
Account account2 = new Account("Bob", 1000); // Initial deposit equals minimum balance

// Depositing money into both accounts


account1.deposit(2000); // Depositing Rs. 2000 into Alice's account
account2.deposit(500); // Depositing Rs. 500 into Bob's account

// Displaying balances after deposit


account1.displayBalance();
account2.displayBalance();

// Attempt to withdraw valid and invalid amounts


try {
// Withdraw Rs. 3000 from Alice's account (valid)
account1.withdraw(3000);
} catch (LessBalanceException e) {
System.out.println(e.getMessage());
}

try {
// Withdraw Rs. 800 from Bob's account (invalid as it will breach the minimum balance)
account2.withdraw(800);
} catch (LessBalanceException e) {
System.out.println(e.getMessage());
}

// Display balances after withdrawals


account1.displayBalance();
account2.displayBalance();
}
}
Output:-
Q2)Write a Java program to illustrate Constructor Chaining.

class Employee {

private String name;

private int id;

private double salary;

// Constructor with no parameters

public Employee() {

this("Unknown", 0, 0.0); // Calling the parameterized constructor

System.out.println("Default constructor called");

// Constructor with two parameters

public Employee(String name, int id) {

this(name, id, 30000.0); // Calling the constructor with three parameters

System.out.println("Constructor with name and ID called");

// Constructor with three parameters

public Employee(String name, int id, double salary) {

this.name = name;

this.id = id;

this.salary = salary;

System.out.println("Constructor with name, ID, and salary called");

// Method to display employee information

public void displayInfo() {


System.out.println("Employee Name: " + name);

System.out.println("Employee ID: " + id);

System.out.println("Employee Salary: " + salary);

public class ConstructorChainingExample {

public static void main(String[] args) {

System.out.println("Creating Employee using default constructor:");

Employee emp1 = new Employee(); // Calls default constructor

System.out.println("\nCreating Employee using name and ID constructor:");

Employee emp2 = new Employee("Alice", 101); // Calls constructor with name and ID

System.out.println("\nCreating Employee using all parameters constructor:");

Employee emp3 = new Employee("Bob", 102, 50000.0); // Calls constructor with all parameters

// Display employee information

System.out.println("\nEmployee Information:");

emp1.displayInfo();

emp2.displayInfo();

emp3.displayInfo();

Output:-
Q3)You have been given the list of the names of the files in a directory. You have to select Java files

from them. A file is a Java file if it’s name ends with “.java”. For e.g. File- “Names.java” is a Java file,

“FileNames.java.pdf” is not.

Input: test.java, ABC.doc, Demo.pdf, add.java, factorial.java, sum.txt

Output: tset.java, add.java, factorial.java

*/

import java.util.ArrayList;

import java.util.List;

public class JavaFileSelector {

// Method to filter out Java files from a list of filenames

public static List<String> getJavaFiles(String[] files) {

List<String> javaFiles = new ArrayList<>();

// Loop through the list of files

for (String file : files) {

// Check if the file name ends with ".java"

if (file.endsWith(".java")) {

javaFiles.add(file);

return javaFiles;

public static void main(String[] args) {

// Input list of filenames

String[] files = {"test.java", "ABC.doc", "Demo.pdf", "add.java", "factorial.java", "sum.txt"};


// Call the method to get only Java files

List<String> javaFiles = getJavaFiles(files);

// Print the Java files

System.out.println("Java Files:");

for (String javaFile : javaFiles) {

System.out.println(javaFile);

Output:-
Q4Write java program where user will enter loginid and password as input. The password should be 8

digit containing one digit and one special symbol. If user enter valid password satisfying above

criteria then show “Login Successful Message”. If user enter invalid Password then create

InvalidPasswordException stating Please enter valid password of length 8 containing one digit and

one Special Symbol.

*/

import java.util.Scanner;

import java.util.regex.Pattern;

// Custom exception for invalid passwords

class InvalidPasswordException extends Exception {

public InvalidPasswordException(String message) {

super(message);

public class LoginSystem {

// Method to validate the password

public static void validatePassword(String password) throws InvalidPasswordException {

// Check if the password length is 8

if (password.length() != 8) {

throw new InvalidPasswordException("Password must be 8 characters long.");

// Check if the password contains at least one digit

if (!Pattern.compile("[0-9]").matcher(password).find()) {

throw new InvalidPasswordException("Password must contain at least one digit.");


}

// Check if the password contains at least one special character

if (!Pattern.compile("[!@#$%^&*(),.?\":{}|<>]").matcher(password).find()) {

throw new InvalidPasswordException("Password must contain at least one special symbol.");

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Get login ID and password from the user

System.out.print("Enter your login ID: ");

String loginId = scanner.nextLine();

System.out.print("Enter your password: ");

String password = scanner.nextLine();

try {

// Validate the password

validatePassword(password);

System.out.println("Login Successful.");

} catch (InvalidPasswordException e) {

// Handle invalid password exception

System.out.println("Invalid Password: " + e.getMessage());

System.out.println("Please enter a valid password of length 8 containing at least one digit and

one special symbol.");

Output:-
Q5)Write a menu driven Java program which will read a number and should implement the following

methods

1. factorial()

2. testArmstrong()

3. testPalindrome()

4. testPrime()

5. fibonacciSeries()

*/

import java.util.Scanner;

public class NumberOperations {

// Method to calculate factorial of a number

public static long factorial(int num) {

long fact = 1;

for (int i = 1; i <= num; i++) {

fact *= i;

return fact;

// Method to test if a number is an Armstrong number

public static boolean testArmstrong(int num) {

int originalNum = num;

int sum = 0;

int digits = String.valueOf(num).length();

while (num != 0) {
int digit = num % 10;

sum += Math.pow(digit, digits);

num /= 10;

return sum == originalNum;

// Method to test if a number is a palindrome

public static boolean testPalindrome(int num) {

int originalNum = num;

int reversedNum = 0;

while (num != 0) {

int digit = num % 10;

reversedNum = reversedNum * 10 + digit;

num /= 10;

return originalNum == reversedNum;

// Method to test if a number is a prime number

public static boolean testPrime(int num) {

if (num <= 1) return false;

for (int i = 2; i <= Math.sqrt(num); i++) {

if (num % i == 0) return false;

return true;

}
// Method to print the Fibonacci series up to a given number

public static void fibonacciSeries(int num) {

int a = 0, b = 1;

System.out.print("Fibonacci Series: ");

for (int i = 1; i <= num; i++) {

System.out.print(a + " ");

int next = a + b;

a = b;

b = next;

System.out.println();

// Main method to drive the menu and implement user options

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int choice;

do {

System.out.println("\nNumber Operations Menu:");

System.out.println("1. Factorial");

System.out.println("2. Test Armstrong Number");

System.out.println("3. Test Palindrome Number");

System.out.println("4. Test Prime Number");

System.out.println("5. Fibonacci Series");

System.out.println("6. Exit");

System.out.print("Enter your choice: ");

choice = scanner.nextInt();
switch (choice) {

case 1:

System.out.print("Enter a number to find factorial: ");

int num1 = scanner.nextInt();

System.out.println("Factorial of " + num1 + " is: " + factorial(num1));

break;

case 2:

System.out.print("Enter a number to test Armstrong: ");

int num2 = scanner.nextInt();

if (testArmstrong(num2)) {

System.out.println(num2 + " is an Armstrong number.");

} else {

System.out.println(num2 + " is not an Armstrong number.");

break;

case 3:

System.out.print("Enter a number to test Palindrome: ");

int num3 = scanner.nextInt();

if (testPalindrome(num3)) {

System.out.println(num3 + " is a Palindrome number.");

} else {

System.out.println(num3 + " is not a Palindrome number.");

break;

case 4:

System.out.print("Enter a number to test Prime: ");


int num4 = scanner.nextInt();

if (testPrime(num4)) {

System.out.println(num4 + " is a Prime number.");

} else {

System.out.println(num4 + " is not a Prime number.");

break;

case 5:

System.out.print("Enter the number of terms for Fibonacci series: ");

int num5 = scanner.nextInt();

fibonacciSeries(num5);

break;

case 6:

System.out.println("Exiting the program. Thank you!");

break;

default:

System.out.println("Invalid choice. Please try again.");

} while (choice != 6);

scanner.close();

Output:-
Q6)Write menu driven program to implement recursive Functions for following tasks.

a) To find GCD and LCM

b) To print n Fibonacci numbers

c) To find reverse of number

d) To solve 1 +2+3+4+........+(n- l )+n

*/

import java.util.Scanner;

public class RecursiveFunctionsMenu {

// Method to find GCD using recursion

public static int gcd(int a, int b) {

if (b == 0) {

return a;

return gcd(b, a % b);

// Method to find LCM using GCD

public static int lcm(int a, int b) {

return (a * b) / gcd(a, b);

// Method to print Fibonacci numbers using recursion

public static void printFibonacci(int n, int a, int b) {

if (n > 0) {

System.out.print(a + " ");

printFibonacci(n - 1, b, a + b);
}

// Method to find the reverse of a number using recursion

public static int reverse(int num) {

return reverseHelper(num, 0);

private static int reverseHelper(int num, int reversed) {

if (num == 0) {

return reversed;

return reverseHelper(num / 10, reversed * 10 + num % 10);

// Method to calculate the sum of first n natural numbers using recursion

public static int sumNatural(int n) {

if (n <= 0) {

return 0;

return n + sumNatural(n - 1);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int choice;

do {

System.out.println("\nMenu:");
System.out.println("1. Find GCD and LCM");

System.out.println("2. Print n Fibonacci numbers");

System.out.println("3. Find reverse of a number");

System.out.println("4. Calculate sum of first n natural numbers");

System.out.println("5. Exit");

System.out.print("Enter your choice: ");

choice = scanner.nextInt();

switch (choice) {

case 1:

System.out.print("Enter two numbers: ");

int num1 = scanner.nextInt();

int num2 = scanner.nextInt();

System.out.println("GCD: " + gcd(num1, num2));

System.out.println("LCM: " + lcm(num1, num2));

break;

case 2:

System.out.print("Enter the number of Fibonacci numbers to print: ");

int n = scanner.nextInt();

System.out.print("Fibonacci Series: ");

printFibonacci(n, 0, 1);

System.out.println();

break;

case 3:

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int reversedNumber = reverse(number);


System.out.println("Reversed Number: " + reversedNumber);

break;

case 4:

System.out.print("Enter a positive integer: ");

int sumNumber = scanner.nextInt();

int sum = sumNatural(sumNumber);

System.out.println("Sum of first " + sumNumber + " natural numbers: " + sum);

break;

case 5:

System.out.println("Exiting...");

break;

default:

System.out.println("Invalid choice! Please try again.");

} while (choice != 5);

// Close the scanner

scanner.close();

Output:-
Q7)Print Reverse Array list in java by writing our own function.

*/

import java.util.ArrayList;

import java.util.Scanner;

public class ReverseArrayList {

// Method to reverse an ArrayList

public static <T> ArrayList<T> reverseArrayList(ArrayList<T> list) {

ArrayList<T> reversedList = new ArrayList<>();

for (int i = list.size() - 1; i >= 0; i--) {

reversedList.add(list.get(i));

return reversedList;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

ArrayList<String> arrayList = new ArrayList<>();

System.out.print("Enter the number of elements you want to add to the ArrayList: ");

int n = scanner.nextInt();

scanner.nextLine(); // Consume the newline character

// Input elements into the ArrayList

for (int i = 0; i < n; i++) {

System.out.print("Enter element " + (i + 1) + ": ");

String element = scanner.nextLine();


arrayList.add(element);

// Reverse the ArrayList using the custom method

ArrayList<String> reversedList = reverseArrayList(arrayList);

// Display the original and reversed ArrayLists

System.out.println("\nOriginal ArrayList: " + arrayList);

System.out.println("Reversed ArrayList: " + reversedList);

// Close the scanner

scanner.close();

Output:-
Q8)

/*

Implement a java program to calculate gross salary & net salary taking the following data.

Input: empno, empname, basic Process:

DA=70% of basic

HRA=30% of basic

CCA=Rs240/-

PF=10% of basic

PT= Rs100/-

*/

import java.util.Scanner;

public class SalaryCalculator {

public static void main(String[] args) {

// Create Scanner object for input

Scanner scanner = new Scanner(System.in);

// Input employee details

System.out.print("Enter Employee Number: ");

int empNo = scanner.nextInt();

scanner.nextLine(); // Consume newline left-over

System.out.print("Enter Employee Name: ");

String empName = scanner.nextLine();

System.out.print("Enter Basic Salary: ");

double basic = scanner.nextDouble();


// Calculations

double DA = 0.70 * basic; // 70% of basic

double HRA = 0.30 * basic; // 30% of basic

double CCA = 240; // Constant value Rs 240/-

double PF = 0.10 * basic; // 10% of basic

double PT = 100; // Professional Tax Rs 100/-

// Calculate gross salary and net salary

double grossSalary = basic + DA + HRA + CCA;

double deductions = PF + PT;

double netSalary = grossSalary - deductions;

// Output the results

System.out.println("\nEmployee Number: " + empNo);

System.out.println("Employee Name: " + empName);

System.out.println("Basic Salary: " + basic);

System.out.println("Gross Salary: " + grossSalary);

System.out.println("Net Salary: " + netSalary);

Output:-
Q9)Write a Java Program to create a Student Profile form using AWT controls.

*/

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class StudentProfileForm extends Frame implements ActionListener {

// Components of the form

private TextField nameField, ageField;

private Choice genderChoice, courseChoice;

private Button submitButton;

// Constructor to set up the form

public StudentProfileForm() {

// Set the title of the frame

setTitle("Student Profile Form");

// Set the layout of the frame

setLayout(new GridLayout(5, 2, 10, 10)); // 5 rows, 2 columns

// Create and add labels and text fields for name and age

add(new Label("Name:"));

nameField = new TextField(20);

add(nameField);

add(new Label("Age:"));

ageField = new TextField(3);


add(ageField);

// Create and add choice for gender

add(new Label("Gender:"));

genderChoice = new Choice();

genderChoice.add("Select Gender");

genderChoice.add("Male");

genderChoice.add("Female");

genderChoice.add("Other");

add(genderChoice);

// Create and add choice for course

add(new Label("Course:"));

courseChoice = new Choice();

courseChoice.add("Select Course");

courseChoice.add("Computer Science");

courseChoice.add("Mathematics");

courseChoice.add("Physics");

courseChoice.add("Chemistry");

add(courseChoice);

// Create and add submit button

submitButton = new Button("Submit");

submitButton.addActionListener(this);

add(submitButton);

// Set the size and visibility of the frame

setSize(400, 300);

setVisible(true);
// Add a window listener to handle closing the window

addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosing(java.awt.event.WindowEvent windowEvent) {

System.exit(0);

});

// Method to handle button click events

@Override

public void actionPerformed(ActionEvent e) {

// Get the values from the form fields

String name = nameField.getText();

String age = ageField.getText();

String gender = genderChoice.getSelectedItem();

String course = courseChoice.getSelectedItem();

// Display the student profile information in a message dialog

String message = "Student Profile:\n" +

"Name: " + name + "\n" +

"Age: " + age + "\n" +

"Gender: " + gender + "\n" +

"Course: " + course;

// Show the message dialog with student profile

Dialog dialog = new Dialog(this, "Profile Submitted", true);

dialog.setLayout(new FlowLayout());

dialog.add(new Label(message));
Button okButton = new Button("OK");

okButton.addActionListener(e1 -> dialog.dispose());

dialog.add(okButton);

dialog.setSize(300, 200);

dialog.setVisible(true);

// Main method to run the application

public static void main(String[] args) {

new StudentProfileForm();

Output:-

You might also like