Java Model Examination Anwer Key (4)
Java Model Examination Anwer Key (4)
ENGINEERING COLLEGE
(An Autonomous Institution)
22CS202 JAVA PROGRAMMING
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 normally retains values as long as the It normally retains values until the
object exists. program terminates.
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.
[Link](num); // prints 10
num = 20;
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:
(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.
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.
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
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.
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:
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.
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;
}
class Bank
{
Account[] accounts;
int num;
Bank(int max)
{
accounts = new Account[max];
}
void displayAccounts()
{
for (int i = 0; i < num; i++)
{
Account acc = accounts[i];
[Link]("Account ID: " + [Link] + ", Customer: " + [Link] + ", Balance:
" + [Link]);
}
}
}
[Link]("Performing Transactions");
[Link](200);
[Link](100);
[Link](account2, 150);
[Link]("Displaying account details AFTER Transaction");
[Link](); }
}
OUTPUT:
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
class Student {
String studentId;
String name;
Course[] courses;
int num;
void displayCourses() {
[Link](name + " is enrolled in:");
for (int i = 0; i < num; i++) {
[Link]("- " + courses[i].courseName);
}
}
}
class Course
{
String courseId;
String courseName;
// Create courses
Course course1 = new Course("C1", "Mathematics");
Course course2 = new Course("C2", "Physics");
import [Link];
import [Link];
@Override
public LocalDate calculateDueDate() {
return [Link](checkoutPeriodDays);
}
@Override
public void displayDetails() {
[Link]("Title: " + title);
[Link]("Author: " + author);
[Link]("Page Count: " + pageCount);
}
}
@Override
public LocalDate calculateDueDate() {
return [Link](checkoutPeriodDays);
}
@Override
public void displayDetails() {
[Link]("Title: " + title);
[Link]("Author: " + author);
[Link]("Publication Date: " + publicationDate);
}
}
@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]();
OUTPUT:
Due Date for Book: 15/06/2024
Title: Java Programming
Author: John
Page Count: 500
import [Link].*;
while (true) {
try {
[Link]("Enter your guess: ");
int userGuess = [Link]();
[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].*;
try {
[Link]("Enter your grade (A to F): ");
String grade = [Link]().toUpperCase();
[Link]();
}
import [Link];
import [Link];
@Override
public void run() {
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
synchronized (primes) {
[Link](i);
}
}
}
}
}
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]
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];
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
int lineNumber = 1;
[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};
// Iterate through the array and use the lambda expression to find even numbers
for (int num : inputArray) {
if ([Link](num)) {
[Link](num);
}
}
}
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 {
import [Link].*;
public class Main {
public static void main(String[] args) {
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: ");
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];
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: ");
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]();
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]();
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]();
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);
}
}
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: