0% found this document useful (0 votes)
2 views33 pages

Java Model Examination Anwer Key (4)

The document provides an answer key for a Java programming model examination at R.M.D. Engineering College for the academic year 2023-2024. It covers various topics including control structures, instance vs class variables, the use of 'final', abstract vs concrete classes, and JDBC connection steps, along with practical programming tasks such as simulating a bank account management system and managing student enrollment. Each section includes explanations, code examples, and differences between concepts in Java.

Uploaded by

gpartha0673
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views33 pages

Java Model Examination Anwer Key (4)

The document provides an answer key for a Java programming model examination at R.M.D. Engineering College for the academic year 2023-2024. It covers various topics including control structures, instance vs class variables, the use of 'final', abstract vs concrete classes, and JDBC connection steps, along with practical programming tasks such as simulating a bank account management system and managing student enrollment. Each section includes explanations, code examples, and differences between concepts in Java.

Uploaded by

gpartha0673
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

R.M.D.

ENGINEERING COLLEGE
(An Autonomous Institution)
22CS202 JAVA PROGRAMMING

ACADEMIC YEAR 2023 - 2024


MODEL EXAMINATION - ANSWER KEY

PART - A
1. Explain the role of the “break” and “continue” statements in Java control structures.
BREAK:
When a break statement is executed, the most deeply nested loop currently being executed is ended
and execution picks up with the next statement after the loop.
For example, consider the following program:
while (1) {
if (n < 0) break;
foo(n);
n = n - 1;
}

CONTINUE:
The continue statement ends the current operation of the loop and returns to the condition at the top
of the loop. Such loops are typically used to exclude some values from calculations.
For example, we could use the following loop to sum the positive values in the array x,
real sum;
sum = 0;
for (n in 1:size(x)) {
if (x[n] <= 0) continue;
sum += x[n];
}

2. What is the difference between instance variables and class variables in Java?
Instance Variable Class Variable

It is a variable whose value is instance-


It is a variable that defines a specific
specific and now shared among
attribute or property for a class.
instances.
These variables cannot be shared
These variables can be shared between
between classes. Instead, they only
class and its subclasses.
belong to one specific class.

It usually maintains a single shared


It usually reserves memory for data that
value for all instances of class even if
the class needs.
no instance object of the class exists.

It is generally created when an instance It is generally created when the program


of the class is created. begins to execute.

It normally retains values as long as the It normally retains values until the
object exists. program terminates.

3. State the implications of using “final” with methods and variables

o The final keyword can be used to indicate that something cannot be changed.
o It can be used in several contexts, such as to declare a variable as a constant, to declare a
method as final, or to declare a class as final.
o The final Keyword in Java behaves differently when used with classes, methods, and
variables
o Once any data member (a variable, method, or class) gets declared as final, it can only be
assigned once.
o The final variable cannot be reinitialized with another value.
o A final method cannot be overridden by another method.
o A final class cannot be extended or inherited by another child class.
Variables with Final Keywords
When a final keyword is used with a variable, it makes the variable constant. Hence, once assigned, the
value of the variable cannot be changed.

