0% found this document useful (0 votes)
6 views

22CS202 JAVA PROGG ANSKEY FIAT SIAT ME ESE 2022-2023

The document provides a comprehensive overview of Java programming concepts, including data types, access specifiers, constructors, arrays, and exception handling. It also covers advanced topics like threads, inter-thread communication, and I/O streams, along with examples and explanations. Additionally, it discusses the structure of Java programs, the use of the final and super keywords, and the implementation of interfaces and abstract classes.

Uploaded by

240944.EA
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)
6 views

22CS202 JAVA PROGG ANSKEY FIAT SIAT ME ESE 2022-2023

The document provides a comprehensive overview of Java programming concepts, including data types, access specifiers, constructors, arrays, and exception handling. It also covers advanced topics like threads, inter-thread communication, and I/O streams, along with examples and explanations. Additionally, it discusses the structure of Java programs, the use of the final and super keywords, and the implementation of interfaces and abstract classes.

Uploaded by

240944.EA
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
You are on page 1/ 33

FIAT JAVA PROGRAMMING ANSWER KEY

PART - A
1. List the pros and cons of java
Pros: Platform Independence, Object-Oriented Programming (OOP)
Cons: Performance, Verbosity
2. define data type, decln of variables in java
Data Types in Java:
1. Primitive Data Types:
 Java has primitive data types such as int, double, char, boolean, etc., which represent basic values like integers, floating-point
numbers, characters, and boolean values.
2. Reference Data Types:
 Java also supports reference data types, which include objects, arrays, and user-defined types created using classes.
Variables in Java:
1. Variable Declaration:
 In Java, variables must be declared before use, specifying the data type. For example, int count; declares an integer variable named
count.
2. Variable Initialization:
 Variables can be initialized (assigned a value) at the time of declaration or later in the code. For example, int age = 25; declares and
initializes an integer variable.
3. Constants:
 Constants are declared using the final keyword, indicating that their values cannot be changed once assigned.

3. list the access specifier in java


In Java, there are four main access specifiers:
1. public:
 Allows the member to be accessed from any other class.
2. private:
 Restricts access to the member within the declaring class.
3. protected:
 Allows access within the same package and by subclasses, regardless of the package.
4. Default (Package-Private):
 If no access specifier is specified, it is package-private, allowing access within the same package.

4. constructor with eg
Constructor in Java for 2 Marks:
1. Definition:
 A constructor is a special method in a Java class that has the same name as the class and is used to initialize the object of that class.
2. Purpose:
 The main purpose of a constructor is to initialize the instance variables of an object when it is created. It is automatically called when
an object is instantiated using the new keyword.

5. one dimnl array in java


A one-dimensional array in Java is a collection of elements of the same data type arranged in a linear sequence. It is declared using square brackets ([] ).
6. super keyword in java
The super keyword in Java is a reference variable used to refer to the immediate parent class object. It is primarily used to call the methods, fields, and
constructors of the parent class.
7. abstract class, cases of abstract class
An abstract class in Java is a class that cannot be instantiated on its own and may contain abstract methods. Abstract methods are declared but have no
implementation in the abstract class. It serves as a blueprint for other classes.
8. java does not support multiple inheritance
In Java, a class can extend only one class (single inheritance). This is done to avoid the "diamond problem," where conflicts may arise if a class inherits from
two classes with conflicting methods or attributes. To achieve multiple inheritance-like behavior, Java supports interfaces, allowing a class to implement
multiple interfaces.
9. relationship between class and interface
In Java, a class is a blueprint for creating objects, and an interface is a collection of abstract methods. The relationship between a class and an interface is
established through implementation.
10. package in java
A package in Java is a way to organize related classes and interfaces into a single namespace. It helps in avoiding naming conflicts and provides a
hierarchical structure to manage and categorize classes.
PART B
11.a. structure of java program
structure consists of the following elements:
1. Package Declaration (Optional):
 Defines the package to which the class belongs. It helps in organizing and categorizing classes.
2. Import Statements:
 Allows you to import classes or entire packages from the Java API or other user-defined packages.
3. Class Declaration:
 Declares the class using the class keyword. The class name should match the filename (excluding the ".java" extension).
4. Main Method:
 The main method is the entry point of the program. Execution begins from here. It has a specific signature: public static void
main(String[] args).
5. Variable Declarations:
 Declare variables that will be used in the program. Variables can be of various data types.
6. Object Instantiation:
 Create instances of classes using the new keyword. Objects are often created within the main method.
7. Program Logic:
 The main body of the program where the logic and operations are defined. This includes reading input, performing calculations, and
displaying output.
8. Closing Resources:
 If resources like files or scanners are used, it's good practice to close them to free up system resources.
9. Additional Method Definitions (Optional):
 Define additional methods as needed for modularizing and organizing the code.
10. Closing Brace:
 Close the braces for the class declaration.
This basic structure provides a framework for writing Java programs. Depending on the complexity of the program, additional features like class inheritance,
interfaces, and more elaborate logic may be included.

11.b.array concepts in java


1. Declaration and Initialization:
 Declare an array with a specific data type and initialize it with values.
2. Accessing Elements:
 Access elements in an array using index notation (starting from 0).
3. Array Length:
 Retrieve the length of an array using the length property.
4. Iterating Through an Array:
 Use loops (for, enhanced for, or while) to iterate through array elements.
5. Multidimensional Arrays:
 Declare and initialize multidimensional arrays (arrays of arrays).
6. Array Copy:
 Copy elements from one array to another using System.arraycopy() or Arrays.copyOf().
7. Array Sorting:
 Sort array elements using the Arrays.sort() method.

12.a. static field and method, with example.


Static field with example 7 marks
Static method with example 6 marks
12.b. to find the factorial of N numbers.
Factorial of N numbers in java with explanation – 13 marks
13.a. final keyword with eg.
Concept of final keyword - 3 marks
Example program with explanation – 10 marks
13.b.to implement super keyword
Concept of super keyword – 3 marks
Super keyword example -10 marks
14.a. number from command line, sq.root of a no.
Command line concept – 3 marks
Square root of a number using command line with eg – 10 marks
14.b.extending interface in java
Interface concepts in java – 3 marks
Extend interface with example program – 10 marks
15.a. various operators in java with ex.
List out All the 7 operators in java – 4 marks
with one single example program – 9 marks
15.b.benefits of exceptionhandling in java
Exception handling concept – 2 marks
Benefits of exception handing – 2 marks
Example program with output – 9 marks
PART C
16.a. product of two matrices
Product Matrices – concept -5 marks
Example program with output – 10 marks
16.b. abstract class shape from which triangle and rectangle
are derived, shape class should contain the abstract method area(), create appropriate object, methods and pring
derived class concepts – 3 marks
example program of shape, triangle, rectangle – 12 marks
the area of the triangle and rectangle
In this example, Shape is an abstract class with an abstract method calculateArea() . The concrete subclass Circle extends Shape
and provides an implementation for the abstract method. Objects are created from the concrete subclass, not the abstract class.
// Abstract class
abstract class Shape {
int sides;

// Abstract method declaration


abstract void calculateArea();

// Non-abstract method with implementation


void displaySides() {
System.out.println("Number of sides: " + sides);
}
}

// Concrete subclass
class Circle extends Shape {
double radius;

Circle(double radius) {
this.radius = radius;
sides = 1;
}

// Implementation of the abstract method


void calculateArea() {
double area = Math.PI * radius * radius;
System.out.println("Area of the circle: " + area);
}
}

public class Example {


public static void main(String[] args) {
Circle myCircle = new Circle(5.0);
myCircle.displaySides();
myCircle.calculateArea();
}
}
II INTERNAL ASSESSMENT
JAVA PROGRAMMING
ACADEMIC YEAR 2022-2023 - EVEN SEM

PART A
1. states of a thread
RUNNABLE:
● A thread in the RUNNABLE state is ready to run and is waiting for the
scheduler to allocate processor time.
BLOCKED:
● A thread in the BLOCKED state is waiting for a monitor lock to enter
or reenter a synchronized block or method.
These states represent two key scenarios in the life cycle of a thread: one
where it is actively running or ready to run, and another where it is
temporarily unable to proceed due to synchronization constraints.

2. note on notify()
In Java, notify() is a method provided by the Object class, and it is used in
the context of inter-thread communication through the use of monitors
(synchronized blocks or methods).

3. four subclass of input and output stream classes


In Java, the InputStream and OutputStream classes are part of the I/O
(Input/Output) stream hierarchy. There are several subclasses for handling
different types of input and output operations.

4 to implement generic class in java


In Java, you can implement a generic class by using the syntax that includes
type parameters. Here are two key points to consider when implementing a
generic class:
Declaration with Type Parameters, Instantiation with Specific Types

5. different ways of constructing string object


In Java, there are several ways to construct a String object:
Using String Literal:
● The most common way to create a String object is by using
string literals. String literals are sequences of characters
enclosed in double quotes.
Using the new Keyword:
● You can use the new keyword along with the String constructor
to create a String object. However, this method is less common
than using string literals.

6. different ways of constructing string object


two different ways of constructing a String object in Java:
Using String Literal:
● The simplest and most common way to create a String object is
by using a string literal, which is a sequence of characters
enclosed in double quotes.
● Using Concatenation Operator (+): You can concatenate
multiple strings using the + operator to create a new String
object.
7. iterator in java collection framework
two key points about iterators in the Java Collection Framework:
Interface:
● The Iterator interface is part of the Java Collections Framework and is
used to traverse elements in a collection.
● It provides methods such as hasNext() to check if there are more
elements, and next() to retrieve the next element in the iteration.
Fail-Fast Behavior:
● Iterators exhibit fail-fast behavior, meaning that if the collection is modified
while an iterator is traversing it (except through the iterator's own remove
method), a ConcurrentModificationException is thrown.

8. vector in java
two key points about the Vector class in Java:
Dynamic Array Implementation:
● Vector is a part of the Java Collections Framework and implements a
dynamic array, similar to an array but can dynamically resize itself to
accommodate more elements.
Legacy Class:
● Vector is considered a legacy class because it was part of the original version
of the Java Collections Framework introduced in Java 1.0.

9. different ways to iterator over list


Here are two different ways to iterate over a List in Java:
Using Iterator:
● You can use the Iterator interface to iterate over elements in a List.
The Iterator provides methods like hasNext() and next() for
sequential access to the elements.
Using Enhanced for Loop (for-each loop):
● Java provides a concise way to iterate over a List using the enhanced for
loop, also known as the for-each loop.

10. two classes which support regular expression


Two classes in Java that support regular expressions are:
Pattern class:
● The Pattern class is part of the java.util.regex package and
represents a compiled regular expression pattern.
Matcher class:
● The Matcher class, also part of the java.util.regex package, is used to
perform match operations on a character sequence (typically a string) based
on a compiled pattern.
PART B
11a different states of a thread and thread prioritites
Threads in Java go through various states during their lifecycle, and they can be
assigned different priorities for execution. Here's an overview of both the thread
states and thread priorities:
Thread States:
NEW:
● A thread is in the NEW state when it is created but has not yet started.
It is in this state before the start() method is invoked.
RUNNABLE:
● A thread is in the RUNNABLE state when it is ready to run, but it may
not be currently executing due to the thread scheduler.
BLOCKED:
● A thread is in the BLOCKED state when it is waiting for a monitor lock
to enter a synchronized block or method. This happens when another
thread holds the lock.
WAITING:
● A thread is in the WAITING state when it is waiting indefinitely for
another thread to perform a particular action. This state can be
entered, for example, by calling Object.wait().
TIMED_WAITING:
● A thread is in the TIMED_WAITING state when it is waiting for another
thread to perform a particular action for a specified amount of time.
This state can be entered, for example, by calling Thread.sleep().
TERMINATED:
● A thread is in the TERMINATED state when it has exited. This happens
when the run() method completes or when the stop() method is
explicitly called.
Thread Priorities:
Java supports thread priorities, where each thread is assigned a priority that
influences its order of execution. Thread priorities are specified as integers ranging
from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10), with
Thread.NORM_PRIORITY (5) being the default.
MAX_PRIORITY (10):
● Threads with maximum priority are scheduled to run before those with
lower priorities. It represents the highest priority.
NORM_PRIORITY (5):
● This is the default priority. Threads with normal priority are scheduled
in a balanced manner with respect to other threads.
MIN_PRIORITY (1):
● Threads with minimum priority are scheduled to run only when no
higher priority threads are runnable.
Thread priorities are used as hints for the thread scheduler, and the actual behavior
might vary between different operating systems and Java Virtual Machine (JVM)
implementations. It's important to note that thread priorities should be used
judiciously, as they don't guarantee precise control over the order of thread
execution.

11b interthread communication with example


example of interthread communication in Java using the classic producer-consumer
problem. In this scenario, one thread (producer) produces data, and another thread
(consumer) consumes the data. The wait(), notify(), and notifyAll() methods are
used for synchronization and communication between the threads.
example
class SharedResource {
private int data;
private boolean dataProduced = false;

public synchronized void produce(int newData) {


// Wait until data is consumed
while (dataProduced) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

// Produce new data


data = newData;
System.out.println("Produced: " + data);

// Notify the consumer that data is available


dataProduced = true;
notify();
}

public synchronized int consume() {


// Wait until data is produced
while (!dataProduced) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

// Consume the data


System.out.println("Consumed: " + data);

// Notify the producer that data has been consumed


dataProduced = false;
notify();

return data;
}
}

class Producer implements Runnable {


private SharedResource sharedResource;

public Producer(SharedResource sharedResource) {


this.sharedResource = sharedResource;
}

@Override
public void run() {
for (int i = 0; i < 5; i++) {
sharedResource.produce(i);
}
}
}

class Consumer implements Runnable {


private SharedResource sharedResource;

public Consumer(SharedResource sharedResource) {


this.sharedResource = sharedResource;
}

@Override
public void run() {
for (int i = 0; i < 5; i++) {
sharedResource.consume();
}
}
}

public class Main {


public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();

// Create producer and consumer threads


Thread producerThread = new Thread(new Producer(sharedResource));
Thread consumerThread = new Thread(new Consumer(sharedResource));

// Start threads
producerThread.start();
consumerThread.start();
}
}

12a I/O stream created with console stream


Java provides the System class, which has a method called console() that returns the
unique Console object associated with the current Java virtual machine (JVM). The
Console class provides methods for reading and writing to the console, making it
useful for creating I/O streams with console input and output. Here's an example
demonstrating I/O streams created with the console stream:
import java.io.Console;

public class ConsoleExample {


public static void main(String[] args) {
// Obtain the Console object
Console console = System.console();

if (console == null) {
System.out.println("Console is not available on this platform.");
System.exit(1);
}

// Reading input from the console


String inputLine = console.readLine("Enter a line of text: ");
System.out.println("You entered: " + inputLine);

// Reading sensitive information (e.g., password) without echoing to the console


char[] passwordArray = console.readPassword("Enter your password: ");
String password = new String(passwordArray);

// Writing output to the console


console.writer().println("Output to the console.");

// Closing the console (optional)


console.flush();

// Note: Closing the console is optional because it is automatically closed when


the JVM terminates.
}
}

12b usage of file reader and writer class


The FileReader and FileWriter classes in Java are used for reading and writing
character data, respectively, from and to files. Here's an example demonstrating the
usage of FileReader and FileWriter:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReadWriteExample {


public static void main(String[] args) {
// Specify the file path
String filePath = "example.txt";

// Writing to a file using FileWriter


try (FileWriter fileWriter = new FileWriter(filePath)) {
String dataToWrite = "Hello, FileWriter!";
fileWriter.write(dataToWrite);
System.out.println("Data written to the file.");
} catch (IOException e) {
e.printStackTrace();
}

// Reading from a file using FileReader


try (FileReader fileReader = new FileReader(filePath)) {
int charCode;
StringBuilder content = new StringBuilder();

while ((charCode = fileReader.read()) != -1) {


content.append((char) charCode);
}

System.out.println("Data read from the file: " + content.toString());


} catch (IOException e) {
e.printStackTrace();
}
}
}

13a lambda expression with no parameter and single parameter


Lambda expressions in Java provide a concise way to express instances of single-
method interfaces (functional interfaces). Lambda expressions can be used when an
interface has only one abstract method, making them ideal for simplifying code,
especially in scenarios involving functional programming. Below are examples of
lambda expressions with no parameters and with a single parameter:
Lambda Expression with No Parameters:
// Functional interface with no parameters
interface NoParameterInterface {
void printMessage();
}

public class NoParameterLambdaExample {


public static void main(String[] args) {
// Using a lambda expression to implement the interface
NoParameterInterface noParameterLambda = () -> {
System.out.println("Hello, Lambda!");
};

// Calling the method defined in the lambda expression


noParameterLambda.printMessage();
}
}

Lambda Expression with Single Parameter:


// Functional interface with a single parameter
interface SingleParameterInterface {
void printMessage(String message);
}

public class SingleParameterLambdaExample {


public static void main(String[] args) {
// Using a lambda expression to implement the interface
SingleParameterInterface singleParameterLambda = (message) -> {
System.out.println("Message: " + message);
};

// Calling the method defined in the lambda expression


singleParameterLambda.printMessage("Lambda is awesome!");
}
}

13b string handling methods in java


String handling in Java involves various methods provided by the String class, which
is part of the Java Standard Library. Below are eight commonly used string handling
methods in Java
any 8 methods with explanation, example and output

14a methods declared in collection interface


The Collection interface in Java is a part of the Java Collections Framework and
serves as the root interface for all the collection types. It declares several methods
that are common to all collections, providing a unified interface for working with
different types of collections. Below are eight commonly used methods declared in
the Collection interface:
Below methods with explanation, example and output
boolean add(E element):
boolean remove(Object element)
boolean contains(Object element)
int size():
boolean isEmpty():
void clear():
Object[] toArray() and <T> T[] toArray(T[] array):

14b max. and min. element in an array list


To find the maximum and minimum elements in an ArrayList in Java, you can use
the Collections utility class, which provides methods for working with collections.
Here's an example:
import java.util.ArrayList;
import java.util.Collections;

public class MaxMinArrayListExample {


public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(5);
numbers.add(8);
numbers.add(15);
numbers.add(3);

// Find the maximum element


Integer maxElement = Collections.max(numbers);
System.out.println("Maximum Element: " + maxElement);

// Find the minimum element


Integer minElement = Collections.min(numbers);
System.out.println("Minimum Element: " + minElement);
}
}

15a generic method to print array of data belongs to any class type,
analyse generic working with primitive data types
example of a generic method that can print an array of data belonging to any class
type:
public class GenericArrayPrinter {

public static <T> void printArray(T[] array) {


for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}

public static void main(String[] args) {


// Example with Integer array
Integer[] intArray = {1, 2, 3, 4, 5};
System.out.print("Integer Array: ");
printArray(intArray);
// Example with String array
String[] strArray = {"apple", "banana", "orange"};
System.out.print("String Array: ");
printArray(strArray);

// Example with Double array


Double[] doubleArray = {1.5, 2.5, 3.5, 4.5};
System.out.print("Double Array: ");
printArray(doubleArray);
}
}

If performance is a critical concern, and you are working extensively with primitive
types, consider alternative solutions such as using specialized libraries like Apache
Commons Lang's ArrayUtils.toObject() and ArrayUtils.toPrimitive() methods.
These methods can help bridge the gap between generics and primitive arrays.

15b iterator in java


eight key points about iterators in Java:

Interface:
● Iterator is an interface in the java.util package that provides a way to
iterate over a collection of objects, such as a List, Set, or Map.
Methods:
● The Iterator interface declares three main methods:
● boolean hasNext(): Returns true if the iteration has more
elements.
● E next(): Returns the next element in the iteration.
● void remove(): Removes the last element returned by next
from the underlying collection.
Fail-Fast Behavior:
● Iterators exhibit fail-fast behavior, meaning that if the underlying
collection is modified after the iterator is created, other than by the
iterator's own remove method, a ConcurrentModificationException
is thrown.
ListIterator:
● The ListIterator is a subinterface of Iterator that allows bidirectional
traversal of a List and enables the modification of elements during
iteration.
Enhanced for Loop (for-each loop):
● The enhanced for loop introduced in Java 5 provides a concise way to
iterate over collections without explicitly using an Iterator.
Iterable Interface:
● The Iterable interface, implemented by collection classes, provides
an iterator() method that returns an Iterator for the collection.
Java Streams:
● Java 8 introduced the Stream API, which allows for functional-style
processing of collections. While not a direct replacement for iterators,
streams provide powerful operations like filter, map, and reduce for
processing elements.
In summary, iterators in Java provide a standardized way to traverse elements in
various types of collections, offering a consistent interface for iterating over
elements in a forward direction. The fail-fast behavior ensures that the iterator
reflects the state of the collection at the time of its creation and helps prevent
concurrent modification issues.
PART C
16a inventory application in multithread
Creating a multithreaded inventory application involves managing multiple threads to
handle various aspects of the inventory, such as adding items, removing items,
updating quantities, and handling concurrent access. Below is a simplified example
of an inventory application with multithreading in Java.
import java.util.HashMap;
import java.util.Map;

class Inventory {
private Map<String, Integer> items;

public Inventory() {
this.items = new HashMap<>();
}

public synchronized void addItem(String itemName, int quantity) {


if (items.containsKey(itemName)) {
int currentQuantity = items.get(itemName);
items.put(itemName, currentQuantity + quantity);
} else {
items.put(itemName, quantity);
}
System.out.println(Thread.currentThread().getName() + " added " + quantity + " "
+ itemName);
}

public synchronized void removeItem(String itemName, int quantity) {


if (items.containsKey(itemName)) {
int currentQuantity = items.get(itemName);
if (currentQuantity >= quantity) {
items.put(itemName, currentQuantity - quantity);
System.out.println(Thread.currentThread().getName() + " removed " +
quantity + " " + itemName);
} else {
System.out.println(Thread.currentThread().getName() + " cannot remove " +
quantity + " " + itemName
+ ". Insufficient quantity.");
}
} else {
System.out.println(Thread.currentThread().getName() + " cannot remove " +
quantity + " " + itemName
+ ". Item not found.");
}
}

public synchronized void displayInventory() {


System.out.println("Inventory:");
for (Map.Entry<String, Integer> entry : items.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
class InventoryManager implements Runnable {
private Inventory inventory;

public InventoryManager(Inventory inventory) {


this.inventory = inventory;
}

@Override
public void run() {
for (int i = 0; i < 5; i++) {
inventory.addItem("Item" + i, 10);
}

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


inventory.removeItem("Item" + i, 5);
}

inventory.displayInventory();
}
}

public class MultithreadedInventoryExample {


public static void main(String[] args) {
Inventory inventory = new Inventory();

// Create multiple threads managing the inventory


Thread manager1 = new Thread(new InventoryManager(inventory), "Manager
1");
Thread manager2 = new Thread(new InventoryManager(inventory), "Manager
2");

// Start the threads


manager1.start();
manager2.start();
}
}

Explanation:
The Inventory class represents the inventory with methods for adding,
removing, and displaying items. Methods are synchronized to handle
concurrent access.
The InventoryManager class is a Runnable implementation that simulates
inventory management operations by adding and removing items.
In the MultithreadedInventoryExample class, two threads (Manager 1 and
Manager 2) are created, each managing the inventory concurrently.
Thread safety is ensured by synchronizing the critical sections of code in the
Inventory class, preventing race conditions during inventory updates.
The output demonstrates the concurrent execution of multiple inventory
managers, adding and removing items from the inventory.
16b to obtain a string and a string is a palindrome or not
Creating a program to determine whether a given string is a palindrome or not
involves comparing the characters from the beginning to the end and vice versa.
Here's a simple Java program with eight key points to achieve this:
import java.util.Scanner;

public class PalindromeChecker {

public static boolean isPalindrome(String str) {


// Remove non-alphanumeric characters and convert to lowercase
String cleanedStr = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

int length = cleanedStr.length();


for (int i = 0; i < length / 2; i++) {
if (cleanedStr.charAt(i) != cleanedStr.charAt(length - i - 1)) {
return false; // Not a palindrome
}
}
return true; // Palindrome
}
public static void main(String[] args) {
// Input from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

// Check if the input string is a palindrome


boolean result = isPalindrome(inputString);

// Display the result


if (result) {
System.out.println("The entered string is a palindrome.");
} else {
System.out.println("The entered string is not a palindrome.");
} }}
Explanation:
isPalindrome Method:
● The isPalindrome method takes a string as input and checks whether it is a
palindrome.
● The program uses Scanner to obtain a string from the user.
Removing Non-Alphanumeric Characters:
● The replaceAll("[^a-zA-Z0-9]", "") removes non-alphanumeric
characters from the input string.
Case Insensitivity:
● The string is converted to lowercase to perform a case-insensitive
comparison.
Loop for Comparison:
● The loop compares characters from the beginning to the end and vice versa.
Result Display:
● The program displays whether the entered string is a palindrome or not.
Example Usage:
● The user is prompted to enter a string.
● For example, entering "A man, a plan, a canal, Panama!" would be recognized
as a palindrome.
Code Encapsulation:
● The palindrome-checking logic is encapsulated in a separate method
(isPalindrome), promoting code modularity and readability.
This program provides a simple way to determine whether a given string is a palindrome or
not. It can be extended for more sophisticated palindrome checks based on specific
requirements.
MODEL EXAM JAVA PROGRAMMING ANSWER KEY
PART - A
1. list java tokens in detail
Keywords, identifiers, literals, operators, punctuation, separators, comments, whitespaces
2. char. Of static members of a class
Static fields in a class are declared using the static keyword. They belong to the class rather than
instances of the class. There is only one copy of a static field shared among all instances of the
class
Static methods are also declared with the static keyword. They operate at the class level and can
be called using the class name, not requiring an instance of the class. Static methods cannot
access instance-specific variables directly.
3. abstract class with example
An abstract class in Java is a class that cannot be instantiated on its own and may contain abstract
methods. Abstract methods are declared but have no implementation in the abstract class. It
serves as a blueprint for other classes.
Example program
4. char. of interface in java
An interface in Java is a collection of abstract methods (methods without a body) and constants. It
provides a way to achieve abstraction by defining a contract that concrete classes must adhere to.
Key Points:
Interfaces are declared using the interface keyword.

5. life cycle of thread


Thread Lifecycle in Java for 2 Marks:
New State:
Runnable State:
Blocked/Waiting State:
Timed Waiting State:
Terminated/Dead State:
6. byte and char stream
Byte Stream:
Byte streams in Java handle I/O operations on raw binary data. They deal with the data as a
stream of bytes. Examples of byte stream classes include FileInputStream and FileOutputStream.
Byte streams are suitable for handling all kinds of binary data, such as images or non-text files.
Character Stream:
Character streams in Java handle I/O operations on characters. They are specifically designed
for handling text data. Examples of character stream classes include FileReader and FileWriter.
Character streams automatically handle character encoding and decoding, making them
suitable for reading and writing text files

7. vector in java
In Java, a Vector is a part of the Java Collections Framework and is a dynamic array-like data
structure. It is synchronized, meaning it is thread-safe, and its methods are synchronized, making
it suitable for scenarios where multiple threads may access it concurrently.
8. common exceptions raised by various collections.
common exceptions can be raised when working with collections in Java. Here are some of them:
NullPointerException:
Raised when attempting to perform an operation on a null object reference, such as calling a
method on a null list.
IndexOutOfBoundsException:
Raised when trying to access an element at an index that is outside the valid range for a
collection, like an index less than zero or greater than or equal to the size of the collection.
9. JDBC Driver Manager.
DriverManagerin Java is a class in the JDBC (Java Database Connectivity) API that manages a list of
database drivers. It acts as a connection factory, providing methods to establish database
connections.
10. adv. Disadv. of JDBC-ODBC bridge driver.
Advantages:
Platform Independence:
One of the primary advantages of the JDBC-ODBC Bridge is that it provides a way to connect
Java applications to databases using the ODBC (Open Database Connectivity) standard. This
allows for some level of platform independence, as ODBC drivers are available for various
operating systems.
Ease of Use:
The JDBC-ODBC Bridge is relatively easy to set up and use, especially for developers familiar
with ODBC. It allows Java applications to leverage existing ODBC drivers to connect to a wide
range of databases without the need for a specific database driver for each database.
Disadvantages:
Performance Overhead:
One significant drawback of the JDBC-ODBC Bridge is its performance overhead. The bridge
converts JDBC calls into ODBC calls, resulting in an additional layer of abstraction. This can
introduce latency and affect the overall performance of database operations.
Dependence on ODBC:
The JDBC-ODBC Bridge relies on the presence of ODBC drivers, which may not be available or
well-maintained for all database systems. This introduces a dependency on the ODBC
standard and might limit the portability of Java applications across different database
environments.
Understanding these advantages and disadvantages is essential when deciding whether to use
the JDBC-ODBC Bridge or opt for a more direct JDBC driver, such as a Type 4 driver, for better
performance and independence from ODBC.

PART B
11. a. array declarations in java
Concept of array, array declaration - 3 marks
With example program - 10 marks
12. b. control statements in java
List out all the control statements in java - 4 marks
With example program - 9 marks
13. a. different types of inheritance in java, with eg.
List out types of inheritance - 4 marks
Example program with explanation - 9 makrs
12. b. accept no from command line and pring sq root of a number
Command line concept - 3 marks
Example program for sq. Root of a number - 10 makrs
13. a. generic program to read two data items of diff data types and display
Generic program concept - 3 marks
Example program for different data types int, float with explanation - 10 marks
14. b. reading input from user in command line using buffered reader class and Scanner class
Command line with buffer reader, scanner class - 3 makrs
Example program with output - 10 marks
15. a. lambda expression with or without parameters
Concept of lamda express with/without param - 3 marks
Example program to exaplin the concept - 10 marks
14. b. hierarchy of collection framework
Collection framework hiearachy - 3 makrs
Example program with output - 10 marks
15. a. print all student names starting with A using PreparedStatement interface.
Prepared statement interface - concept - 3 marks
Example progam with output - 10 marks
16. b. jdbc result sets.
Example program with out jdbc result sets - 13 marks
PART C
16.a. generate EB Bill using java for following tariff
First 150 units – Rs. 2 per unit
151-250 units – Rs. 7 per unit
251-1000 units – Rs. 9 per unit
> 1001 units – Rs. 14 per unit
To generate an electricity bill (EB Bill) in Java based on the provided tariff, you can create a simple
program. Here's a sample Java program that takes the number of units consumed as input and
calculates the bill amount based on the specified tariff:
import java.util.Scanner;

public class ElectricityBillGenerator {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input: Number of units consumed


System.out.print("Enter the number of units consumed: ");
int unitsConsumed = scanner.nextInt();

// Calculate the bill amount based on tariff


double billAmount = calculateBill(unitsConsumed);

// Output: Display the calculated bill amount


System.out.println("Electricity Bill Amount: Rs. " + billAmount);

// Close the scanner


scanner.close();
}

// Method to calculate the bill amount based on the tariff


private static double calculateBill(int unitsConsumed) {
double billAmount = 0;

// First 150 units - Rs. 2 per unit


if (unitsConsumed <= 150) {
billAmount = unitsConsumed * 2;
}
// 151-250 units - Rs. 7 per unit
else if (unitsConsumed <= 250) {
billAmount = 150 * 2 + (unitsConsumed - 150) * 7;
}
// 251-1000 units - Rs. 9 per unit
else if (unitsConsumed <= 1000) {
billAmount = 150 * 2 + 100 * 7 + (unitsConsumed - 250) * 9;
}
// > 1001 units - Rs. 14 per unit
else {
billAmount = 150 * 2 + 100 * 7 + 750 * 9 + (unitsConsumed - 1000) * 14;
}

return billAmount;
}
}
This program defines a method calculateBill that takes the number of units consumed as a
parameter and calculates the bill amount based on the specified tariff. The main method takes
user input for the number of units consumed, calls the calculateBill method, and then displays the
calculated bill amount.

16.b. to obtain the string, substring, and the string that has to replace
the substring and print the modified string
first line – string, second line-substring and third line-to replace the substring
input – audacious cio aaa
output - audaaaaus
If you want to obtain a string, a substring, and the replacement string to modify the original string
in Java, you can use the Scanner class to take user input. Here's a simple example:
import java.util.Scanner;
public class StringReplacementExample {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input: Original string


System.out.print("Enter the original string: ");
String originalString = scanner.nextLine();

// Input: Substring to be replaced


System.out.print("Enter the substring to replace: ");
String substringToReplace = scanner.nextLine();

// Input: Replacement string


System.out.print("Enter the replacement string: ");
String replacementString = scanner.nextLine();

// Perform the replacement


String modifiedString = replaceSubstring(originalString, substringToReplace, replacementString);

// Output: Display the modified string


System.out.println("Modified String: " + modifiedString);

// Close the scanner


scanner.close();
}

// Method to replace a substring in the original string


private static String replaceSubstring(String original, String substring, String replacement) {
return original.replace(substring, replacement);
}
}
In this program, the replaceSubstring method from the String class is used to replace the specified
substring with the replacement string. The Scanner class is used to take user input for the original
string, the substring to replace, and the replacement string. The modified string is then printed.
Output:
Enter the original string: Hello, world! Hello, Java!
Enter the substring to replace: Hello
Enter the replacement string: Hi
Modified String: Hi, world! Hi, Java!
ANSWER KEY
B.E. / B.TECH. END SEMESTER THEORY EXAMINATIONS – APRIL/MAY-2023
Second Semester
Computer Science and Engineering/Electronics and Communication Engineering/
Information Technology/Artificial Intelligence and Machine Learning/
Computer Science and Business Systems
22CS202 – Java Programming (Lab Integrated)
(Regulations 2022)
COs Course Outcome: The students, after the completion of the course, are expected to ….
CO1 Understand the object oriented programming concepts and fundamentals of Java.
CO2 Develop Java programs with the packages, interfaces and exceptions.
CO3 Build Java applications with I/O streams, threads and generics programming.
CO4 Apply strings and collections in developing applications.
CO5 Implement the concept of JDBC
CO6 Apply strings and collections in developing applications.
Time: 3 Hours Answer ALL Questions Max. Marks: 100
Part-A (10 x 2 = 20 Marks)
1. Is Java a pure object-oriented programming language? Justify.

Java is not a pure object oriented programming language. Because it contains the following
properties.
A. Primitive data type 2. Wrapper class 3. The static keyword.
2. If ObjA1 is an object of class A created using new keyword, what does the statement A
ObjA2=ObjA1; mean?
The = operator does not copy values from one object to another. Instead, it makes both
variables refer to the same object.

3. What is the benefit of using final in inheritance?

Final is a keyword in java used for restricting some functionality. Final can be used to
restrict inheritance.
4. What are built in exceptions?

Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
5. How a thread differs from a process?

A process is an instance of a program that is being executed or processed. Thread is a segment


of a process or a lightweight process that is managed by the scheduler independently.
Processes are independent of each other and hence don't share a memory or other resources.
Threads are interdependent and share memory.
6. Write a method used for reading a numerical value.
1. nextInt() 2. nextDouble() 3.nextFloat() 4. nextLong()

7. What is the use of a map?

Java maps are used for many different functions and operations, but in short, they are a way to
keep track of information in the form of key-value pairs. In Java, a map can consist of virtually
any number of key-value pairs, but the keys must always be unique — non-repeating.
8. Mention the need for collections.

A framework is a set of classes and interfaces which provide a ready-made architecture. In


order to implement a new feature or a class, there is no need to define a framework.
However, an optimal object-oriented design always includes a framework with a collection
of classes such that all the classes perform the same kind of task.

9. What is a prepared statement?

A prepared statement is a feature used to execute the same (or similar) SQL statements
repeatedly with high efficiency.

Prepared statements basically work like this:

1. Prepare: An SQL statement template is created and sent to the database. Certain values
are left unspecified, called parameters (labeled "?"). Example: INSERT INTO
MyGuests VALUES(?, ?, ?)
2. The database parses, compiles, and performs query optimization on the SQL statement
template, and stores the result without executing it
3. Execute: At a later time, the application binds the values to the parameters, and the
database executes the statement. The application may execute the statement as many
times as it wants with different values

10. Mention any two advantages of embedded sql.

• Helps to access databases from anywhere.


• Allows integrating authentication service for large scale applications.
• Provides extra security to database transactions.
• Avoids logical errors while performing transactions on our database.
• Makes it easy to integrate the frontend and the backend of our application.

Part – B (5 x 13 = 65 Marks)
11.a. Create a class employee with data members employee ID, employee name,
designation and salary. Write methods get employee ()- To take user input,
show Grade ()- to display grade of employee based on salary, show_employee () to
display employee details.

[Award marks if students write their program with a different logic]

import java.util.Scanner;

public class Employee {

int empid;
String name;
float salary;

public void getInput() {


Scanner in = new Scanner(System.in);
System.out.print("Enter the empid :: ");
empid = in.nextInt();
System.out.print("Enter the name :: ");
name = in.next();
System.out.print("Enter the salary :: ");
salary = in.nextFloat();
}

public void display() {

System.out.println("Employee id = " + empid);


System.out.println("Employee name = " + name);
System.out.println("Employee salary = " + salary);
}

public static void main(String[] args) {

Employee e[] = new Employee[5];

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

e[i] = new Employee();


e[i].getInput();
}

System.out.println("**** Data Entered as below ****");

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

e[i].display();
}
}
}

