22CS202 JAVA PROGG ANSKEY FIAT SIAT ME ESE 2022-2023
22CS202 JAVA PROGG ANSKEY FIAT SIAT ME ESE 2022-2023
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.
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.
// Concrete subclass
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
sides = 1;
}
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).
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.
return data;
}
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
sharedResource.produce(i);
}
}
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
sharedResource.consume();
}
}
}
// Start threads
producerThread.start();
consumerThread.start();
}
}
if (console == null) {
System.out.println("Console is not available on this platform.");
System.exit(1);
}
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 {
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.
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<>();
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
inventory.addItem("Item" + i, 10);
}
inventory.displayInventory();
}
}
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;
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;
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 {
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.
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?
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 prepared statement is a feature used to execute the same (or similar) SQL statements
repeatedly with high efficiency.
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
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.
import java.util.Scanner;
int empid;
String name;
float salary;
e[i].display();
}
}
}
Or
11.b. What are various data types in java? Explain them in detail?
12.a. Write a program to generate student mark sheet using multi-level inheritance.
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);
}
}
Or
12.b. Discuss the importance of final modifier in 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
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.
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 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.
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
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.
// 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);
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.
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:
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:
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.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
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.
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. }
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.