public class MyClass {

public static void main(String[] args) {

final int num = 10;

[Link](num); // prints 10

// the following line will cause an error because num is final

num = 20;

Methods With Final Keywords


The final keyword can also be used to declare a method as final. A final method cannot be overridden
by a subclass.
4.
How do abstract classes differ from concrete classes?

Abstract Class Concrete Class


An abstract class is declared using A concrete class is not declared using
abstract modifier. abstract modifier.

An abstract class cannot be directly A concrete class can be directly


instantiated using the new keyword. instantiated using the new keyword.

An abstract class may or may not A concrete class cannot contain an


contain abstract methods. abstract method.

An abstract class cannot be declared A concrete class can be declared as


as final. final.

Implement an interface is possible by


not providing implementations of all Easy implementation of all of the
of the interface’s methods. For this a methods in the interface.
child class is needed..

5. Enlist the difference between generic class and a generic method in java

Generic methods introduce their type of parameters, i.e., static and non-static generic methods are
allowed and constructors. The methods in a generic class can use a class type parameter and are,
therefore, automatically generic relative to the type parameter.

Generic Class
The general form or the syntax for declaring a generic class is shown below:

Class class-name <type-arg-list>{ //……

And the syntax for declaring a reference to a generic class is:

Class-name <type-arg-list> var-name= new class-name<type-arg-list>

(cons-arg-list);

Generic classes can also be a part of the class hierarchy in the same way a generic class can be. Thus, a
as both a superclass and a subclass.

6. Define thread priorties

Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, the thread scheduler schedules the threads according to their priority.
public final int getPriority(): The [Link]() method returns the priority of the
given thread.

public final void setPriority(int newPriority): The [Link]() method updates or


assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the
value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).

3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value
of MAX_PRIORITY is 10.
7. Enlist the differences between Iterator and ListIterator in Java

Iterator ListIterator

Can traverse elements present in


Can traverse elements present in
Collection both in forward and
Collection only in the forward direction.
backward directions.

Can only traverse List and not the


Helps to traverse Map, List and Set.
other two.

It has methods like nextIndex() and


Indexes cannot be obtained by using previousIndex() to obtain indexes
Iterator. of elements at any time while
traversing List.
Cannot modify or replace elements We can modify or replace elements
present in Collection with the help of set(E e)

Cannot add elements and it throws Can easily add elements to a


ConcurrentModificationException. collection at any time.

Certain methods of ListIterator are


Certain methods of Iterator are next(),
next(), previous(), hasNext(),
remove() and hasNext().
hasPrevious(), add(E e).

8. How do you create a regular expression pattern in Java?

 A regular expression is a sequence of characters that forms a search pattern. When you
search for data in a text, you can use this search pattern to describe what you are
searching for.

 A regular expression can be a single character, or a more complicated pattern.

 Regular expressions can be used to perform all types of text search and text replace
operations.

 Java does not have a built-in Regular Expression class, but we can import the
[Link] package to work with regular expressions. The package includes the
following classes:

 Pattern Class - Defines a pattern (to be used in a search)


 Matcher Class - Used to search for the pattern
 PatternSyntaxException Class - Indicates syntax error in a regular expression pattern
 The first parameter of the [Link]() method is the pattern. It describes what is
being searched for.

 Brackets are used to find a range of characters:

Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find one character NOT between the brackets
[0-9] Find one character from the range 0 to 9
9. What is a ResultSet in JDBC, and how is it used to retrieve data from a database?
 The ResultSet is an interface available in JDBC which is used for data handling by
using result object of preparedStatement class.
 Syntax:
The below statements is representing the syntax of ResultSet with PreparedStatement object.
PreparedStatementpreparedStatement = [Link](sql_query);
ResultSetresultSet = [Link]();

Implementation of ResultSet
 First, we need create One class in our Java project.
 After that need to establish the connection with MySQL Database by using JDBC and We
need one jar file that is [Link] file.
 Once complete connection then create table in database with some data in it.
 Now, write the SQL query for retrieving all data from Table by using preparedStatement.
 After that preparedStatement object is call the executeQuery method for executing the SQL
query once the query is successfully executed then we get result of data based this SQL
query.
 Now this result is assigned to ResultSet object.

10. Write the steps involved in establishing a connection to a databased using JDBC?
JDBC is an acronym for Java Database Connectivity. It’s an advancement for
ODBC ( Open Database Connectivity ). JDBC is a standard API specification developed in order to
move data from the front end to the back end. This API consists of classes and interfaces written in
Java. It basically acts as an interface (not the one we use in Java) or channel between your Java
program and databases i.e it establishes a link between the two so that a programmer can send data
from Java code and store it in the database for future use.

The steps that explains how to connect to Database in Java:

Step 1 – Import the Packages


Step 2 – Load the drivers using the forName() method
Step 3 – Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5 – Create a statement
Step 6 – Execute the query
Step 7 – Close the connections
PART - B
11.a. Write a Java program to simulate a bank account management system. Implement classes for
customers, accounts and transactions. Use arrays to store account records and methods to deposit,
withdraw and transfer funds between accounts.

class Customer
{
String name;
String customerId;
Customer(String name, String customerId)
{
[Link] = name;
[Link] = customerId;
}
}
class Account
{
String accountId;
Customer cust;
double balance;
Account(String accountId, Customer cust, double balance)
{
[Link] = accountId;
[Link] = cust;
[Link] = balance;
}

void deposit(double amount)


{
if (amount > 0) {
balance += amount;
[Link]("Deposit successful. New balance: " + balance);
} else {
[Link]("Deposit amount must be positive.");
}
}

void withdraw(double amount)


{
if (amount > 0 && amount <= balance)
{
balance -= amount;
[Link]("Withdrawal successful. New balance: " + balance);
}
else
{
[Link]("Withdrawal amount must be positive and less than or equal to the balance.");
}
}

void transfer(Account toAccount, double amount)


{
if (amount > 0 && amount <= balance)
{
balance -= amount;
[Link](amount);
[Link]("Transfer successful. New balance: " + balance);
}
else
{
[Link]("Transfer amount must be positive and less than or equal to the balance.");
}
}
}

class Bank
{
Account[] accounts;
int num;
Bank(int max)
{
accounts = new Account[max];
}

void addAccount(Account acc)


{
if (num < [Link])
{
accounts[num++] = acc;
[Link]("Account added successfully.");
} else {
[Link]("Bank is full, cannot add more accounts.");
}
}

void displayAccounts()
{
for (int i = 0; i < num; i++)
{
Account acc = accounts[i];
[Link]("Account ID: " + [Link] + ", Customer: " + [Link] + ", Balance:
" + [Link]);
}
}
}

public class Main


{
public static void main(String[] args)
{
[Link]("Creating Customers and Accounts");
Customer customer1 = new Customer("John", "C001");
Customer customer2 = new Customer("Smith", "C002");

Account account1 = new Account("A001", customer1, 500);


Account account2 = new Account("A002", customer2, 1000);

Bank bank = new Bank(10);


[Link](account1);
[Link](account2);

[Link]("Displaying account details BEFORE Transaction");


[Link]();

[Link]("Performing Transactions");
[Link](200);
[Link](100);
[Link](account2, 150);
[Link]("Displaying account details AFTER Transaction");
[Link](); }
}
OUTPUT:

Creating Customers and Accounts


Account added successfully.
Account added successfully.

Displaying account details BEFORE Transaction


Account ID: A001, Customer: John, Balance: 500.0
Account ID: A002, Customer: Smith, Balance: 1000.0

Performing Transactions
Deposit successful. New balance: 700.0
Withdrawal successful. New balance: 600.0
Deposit successful. New balance: 1150.0
Transfer successful. New balance: 450.0

Displaying account details AFTER Transaction


Account ID: A001, Customer: John, Balance: 450.0
Account ID: A002, Customer: Smith, Balance: 1150.0
11. b. Create a Java program to manage student enrollment at a university. Define classes for
students, courses and enrollments. Utilize arrays to store student and course records and methods
to enroll students in courses, drop courses and calculate GPA for each student.

class Student {
String studentId;
String name;
Course[] courses;
int num;

Student(String studentId, String name) {


[Link] = studentId;
[Link] = name;
[Link] = new Course[5]; // Maximum 5 courses per student
[Link] = 0;
}
void enroll(Course course)
{
if (num < [Link])
{
courses[num++] = course;
[Link](name + " enrolled in " + [Link]);
}
else
{
[Link](name + " cannot enroll in more courses.");
}
}

void drop(Course course) {


for (int i = 0; i < num; i++) {
if (courses[i].equals(course)) {
courses[i] = courses[--num];
courses[num] = null;
[Link](name + " dropped " + [Link]);
return;
}
}
[Link](name + " is not enrolled in " + [Link]);
}

void displayCourses() {
[Link](name + " is enrolled in:");
for (int i = 0; i < num; i++) {
[Link]("- " + courses[i].courseName);
}
}
}
class Course
{
String courseId;
String courseName;

Course(String courseId, String courseName) {


[Link] = courseId;
[Link] = courseName;
}

public class Main


{
public static void main(String[] args) {
// Create students
Student student1 = new Student("S1", "John");
Student student2 = new Student("S2", "Smith");

// Create courses
Course course1 = new Course("C1", "Mathematics");
Course course2 = new Course("C2", "Physics");

// Enroll students in courses


[Link](course1);
[Link](course2);
[Link](course1);

// Display enrolled courses


[Link]();
[Link]();

// Drop a course for a student


[Link](course2);

// Display enrolled courses after dropping a course


[Link]();
}
}
OUTPUT:

John enrolled in Mathematics


John enrolled in Physics
Smith enrolled in Mathematics
John is enrolled in:
- Mathematics
- Physics
Smith is enrolled in:
- Mathematics
John dropped Physics
John is enrolled in:
- Mathematics
12.a. Develop a Java program for a library catalog system. Implement classes for different types of
materials such as books, journals and DVDs. Use Inheritance to represent their common attributes.
Override methods to calculate due dates and display item details

import [Link];
import [Link];

abstract class LibraryItem {


protected String title;
protected String author;
protected LocalDate checkoutDate;
protected int checkoutPeriodDays;

public LibraryItem(String title, String author, int checkoutPeriodDays) {


[Link] = title;
[Link] = author;
[Link] = checkoutPeriodDays;
}

public abstract LocalDate calculateDueDate();

public abstract void displayDetails();

public String getTitle() {


return title;
}

public String getAuthor() {


return author;
}
}

class Book extends LibraryItem {


private int pageCount;

public Book(String title, String author, int pageCount) {


super(title, author, 14); // Default checkout period for books: 14 days
[Link] = pageCount;
}

@Override
public LocalDate calculateDueDate() {
return [Link](checkoutPeriodDays);
}
@Override
public void displayDetails() {
[Link]("Title: " + title);
[Link]("Author: " + author);
[Link]("Page Count: " + pageCount);
}
}

class Journal extends LibraryItem {


private String publicationDate;

public Journal(String title, String author, String publicationDate) {


super(title, author, 7); // Default checkout period for journals: 7 days
[Link] = publicationDate;
}

@Override
public LocalDate calculateDueDate() {
return [Link](checkoutPeriodDays);
}

@Override
public void displayDetails() {
[Link]("Title: " + title);
[Link]("Author: " + author);
[Link]("Publication Date: " + publicationDate);
}
}

class DVD extends LibraryItem {


private int durationMinutes;

public DVD(String title, String author, int durationMinutes) {


super(title, author, 3); // Default checkout period for DVDs: 3 days
[Link] = durationMinutes;
}

@Override
public LocalDate calculateDueDate() {
return [Link](checkoutPeriodDays);
}

@Override
public void displayDetails() {
[Link]("Title: " + title);
[Link]("Director: " + author);
[Link]("Duration (minutes): " + durationMinutes);
}
}
public class Main
{
public static void main(String[] args) {
// Sample usage
Book book = new Book("Java Programming", "John ", 500);
[Link] = [Link]();
[Link]("Due Date for Book: " +
[Link]().format([Link]("dd/MM/yyyy")));
[Link]();

Journal journal = new Journal("Science Today", "Smith", "01/05/2024");


[Link] = [Link]();
[Link]("\nDue Date for Journal: " +
[Link]().format([Link]("dd/MM/yyyy")));
[Link]();

DVD dvd = new DVD("Inception", "Christopher Nolan", 180);


[Link] = [Link]();
[Link]("\nDue Date for DVD: " +
[Link]().format([Link]("dd/MM/yyyy")));
[Link]();
}
}

OUTPUT:
Due Date for Book: 15/06/2024
Title: Java Programming
Author: John
Page Count: 500

Due Date for Journal: 08/06/2024


Title: Science Today
Author: Smith
Publication Date: 01/05/2024

Due Date for DVD: 04/06/2024


Title: Inception
Director: Christopher Nolan
Duration (minutes): 180
12.b. (i) Create a Java program that generates a random number between 1 and 10 and asks the user to guess it.
Handle the Input Mismatch Exception that may occur if the user enters a non-numeric value. (6.5 Marks)

import [Link].*;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Random random = new Random();
int randomNumber = [Link](10) + 1; // Generates a random number between 1 and 10

[Link]("Welcome to Guess the Number game!");


[Link]("I have picked a number between 1 and 10. Can you guess it?");

while (true) {
try {
[Link]("Enter your guess: ");
int userGuess = [Link]();

if (userGuess < 1 || userGuess > 10) {


[Link]("Please enter a number between 1 and 10.");
} else if (userGuess == randomNumber) {
[Link]("Congratulations! You guessed it right!");
break;
} else {
[Link]("Sorry, that's incorrect. Try again!");
}
} catch (InputMismatchException e) {
[Link]("Invalid input. Please enter a valid number.");
[Link](); // Clear the input buffer
}
}

[Link]();
}
}
OUTPUT:
Welcome to Guess the Number game!
I have picked a number between 1 and 10. Can you guess it?
Enter your guess: a
Invalid input. Please enter a valid number.
Enter your guess: 15
Please enter a number between 1 and 10.

(ii) Write a Java Program that prompts the user to enter their grade and calculates their GPA.
Handle the Illegal Argument Exception that may occur if the grade entered is not valid (e.g., not
within the range A to F). (6.5 Marks)

import [Link].*;

public class CalculateGPA {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Welcome to GPA Calculator!");

try {
[Link]("Enter your grade (A to F): ");
String grade = [Link]().toUpperCase();

double gpa = calculateGPA(grade);


[Link]("Your GPA is: " + gpa);
} catch (IllegalArgumentException e) {
[Link]("Invalid grade entered. Grade must be between A to F.");
}

[Link]();
}

public static double calculateGPA(String grade) {


switch (grade) {
case "A":
return 4.0;
case "B":
return 3.0;
case "C":
return 2.0;
case "D":
return 1.0;
case "F":
return 0.0;
default:
throw new IllegalArgumentException("Invalid grade: " + grade);
}
}
}
OUTPUT:

Welcome to GPA Calculator!


Enter your grade (A to F): H
Invalid grade entered. Grade must be between A to F.
13.a. Create a multithreaded Java program to generate prime numbers upto a given limit. Each thread
should handle a different segment of the prime number generation.

import [Link];
import [Link];

class PrimeGenerator implements Runnable {


private final int start;
private final int end;
private final List<Integer> primes;

public PrimeGenerator(int start, int end, List<Integer> primes) {


[Link] = start;
[Link] = end;
[Link] = primes;
}

private boolean isPrime(int num) {


if (num <= 1) return false;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) return false;
}
return true;
}