Or
11.b. What are various data types in java? Explain them in detail?

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
Java is a statically-typed programming language. It means, all variables must be declared
before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

1. boolean data type


2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type

12.a. Write a program to generate student mark sheet using multi-level inheritance.

[Award marks if students write their program with a different logic]

interface Exam {

void Percent_cal();
}

class Student {

String name;
int roll_no, Marks1, Marks2;
Student(String n, int rn, int m1, int m2) {
name = n;
roll_no = rn;
Marks1 = m1;
Marks2 = m2;
}

void show() {
System.out.println("Student Name : "+name);
System.out.println("Roll no : "+roll_no);
System.out.println("Marks1 : "+Marks1);
System.out.println("Marks2 : "+Marks2);
}
}

class Result extends Student implements Exam {


float per;
Result(String n,int rn,int m1,int m2) {
super(n,rn,m1,m2);
}
public void Percent_cal() {
int tot = Marks1 + Marks2;
per = (float)tot / 2;
}
void display() {
show();
System.out.println("Percentage = "+per);
}
}
public class StudentDetails {

public static void main (String[] args) {

Result r = new Result("Aashish",11,75,95);


r.Percent_cal();
r.display();
}
}

Or
12.b. Discuss the importance of final modifier in inheritance.

Using final to Prevent Inheritance

