OOP & Design Question and Answer
(Suggest Find the question by search page and keep refreshing the page for updated content)
Q . A) Assume you are writing a Java program for a bank. The bank’s account numbers are generated sequentially, and the first account number is 1000. You want to keep track of the latest account number that was generated. Declare a static variable that will hold the latest account number, and write a method to generate the next account number based on the previous one. Make sure the latest account number is incremented by 1 each time a new account is generated.
Answer.
Java program that declares a static variable to keep track of the latest account number and generates the next account number based on the previous one:
public class Bank { private static int latestAccountNumber = 1000; public static int generateAccountNumber() { int accountNumber = latestAccountNumber; latestAccountNumber++; return accountNumber; } }
In this program, the static variable latestAccountNumber is initialized to 1000 as per the bank’s requirement. The generateAccountNumber() method returns the current latestAccountNumber and then increments it by 1 so that the next generated account number is unique. This way, each time the method is called, it will return a new account number that is sequentially generated.
To use this program, you can call the generateAccountNumber() method to get the next account number:
int accountNumber = Bank.generateAccountNumber(); System.out.println("Generated account number: " + accountNumber);
This will print the next account number that was generated by the program. You can then use this account number to create a new account for a customer, for example.
B ) You are working on a Java program that requires a constant value that is used in multiple classes. Declare a public static final vanable in a separate class to store the constant value, and access it from other classes
Answer.
Here how you can declare a public static final variable in a separate class and access it from other classes:
public class Constants { public static final int MAXIMUM_VALUE = 100; }
In this example, we declare a public class Constants
that contains a public static final variable MAXIMUM_VALUE
. The public
modifier makes the variable accessible from other classes, the static
modifier means that the variable belongs to the class rather than to any specific instance of the class, and the final
modifier means that the value of the variable cannot be changed once it is initialized.
Now, you can access this constant value from other classes by referring to the class name and the variable name:
public class MyClass { public void doSomething() { int value = Constants.MAXIMUM_VALUE; System.out.println("The maximum value is " + value); } }
In this example, we create a new class MyClass
that needs to use the constant MAXIMUM_VALUE
declared in the Constants
class. We access the constant using the class name Constants
followed by the variable name MAXIMUM_VALUE
. This will give us the value of the constant, which we can then use in our program.
Q a).Given an array of Pairs consisting of two fields of type string and integer. Sort the array in ascending Lexicographical order and if two strings are the same sort it based on their integer value. Use comparable interface in java coding
Answer.
import java.util.Arrays; public class Pair implements Comparable<Pair> { private String str; private int num; public Pair(String str, int num) { this.str = str; this.num = num; } public String getStr() { return str; } public int getNum() { return num; } @Override public int compareTo(Pair other) { int result = str.compareTo(other.getStr()); if (result == 0) { result = Integer.compare(num, other.getNum()); } return result; } public static void main(String[] args) { Pair[] pairs = { new Pair("foo", 3), new Pair("bar", 2), new Pair("baz", 2), new Pair("foo", 2) }; Arrays.sort(pairs); for (Pair pair : pairs) { System.out.println(pair.getStr() + " " + pair.getNum()); } } }
b). Write down a program in which demonstrate types of exception using different cases and Display Exception on console with description. (5 Marks) 09-2021wb1551
1.Arithmatic Exception
2.Null Pointer Exception
3.ArrayIndexOutOfBoundsException
4.StringIndexOutOfBoundsException
Answer.
Here is an example program that demonstrates different types of exceptions and displays the exception description on the console:
public class ExceptionDemo { public static void main(String[] args) { //Arithmetic Exception try { int result = 5/0; } catch (ArithmeticException e) { System.out.println("Arithmetic Exception: " + e.getMessage()); } //Null Pointer Exception try { String str = null; int length = str.length(); } catch (NullPointerException e) { System.out.println("Null Pointer Exception: " + e.getMessage()); } //ArrayIndexOutOfBoundsException try { int[] numbers = {1, 2, 3}; int element = numbers[3]; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException: " + e.getMessage()); } //StringIndexOutOfBoundsException try { String str = "Hello"; char ch = str.charAt(10); } catch (StringIndexOutOfBoundsException e) { System.out.println("StringIndexOutOfBoundsException: " + e.getMessage()); } } }
In the program, four different types of exceptions are demonstrated using try-catch blocks:
- ArithmeticException: This exception occurs when there is an arithmetic error, such as division by zero.
- NullPointerException: This exception occurs when trying to access an object or variable that has not been initialized.
- ArrayIndexOutOfBoundsException: This exception occurs when trying to access an index in an array that is outside the range of valid indexes.
- StringIndexOutOfBoundsException: This exception occurs when trying to access a character in a string that is outside the range of valid indexes.
In each catch block, the exception message is displayed on the console along with a description of the exception type.
Q . a) Create a class Student with name, id, gpa and institution with required constructors
Answer.
To create a Student
class with the required attributes and constructors in Java:
public class Student { private String name; private int id; private double gpa; private String institution; public Student(String name, int id, double gpa, String institution) { this.name = name; this.id = id; this.gpa = gpa; this.institution = institution; } public String getName() { return name; } public int getId() { return id; } public double getGpa() { return gpa; } public String getInstitution() { return institution; } }
In this example, we create a class Student
with private attributes name
, id
, gpa
, and institution
. We provide a constructor that takes these attributes as arguments and initializes them. We also provide getter methods for each attribute so that they can be accessed from other parts of the program.
To create a new Student
object, you can call the constructor and provide the required arguments:
Student student1 = new Student("John Doe", 12345, 3.5, "University of XYZ");
This will create a new Student
object with the given name, ID, GPA, and institution. You can then use the getter methods to access the attributes of the object, like this:
String name = student1.getName(); int id = student1.getId(); double gpa = student1.getGpa(); String institution = student1.getInstitution(); System.out.println("Student " + name + " (ID: " + id + ") has a GPA of " + gpa + " and attends " + institution + ".");
This will output a message with the details of the Student
object that was created.
b) Create a class Employee with name, id, salary and Organization with required constructors.
Answer.
To create a Employee
class with the required attributes and constructors in Java:
public class Employee { private String name; private int id; private double salary; private String organization; public Employee(String name, int id, double salary, String organization) { this.name = name; this.id = id; this.salary = salary; this.organization = organization; } public String getName() { return name; } public int getId() { return id; } public double getSalary() { return salary; } public String getOrganization() { return organization; } }
In this example, we create a class Employee
with private attributes name
, id
, salary
, and organization
. We provide a constructor that takes these attributes as arguments and initializes them. We also provide getter methods for each attribute so that they can be accessed from other parts of the program.
To create a new Employee
object, you can call the constructor and provide the required arguments:
Employee employee1 = new Employee("John Doe", 12345, 5000.0, "ABC Inc.");
This will create a new Employee
object with the given name, ID, salary, and organization. You can then use the getter methods to access the attributes of the object, like this:
String name = employee1.getName(); int id = employee1.getId(); double salary = employee1.getSalary(); String organization = employee1.getOrganization(); System.out.println(name + " (ID: " + id + ") earns a salary of " + salary + " and works for " + organization + ".");
This will output a message with the details of the Employee
object that was created.
To create instances of
Student
and Employee
, and add them to an ArrayList
in the main class:import java.util.ArrayList; public class Main { public static void main(String[] args) { // Create instances of Student Student student1 = new Student("John Doe", 12345, 3.5, "University of XYZ"); Student student2 = new Student("Jane Smith", 54321, 3.8, "College of ABC"); Student student3 = new Student("Bob Johnson", 98765, 3.2, "Community College"); // Add students to ArrayList ArrayList<Student> stuList = new ArrayList<>(); stuList.add(student1); stuList.add(student2); stuList.add(student3); // Create instances of Employee Employee employee1 = new Employee("Alice Brown", 1001, 5000.0, "ABC Inc."); Employee employee2 = new Employee("Bob Green", 1002, 6000.0, "XYZ Corp."); Employee employee3 = new Employee("Charlie White", 1003, 7000.0, "Acme Co."); // Add employees to ArrayList ArrayList<Employee> empList = new ArrayList<>(); empList.add(employee1); empList.add(employee2); empList.add(employee3); } }
Student
and add them to an ArrayList
called stuList
. We also create three instances of Employee
and add them to an ArrayList
called empList
. These lists can be accessed and modified as needed in the rest of the program.Student
and Employee
objects and print a message if a person is both a student at BITS and an employee at WIPRO:import java.util.ArrayList; public class Main { public static void main(String[] args) { // Create instances of Student Student student1 = new Student("John Doe", 12345, 3.5, "BITS Pilani"); Student student2 = new Student("Jane Smith", 54321, 3.8, "College of ABC"); Student student3 = new Student("Bob Johnson", 98765, 3.2, "Community College"); // Add students to ArrayList ArrayList<Student> stuList = new ArrayList<>(); stuList.add(student1); stuList.add(student2); stuList.add(student3); // Create instances of Employee Employee employee1 = new Employee("Alice Brown", 1001, 5000.0, "ABC Inc."); Employee employee2 = new Employee("Bob Green", 1002, 6000.0, "WIPRO"); Employee employee3 = new Employee("Charlie White", 1003, 7000.0, "Acme Co."); // Add employees to ArrayList ArrayList<Employee> empList = new ArrayList<>(); empList.add(employee1); empList.add(employee2); empList.add(employee3); // Compare student and employee details for (Student student : stuList) { for (Employee employee : empList) { if (student.getName().equals(employee.getName()) && student.getInstitution().equals("BITS Pilani") && employee.getOrganization().equals("WIPRO")) { System.out.println(student.getName() + " is a student of " + student.getInstitution() + " and an employee of " + employee.getOrganization() + "."); } } } } }
In this example, we loop through the stuList
and empList
to compare the details of each Student
and Employee
object. If a person is both a student at BITS Pilani and an employee at WIPRO, we print a message with their name, institution, and organization.
public class BankDeposit { public static void main(String[] args) { deposit(1000); // Deposit in Bank A deposit(1500); // Deposit in Bank B deposit(2000); // Deposit in Bank C } public static void deposit(int amount) { System.out.println("Deposit in Bank: " + amount); } }
deposit()
method that takes an int
parameter for the amount deposited in a bank. We then call this method three times with different arguments to simulate the man depositing money in Bank A, Bank B, and Bank C. The output of this program will be:Deposit in Bank: 1500
Deposit in Bank: 2000
deposit()
method or by creating additional overloaded methods with different parameter lists.B ) Create a program of list of Student Objects and a Map of Course Enrolments. With the Course Enrolments being stored in a HashMap, where the keys are the Course Names and the Values are Set Objects holding the registered students, and the list of students being stored in an ArrayList. Also create a class called Student to hold data on each student, such as their name and age. The Student objects are to be added to the list and the course enrolments are made using this class. Finally, use a for-each loop to iterate over the collections, print out the list of students and the enrolments for each course.
import java.util.*; public class CourseEnrollment { public static void main(String[] args) { // Create a list of Student objects List<Student> studentList = new ArrayList<>(); studentList.add(new Student("John", 20)); studentList.add(new Student("Jane", 22)); studentList.add(new Student("Bob", 19)); // Create a map of course enrollments Map<String, Set<Student>> courseEnrollments = new HashMap<>(); Set<Student> course1 = new HashSet<>(); course1.add(studentList.get(0)); course1.add(studentList.get(1)); courseEnrollments.put("Course 1", course1); Set<Student> course2 = new HashSet<>(); course2.add(studentList.get(1)); course2.add(studentList.get(2)); courseEnrollments.put("Course 2", course2); // Iterate over the collections and print out the results System.out.println("List of Students:"); for (Student student : studentList) { System.out.println(student.getName() + " (age " + student.getAge() + ")"); } System.out.println("\nEnrollments for each course:"); for (String course : courseEnrollments.keySet()) { System.out.println(course + ":"); Set<Student> students = courseEnrollments.get(course); for (Student student : students) { System.out.println("- " + student.getName() + " (age " + student.getAge() + ")"); } } } } class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
In this example, we create a list of Student
objects and a map of course enrollments using a HashMap
. We then populate the HashMap
with Set
objects that hold the registered students for each course. We use a for-each loop to iterate over the collections and print out the list of students and the enrollments for each course.
The output of this program will be:
List of Students:
John (age 20)
Jane (age 22)
Bob (age 19)
Enrollments for each course:
Course 1:
– John (age 20)
– Jane (age 22)
Course 2:
– Jane (age 22)
– Bob (age 19)
i).Input two email from the user
import java.util.Scanner; public class Employee { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Input two email addresses from the user System.out.print("Enter the first email address: "); String email1 = input.nextLine(); System.out.print("Enter the second email address: "); String email2 = input.nextLine(); // Extract the domains from the email addresses String domain1 = email1.substring(email1.indexOf("@") + 1); String domain2 = email2.substring(email2.indexOf("@") + 1); // Display the domains System.out.println("Domain of first email: " + domain1); System.out.println("Domain of second email: " + domain2); // Check if the domains are the same if (domain1.equals(domain2)) { System.out.println("Both are brothers"); } else { System.out.println("Both are enemies"); } } }
In this program, we use a Scanner
object to get input from the user. We then extract the domain names from the email addresses using the substring()
method and the indexOf()
method to find the index of the “@” character. Finally, we compare the domains and display the appropriate message.
For example, if the user inputs “raj@gmail.com” and “usha@rediffmail.com“, the output will be:
Domain of first email: gmail.com Domain of second email: rediffmail.com Both are enemies
import java.util.Random; public class MultiThreadedProgram { public static void main(String[] args) { Random random = new Random(); Thread thread1 = new Thread(() -> { while (true) { int value = random.nextInt(100); System.out.println("Generated value: " + value); if (value % 2 == 0) { synchronized (thread2) { thread2.notify(); } } else { synchronized (thread3) { thread3.notify(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread thread2 = new Thread(() -> { while (true) { synchronized (thread2) { try { thread2.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int value = random.nextInt(100); if (value % 2 == 0) { System.out.println("Square of " + value + ": " + (value * value)); } } }); Thread thread3 = new Thread(() -> { while (true) { synchronized (thread3) { try { thread3.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int value = random.nextInt(100); if (value % 2 != 0) { System.out.println("Cube of " + value + ": " + (value * value * value)); } } }); thread1.start(); thread2.start(); thread3.start(); } }
In this program, we use the Random
class to generate a random integer every 1 second in the first thread. If the value is even, we notify the second thread, and if it is odd, we notify the third thread.
The second thread waits for a notification from the first thread, then generates another random integer and computes its square if it is even.
The third thread waits for a notification from the first thread, then generates another random integer and computes its cube if it is odd.
To synchronize the threads, we use the synchronized
keyword and the wait()
and notify()
methods.
When we run this program, it will generate random values and print the square or cube of each value, depending on whether it is even or odd.
For More Updates Join Our Channels :