@Override
public void run() {
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
synchronized (primes) {
[Link](i);
}
}
}
}
}

public class MultiThreadedPrimeGenerator {


public static void main(String[] args) {
int limit = 100; // Change this to your desired limit
int numThreads = 4; // Change this to the number of threads you want to use

List<Integer> primes = new ArrayList<>();


List<Thread> threads = new ArrayList<>();

int segmentSize = limit / numThreads;

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


int start = i * segmentSize + 1;
int end = (i + 1) * segmentSize;
if (i == numThreads - 1) {
end = limit;
}
Thread thread = new Thread(new PrimeGenerator(start, end, primes));
[Link](thread);
[Link]();
}

for (Thread thread : threads) {


try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
}

[Link]("Prime numbers up to " + limit + ":");


[Link](primes);
}
}

OUTPUT:
Prime numbers up to 100:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 79, 53, 59, 61, 67, 71, 73, 29, 31, 37, 41, 43, 47, 83, 89, 97]

Prime numbers up to 200:


[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179...

13.b. Create a Java program to search for a specific string in a text file and display all occurrences along
with their line numbers.

import [Link];
import [Link];
import [Link];

public class TextSearch {

public static void main(String[] args) {


String filePath = "[Link]"; // Update with your file path
String searchString = "java"; // Update with your search string

try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
int lineNumber = 1;

while ((line = [Link]()) != null) {


if ([Link](searchString)) {
[Link]("Found at line " + lineNumber + ": " + line);
}
lineNumber++;
}

[Link]();
} catch (IOException e) {
[Link]("Error reading the file: " + [Link]());
}
}
}
OUTPUT:
Found at line 2: Welcome to Java Programming!