When a class is declared as final then it cannot be subclassed i.e. no other class can extend it.
This is particularly useful, for example, when creating an immutable class like the
predefined String class. The following fragment illustrates the final keyword with a class:

final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
Note :

• Declaring a class as final implicitly declares all of its methods as final, too.
• It is illegal to declare a class as both abstract and final since an abstract class is
incomplete by itself and relies upon its subclasses to provide complete implementations.
For more on abstract classes, refer abstract classes in java

Using final to Prevent Overriding

When a method is declared as final then it cannot be overridden by subclasses.


The Object class does this—a number of its methods are final. The following fragment
illustrates the final keyword with a method:

class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}
Normally, Java resolves calls to methods dynamically, at run time. This is called late or
dynamic binding. However, since final methods cannot be overridden, a call to one can be
resolved at compile time. This is called early or static binding.

13.a. Explain thread synchronization with examples.

Java Synchronization is used to make sure by some synchronization method that only one
thread can access the resource at a given point in time.

Java Synchronized Blocks

Java provides a way of creating threads and synchronizing their tasks using synchronized
blocks.
A synchronized block in Java is synchronized on some object. All synchronized blocks
synchronize on the same object and can only have one thread executed inside them at a time.
All other threads attempting to enter the synchronized block are blocked until the thread
inside the synchronized block exits the block.

General Form of Synchronized Block

synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}
This synchronization is implemented in Java with a concept called monitors or locks. Only
one thread can own a monitor at a given time. When a thread acquires a lock, it is said to
have entered the monitor. All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor.
Types of Synchronization
There are two synchronizations in Java mentioned below:
1. Process Synchronization
2. Thread Synchronization

1. Process Synchronization in Java

Process Synchronization is a technique used to coordinate the execution of multiple


processes. It ensures that the shared resources are safe and in order.

2. Thread Synchronization in Java

Thread Synchronization is used to coordinate and ordering of the execution of the threads in
a multi-threaded program. There are two types of thread synchronization are mentioned
below:
• Mutual Exclusive
• Cooperation (Inter-thread communication in Java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data.
There are three types of Mutual Exclusive mentioned below:
• Synchronized method.
• Synchronized block.
• Static synchronization.

Or
13.b. Write a Java program for implementing the Runnable Interface.

[Award marks if students write their program with a different logic]

1. Runnable runnable = new MyRunnable();


2. Thread thread = new Thread(runnable);
3. thread.start();

pu Public class ExampleClass implements Runnable {


public void run() {
System.out.println("Thread has ended");
}
public static void main(String[] args) {
ExampleClass ex = new ExampleClass();
Thread t1= new Thread(ex);
t1.start();
System.out.println("Hi"); }}
14.a. Write a Java program to compare two strings ignoring the cases.

[Award marks if students write their program with a different logic]

// Java Program to Illustrate equalsIgnoreCase() method

// Importing required classes


import java.lang.*;

// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Declaring and initializing strings to compare
String str1 = "GeeKS FOr gEEks";
String str2 = "geeKs foR gEEKs";
String str3 = "ksgee orF geeks";

// Comparing strings
// If we ignore the cases
boolean result1 = str2.equalsIgnoreCase(str1);
// Both the strings are equal so display true
System.out.println("str2 is equal to str1 = "
+ result1);
// Even if we ignore the cases
boolean result2 = str2.equalsIgnoreCase(str3);

// Both the strings are not equal so display false


System.out.println("str2 is equal to str3 = "
+ result2);
}
}