14.a (i) Develop a Java program to filter even numbers from an array using lambda expressions and
. store them in another array (6.5 marks)

import [Link].*;

@FunctionalInterface
interface CheckEven {
boolean check(int num);
}
public class Main {
public static void main(String[] args) {
// Input array
int[] inputArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// List to store even numbers


List<Integer> evenNumbersList = new ArrayList<>();

// Lambda expression to check if a number is even


CheckEven isEven = (num) -> num % 2 == 0;

// Iterate through the array and use the lambda expression to find even numbers
for (int num : inputArray) {
if ([Link](num)) {
[Link](num);
}
}

// Convert the List<Integer> to an int array


int[] evenNumbersArray = new int[[Link]()];
for (int i = 0; i < [Link](); i++) {
evenNumbersArray[i] = [Link](i);
}

// Print the result


[Link]("Even numbers: " + [Link](evenNumbersArray));
}

}
OUTPUT:
Even numbers: [2, 4, 6, 8, 10]
(ii) Develop a Java program to iterate over a Linked List of integers and calculate the sum of all elements
using an iterator

import [Link].*;
public class Main {

public static void main(String[] args) {

LinkedList<Integer> numbers = new LinkedList<>();


[Link](10);
[Link](20);
[Link](30);
[Link](40);
int sum = 0;
Iterator<Integer> it = [Link]();
while ([Link]()) {
sum += [Link]();
}
[Link]("Sum of elements: " + sum);
}
}
OUTPUT:
Sum of elements: 100
14. Create a Java program that acts as a dictionary using a Hash Map. Store word definitions in the
b. Hash Map and implement functionalities to search for word definitions, add new words, and update
existing definitions

import [Link].*;
public class Main {
public static void main(String[] args) {

HashMap<String, String> dictionary = new HashMap<>();


Scanner scanner = new Scanner([Link]);

while (true) {
[Link]("\nDictionary Menu:");
[Link]("1. Add new word");
[Link]("2. Search for word definition");
[Link]("3. Update word definition");
[Link]("4. Exit");
[Link]("Choose an option: ");

int choice = [Link]();


[Link](); // Consume newline

if (choice == 1) {
// Add new word
[Link]("Enter word: ");
String word = [Link]();
[Link]("Enter definition: ");
String definition = [Link]();
[Link](word, definition);
[Link]("Word added successfully!");
}

else if (choice == 2) {
// Search for word definition
[Link]("Enter word to search: ");
String word = [Link]();
String definition = [Link](word);
if (definition != null) {
[Link]("Definition: " + definition);
} else {
[Link]("Word not found!");
}
}

else if (choice == 3) {
// Update word definition
[Link]("Enter word to update: ");
String word = [Link]();
if ([Link](word)) {
[Link]("Enter new definition: ");
String definition = [Link]();
[Link](word, definition);
[Link]("Definition updated successfully!");
} else {
[Link]("Word not found!");
}
}

else if (choice == 4) {
// Exit
[Link]("Execution over");
break;
} else {
[Link]("Invalid choice, please try again.");
}
}
[Link]();
}
}