Or
14.b. What is the difference between ArrayList and Vector classes in collection framework?
Explain with examples.

• ArrayList is unsynchronized and not thread-safe, whereas Vectors are. Only one thread
can call methods on a Vector, which is slightly overhead but helpful when safety is a
concern. Therefore, in a single-threaded case, ArrayList is the obvious choice, but where
multithreading is concerned, vectors are often preferable.
• If we don’t know how much data we will have but know the rate at which it grows,
Vector has an advantage since we can set the increment value in vectors.
• ArrayList is newer and faster. If we don’t have any explicit requirements for using either
of them, we use ArrayList over vector.

// Java Program to illustrate use


// of ArrayList and Vector in Java

import java.io.*;
import java.util.*;

class GFG
{
public static void main (String[] args)
{
// creating an ArrayList
ArrayList<String> al = new ArrayList<String>();
// adding object to arraylist
al.add("Practice.GeeksforGeeks.org");
al.add("www.GeeksforGeeks.org");
al.add("code.GeeksforGeeks.org");
al.add("contribute.GeeksforGeeks.org");
// traversing elements using Iterator'
System.out.println("ArrayList elements are:");
Iterator it = al.iterator();
while (it.hasNext())
System.out.println(it.next());
// creating Vector
Vector<String> v = new Vector<String>();
v.addElement("Practice");
v.addElement("quiz");
v.addElement("code");
// traversing elements using Enumeration
System.out.println("\nVector elements are:");
Enumeration e = v.elements();
while (e.hasMoreElements())
System.out.println(e.nextElement());
}
}

15.a. Illustrate the procedure to connect database in Java with suitable program.

Steps For Connectivity Between Java Program and Database

1. Import the Packages


2. Load the drivers using the forName() method
3. Register the drivers using DriverManager
4. Establish a connection using the Connection class object
5. Create a statement
6. Execute the query
7. Close the connections

STEPS:
Step 1: Import the Packages
Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register it before using it in the
program. Registration is to be done once in your program. You can register a driver in one of
two ways mentioned below as follows:
2-A Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of using new or
create objects. The following example uses Class.forName() to load the Oracle driver as
shown below as follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2-B DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here we call the
constructor of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connection con = DriverManager.getConnection(url,user,password)
• user: Username from which your SQL command prompt can be accessed.
• password: password from which the SQL command prompt can be accessed.
• con: It is a reference to the Connection interface.
• Url: Uniform Resource Locator which is created as shown below:

String url = “ jdbc:oracle:thin:@localhost:1521:xe”


Where oracle is the database used, thin is the driver used, @localhost is the IP Address
where a database is stored, 1521 is the port number and xe is the service provider. All 3
parameters above are of String type and are to be declared by the programmer before calling
the function. Use of this can be referred to form the final code.
Step 4: Create a statement
Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to
send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();
Step 5: Execute the query
Now comes the most important part i.e executing the query. The query here is an SQL
Query. Now we know we can have multiple types of queries. Some of them are as follows:
• The query for updating/inserting a table in a database.
• The query for retrieving data.

The executeQuery() method of the Statement interface is used to execute queries of


retrieving values from the database. This method returns the object of ResultSet that can be
used to get all the records of a table.

The executeUpdate(sql query) method of the Statement interface is used to execute queries
of updating/inserting.

Pseudo Code:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");

Or
15.b. Write a Java Program to use JDBC connectivity to create Employee database and insert
record of each employee along with their Empno, name, Dept, Salary and years of
experience.

[Award marks if students write their program with a different logic]

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
){
// Execute a query
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO Registration VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Part – C (1 x 15 = 15 Marks)
16.a. Write a program to demonstrate the following i) to convert lower case string to upper
case. ii) to compare two strings.

[Award marks if students write their program with a different logic]

i.
1. public class changeCase {
2. public static void main(String[] args) {
3.
4. String str1="Great Power";
5. StringBuffer newStr=new StringBuffer(str1);
6.
7. for(int i = 0; i < str1.length(); i++) {
8.
9. //Checks for lower case character
10. if(Character.isLowerCase(str1.charAt(i))) {
11. //Convert it into upper case using toUpperCase() function
12. newStr.setCharAt(i, Character.toUpperCase(str1.charAt(i)));
13. }
14. //Checks for upper case character
15. else if(Character.isUpperCase(str1.charAt(i))) {
16. //Convert it into upper case using toLowerCase() function
17. newStr.setCharAt(i, Character.toLowerCase(str1.charAt(i)));
18. }
19. }

ii. public class CompareStrings {

public static void main(String[] args) {

String style = "Bold";


String style2 = "Bold";

if(style == style2)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
Or
16.b. Explain in detail about various types of JDBC drivers.

JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand. There are
4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
Type-1 driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
Type-1 driver is also called Universal driver because it can be used to connect to any of the
databases.
• As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
• The ODBC bridge driver is needed to be installed in individual client machines.
• Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
• This driver software is built-in with JDK so no need to install separately.
• It is a database independent driver.
Type-2 driver
The Native API driver uses the client -side libraries of the database. This driver converts
JDBC method calls into native calls of the database API. In order to interact with different
database, this driver needs their local API, that’s why data transfer is much more secure as
compared to type-1 driver.
• Driver needs to be installed separately in individual client machines
• The Vendor client library needs to be installed on client machine.
• Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
• It is a database dependent driver.
Type-3 driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. Here all the database
connectivity drivers are present in a single server, hence no need of individual client-side
installation.
• Type-3 drivers are fully written in Java, hence they are portable drivers.
• No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
• Network support is required on client machine.
• Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
• Switch facility to switch over from one database to another database.
Type-4 driver
Type-4 driver is also called native protocol driver. This driver interact directly with
database. It does not require any native database library, that is why it is also known as Thin
Driver.
• Does not require any native library and Middleware server, so no client-side or server-
side installation.
• It is fully written in Java language, hence they are portable drivers.

You might also like