OUTPUT:

Dictionary Menu:
1. Add new word
2. Search for word definition
3. Update word definition
4. Exit
Choose an option: 1
Enter word: hello
Enter definition: Greet a person
Word added successfully!

Dictionary Menu:
1. Add new word
2. Search for word definition
3. Update word definition
4. Exit
Choose an option: 2
Enter word to search: hello
Definition: Greet a person

15.a. Create a Java application with JDBC Connectivity to track inventory in a warehouse or store.
Users can add new products, update product details and search for products by name or category.

import [Link].*;
import [Link];

public class InventoryApp {


// Database URL, username and password
static final String DB_URL = "jdbc:mysql://localhost:3306/InventoryDB";
static final String USER = "root"; // Replace with your MySQL username
static final String PASS = ""; // Replace with your MySQL password

public static void main(String[] args) {


try {
// Establishing a connection
Connection conn = [Link](DB_URL, USER, PASS);
Scanner scanner = new Scanner([Link]);

while (true) {
// Display menu
[Link]("\nInventory Menu:");
[Link]("1. Add new product");
[Link]("2. Update product details");
[Link]("3. Search for product by name");
[Link]("4. Search for product by category");
[Link]("5. Exit");
[Link]("Choose an option: ");

int choice = [Link]();


[Link](); // Consume newline

if (choice == 1) {
// Add new product
[Link]("Enter product name: ");
String name = [Link]();
[Link]("Enter product category: ");
String category = [Link]();
[Link]("Enter product quantity: ");
int quantity = [Link]();
[Link]("Enter product price: ");
double price = [Link]();

String sql = "INSERT INTO products (name, category, quantity, price) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = [Link](sql);
[Link](1, name);
[Link](2, category);
[Link](3, quantity);
[Link](4, price);
[Link]();

[Link]("Product added successfully!");


}
else if (choice == 2) {
// Update product details
[Link]("Enter product ID to update: ");
int id = [Link]();
[Link](); // Consume newline
[Link]("Enter new product name: ");
String name = [Link]();
[Link]("Enter new product category: ");
String category = [Link]();
[Link]("Enter new product quantity: ");
int quantity = [Link]();
[Link]("Enter new product price: ");
double price = [Link]();

String sql = "UPDATE products SET name = ?, category = ?, quantity = ?, price = ? WHERE
id = ?";
PreparedStatement pstmt = [Link](sql);
[Link](1, name);
[Link](2, category);
[Link](3, quantity);
[Link](4, price);
[Link](5, id);
[Link]();

[Link]("Product details updated successfully!");


}
else if (choice == 3) {
// Search for product by name
[Link]("Enter product name to search: ");
String name = [Link]();
String sql = "SELECT * FROM products WHERE name = ?";
PreparedStatement pstmt = [Link](sql);
[Link](1, name);
ResultSet rs = [Link]();

while ([Link]()) {
[Link]("ID: " + [Link]("id"));
[Link]("Name: " + [Link]("name"));
[Link]("Category: " + [Link]("category"));
[Link]("Quantity: " + [Link]("quantity"));
[Link]("Price: " + [Link]("price"));
[Link]("----------------------");
}
}
else if (choice == 4) {
// Search for product by category
[Link]("Enter product category to search: ");
String category = [Link]();

String sql = "SELECT * FROM products WHERE category = ?";


PreparedStatement pstmt = [Link](sql);
[Link](1, category);
ResultSet rs = [Link]();

while ([Link]()) {
[Link]("ID: " + [Link]("id"));
[Link]("Name: " + [Link]("name"));
[Link]("Category: " + [Link]("category"));
[Link]("Quantity: " + [Link]("quantity"));
[Link]("Price: " + [Link]("price"));
}
}
else if (choice == 5) {
// Exit
[Link]("Exiting the application. ");
break;
} else {
[Link]("Invalid choice! Please choose again.");
}
}

[Link]();
[Link]();
}
catch (SQLException e)
{
[Link]();
}
}
}
OUTPUT:

Inventory Menu:
1. Add new product
2. Update product details
3. Search for product by name
4. Search for product by category
5. Exit
Choose an option: 1
Enter product name: Laptop
Enter product category: Electronics
Enter product quantity: 10
Enter product price: 999.99
Product added successfully!

Inventory Menu:
1. Add new product
2. Update product details
3. Search for product by name
4. Search for product by category
5. Exit
Choose an option: 5
Exiting the application.
15. Develop a Java application for managing events using embedded SQL. Implement functionality to add new
b events, update event details, search for events by date or location, and delete events from the system

import [Link].*;
import [Link];
public class EventManager {
public static void main(String[] args) {
try {
Connection conn = [Link]("jdbc:sqlite:[Link]");
DefaultContext ctx = new DefaultContext(conn);
createEventsTable(ctx);
insertEvent(ctx, "Event1", "2024-06-01", "Location1", "Description1");
updateEvent(ctx, 1, "UpdatedEvent", "2024-06-02", "UpdatedLocation", UpdatedDescription");
searchEventByDate(ctx, "2024-06-01");
searchEventByLocation(ctx, "Location1");
deleteEvent(ctx, 1);

[Link]();
[Link]();
} catch (SQLException e) {
[Link]();
}
}
public static void createEventsTable(DefaultContext ctx) throws SQLException {
#sql { CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
date TEXT NOT NULL,
location TEXT NOT NULL,
description TEXT)
};
}
public static void insertEvent(DefaultContext ctx, String name, String date, String location, String
description) throws SQLException
{
#sql { INSERT INTO events (name, date, location, description) VALUES (:name, :date, :location,
:description) };
}
public static void updateEvent(DefaultContext ctx, int id, String name, String date, String location, String
description) throws SQLException
{
#sql { UPDATE events SET name = :name, date = :date, location = :location, description =
:description WHERE id = :id };
}
public static void searchEventByDate(DefaultContext ctx, String date) throws SQLException
{
#sql { SELECT * FROM events WHERE date = :date };
}
public static void searchEventByLocation(DefaultContext ctx, String location) throws SQLException
{
#sql { SELECT * FROM events WHERE location = :location };
}
public static void deleteEvent(DefaultContext ctx, int id) throws SQLException {
#sql { DELETE FROM events WHERE id = :id };
}
}

PART - C
16. Predict the output of the following Code Snippets
a Program 1:
class Parent
{
Parent()
{
[Link](“Parent Constructor”);
}
}
class Child extends Parent
{
Child()
{
super();
[Link](“Child constructor”);
}
public static void main(String[] args)
{
Child obj=new Child();
}
}
OUTPUT:
Parent Constructor
Child constructor
Program 2:
class MyThread extends Thread
{
public void run()
{
[Link](“Thread priority:” + [Link]().getPriority());
}
public static void main(String[] args)
{
MyThread thread1=new MyThread();
MyThread thread2=new MyThread();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}
OUTPUT:

Thread priority:1
Thread priority:10
Program 3:
String str=”apple, banana, orange”;
String[] fruits=[Link](“,”);
for(String fruit:fruits)
{
[Link](fruit);
}
OUTPUT:

apple
banana
orange
Program 4:
try
{
[Link](“Try block”);
int resut=10/0;
}
catch(ArithmeticException e)
{
[Link](“Arithmetic Exception occurred”);
}
finally
{
[Link](“Finally block”);
}
OUTPUT:
Try block
Arithmetic Exception occurred
Finally block
Program 5:
class MyClass
{
public <T extends Number> void display(T value)
{
[Link](“Value:” + value);
}
}
public class Main
{
public static void main(String[] args)
{
MyClass obj=new MyClass();
[Link](10);
[Link](3.14);
}
}
OUTPUT:
Value:10
Value:3.14
16. Identify and correct the error in the following Java Codes. Explain the error
b.
public class MyClass
{
public void display(int num)
{
[Link](“Integer:” + num);
}
private void display(double num)
{
[Link](“Double:” + num);
}
public static void main(String[] args)
{
MyClass obj=new MyClass();
[Link](42);
[Link](3.14);
}
}

NO ERROR IN THIS PROGRAM

OUTPUT:
Integer:42
Double:3.14

Program 2:
import [Link];
public class Main
{
public static void main(String[] args)
{
int [] numbers={5,3,2,4,1};
[Link](numbers);
[Link](“Sorted numbers:” + numbers);
}
}
Explanation for the error:
 The issue with your program is that when we print the numbers array directly after applying
[Link](numbers), it doesn't output the elements of the array in a readable format.
 Instead, it prints the memory address of the array object.
 To print the sorted array, you can use [Link](numbers) which converts the array to a
string representation that shows the elements in a readable format or print the elements of the
sorted array using loops.

Corrected Program:
import [Link];
public class Main
{
public static void main(String[] args)
{
int [] numbers={5,3,2,4,1};
[Link](numbers);
[Link](“Sorted numbers:” + [Link](numbers));
}
}
OUTPUT:
Sorted numbers:[1, 2, 3, 4, 5]

Program 3:
import [Link];
import [Link];
import [Link];
public class Main
{
public static void main(String[] args)
{
try
{
File file=new File(“[Link]”);
FileInputStream fis=new FileInputStream(file);
}
catch(IOException e)
{
[Link]();
}
}
}
NO ERROR IN THIS PROGRAM
OUTPUT:
If the file is not found, the FileInputStream will throw a FileNotFoundException, which is a subclass of
IOException, and the catch block will handle it by printing the stack trace.

Program 4:
class Parent
{
public void display()
{
[Link](“Parent class”);
}
}
class Child extends Parent
{
public void display()
{
[Link](“Child class”);
}
}
public class Main
{
public static void main(String[] args)
{
Parent parent=new Child();
[Link]();
}
}
NO ERROR IN THIS PROGRAM
OUTPUT:
Child class
Program 5:

public class Main


{
private int value;
public Main()
{
value=0;
}
public static void main(String[] args)
{
Main obj=new Main;
[Link](“Value:” + [Link]);
}
}
Explanation for the error:
In the line of object creation, there is a syntax error as the arguments for the constructor is
missing.
Constructor is a method of a class which has the same name as the class name and is used to initialize
the objects of the class.
The constructor should be defined and invoked as follows:
class Geek {

Geek() // No argument constructor
{

}
}
class Sample {
public static void main(String[] args)
{
Geek geek1 = new Geek(); // Object creation and construction invocation
}
}
Corrected Program:
public class Main
{
private int value;
public Main()
{
value=0;
}
public static void main(String[] args)
{
Main obj=new Main();
[Link](“Value:” + [Link]);
}
}
OUTPUT:
Value: 0

You might also like