0% found this document useful (0 votes)
6 views31 pages

Java 5

The document provides a comprehensive overview of Java programming concepts, including Collections, JDBC, multithreading, and JSP. It covers various topics like thread life cycle, database connectivity, and the differences between interfaces such as Set and List. Additionally, it includes code examples for practical implementation of these concepts.

Uploaded by

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

Java 5

The document provides a comprehensive overview of Java programming concepts, including Collections, JDBC, multithreading, and JSP. It covers various topics like thread life cycle, database connectivity, and the differences between interfaces such as Set and List. Additionally, it includes code examples for practical implementation of these concepts.

Uploaded by

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

Q1) Attempt any eight of the

following.
a) What is Collection?
A Collection in Java is a framework that provides architecture to store, retrieve, and
manipulate groups of objects dynamically.

Located in [Link] package.

It is an interface.

Main subinterfaces: List, Set, Queue.

✔ It allows dynamic memory allocation and built-in methods for data handling.

b) Define JDBC.
JDBC (Java Database Connectivity) is a Java API used to connect and execute
queries with databases.

Package: [Link]

Used to perform:

Insert

Update

Delete

Retrieve operations

✔ It acts as a bridge between Java application and database.

c) What is default priority in


multithreading?
The default priority of a thread in Java is:

5
Minimum Priority → 1

Default Priority → 5

Maximum Priority → 10

✔ Constant name: Thread.NORM_PRIORITY

d) Give syntax of doGet() method.


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// code to handle GET request


}

✔ Used to handle HTTP GET requests in Servlet.

e) List any two implicit objects in JSP.


JSP provides 9 implicit objects.

Any two are:

request

response

Other examples:

session

application

out

config

page

pageContext

exception
f) Give any two applications of Spring
Framework.
Web Application Development

Used to build MVC-based web applications.

Enterprise Application Development

Used in banking, e-commerce, large-scale systems.

g) State constructors of TreeSet class.


TreeSet class provides the following constructors:

TreeSet()

TreeSet(Collection c)

TreeSet(Comparator comp)

TreeSet(SortedSet s)

✔ It is available in [Link] package.

h) Write the use of yield().


yield() method is used to:

Pause the currently executing thread temporarily.

Give chance to other threads of same priority to execute.

Syntax:

[Link]();

✔ It is a static method of Thread class.

i) What is purpose of [Link]()?


[Link]() is used to:

Load the JDBC driver class into memory.

Register driver with DriverManager.

Example:

[Link]("[Link]");

✔ Mainly used in database connectivity.

j) Define session in servlet.


A session in servlet is a mechanism used to:

Maintain user data between multiple HTTP requests.

Track user interactions with the web application.

It is implemented using:

HttpSession session = [Link]();

✔ Used for login systems, shopping carts, etc.

Q2) Attempt any four of the


following.
a) Differentiate between
Thread class and Runnable
interface
In Java, multithreading can be achieved by either extending the Thread class or
implementing the Runnable interface.

🔹 Difference Between Thread and Runnable

Thread Class Runnable Interface


It is an interface
It is a class present in
present in [Link]
[Link] package.
package.
Thread is created by
Thread is created by
implementing
extending Thread class.
Runnable interface.
Cannot extend any Can extend another
other class (Java does class because it only
not support multiple implements an
inheritance). interface.
More flexible and
Less flexible.
preferred method.
Requires passing
Directly creates thread
object to Thread
object.
class constructor.

🔹 Example Using Thread Class

class MyThread extends Thread {


public void run() {
[Link]("Thread using Thread class");
}
public static void main(String args[]) {
MyThread t = new MyThread();
[Link]();
}
}
🔹 Example Using Runnable Interface

class MyThread implements Runnable {


public void run() {
[Link]("Thread using Runnable interface");
}
public static void main(String args[]) {
Thread t = new Thread(new MyThread());
[Link]();
}
}

✅ Conclusion

Runnable interface is preferred because it supports multiple inheritance and provides


better object-oriented design.

b) What is use of commit() in


transactions in Java?
commit() method is used in JDBC transaction management.

🔹 Purpose of commit()

Permanently saves all changes made during a transaction to the database.

Ends the current transaction.

Ensures data consistency.

🔹 Why commit is needed?

By default, JDBC works in auto-commit mode (each SQL statement is committed


automatically).

To manage transactions manually:

[Link](false);

Then after executing SQL statements:

[Link]();
If any error occurs:

[Link]();

🔹 Example

Connection con = [Link](...);


[Link](false);

Statement st = [Link]();
[Link]("INSERT INTO emp VALUES(1,'Ram')");
[Link]("UPDATE emp SET salary=5000 WHERE id=1");

[Link](); // Saves changes permanently

✅ Conclusion

commit() ensures that all SQL operations in a transaction are permanently stored in
the database.

c) Write general syntax of


include directive in JSP
The include directive is used to include content of another file at translation time.

🔹 Syntax:

<%@ include file="[Link]" %>

🔹 Example:

<%@ include file="[Link]" %>

🔹 Features

Includes static content.

Happens at translation phase.

Improves code reusability.


d) Write purpose of
setContentType()
setContentType() method is used to:

Set the MIME type of the response.

Inform browser about type of data being sent.

🔹 Syntax

[Link]("text/html");

🔹 Common Content Types

Type Meaning
HTML
text/html
content
text/plain Plain text
image/jpeg Image file
application/pdf PDF file

🔹 Importance

Prevents browser misinterpretation.

Required for proper rendering of response.

e) Differentiate between Set


and List interface
Both are part of Java Collection Framework.

🔹 Difference Between Set and List

Set Interface List Interface


Does not allow duplicate elements. Allows duplicate
Set Interface List Interface
elements.
Does not maintain insertion order (except Maintains insertion
LinkedHashSet). order.
Can access elements
Access elements using Iterator only.
using index.
Examples: ArrayList,
Examples: HashSet, TreeSet
LinkedList

🔹 Example

Set<Integer> s = new HashSet<>();


[Link](10);
[Link](10); // duplicate ignored
List<Integer> l = new ArrayList<>();
[Link](10);
[Link](10); // duplicate allowed

✅ Conclusion

Use Set when uniqueness is required.

Use List when order and duplicates are allowed.

Q3) Attempt any two of the


following .
a) Write a JSP program to accept the details
of teacher (tid, name, salary, subject) from
user and store it into the database.

CREATE TABLE teacher (

tid INT,
name VARCHAR(50),

salary DOUBLE,

subject VARCHAR(50)

);

<html>

<head>

<title>Teacher Form</title>

</head>

<body>

<h2>Teacher Details Form</h2>

<form action="[Link]"
method="post">

Teacher ID: <input type="text" name="tid"


required><br><br>

Name: <input type="text" name="name"


required><br><br>

Salary: <input type="text" name="salary"


required><br><br>

Subject: <input type="text" name="subject"


required><br><br>

<input type="submit" value="Submit">

</form>

</body>

</html>
<%@ page import="[Link].*" %>

<html>

<head>

<title>Insert Teacher</title>

</head>

<body>

<%

int tid =
[Link]([Link]("tid"));

String name = [Link]("name");

double salary =
[Link]([Link]("salary")
);

String subject = [Link]("subject");

try {

[Link]("[Link]");

Connection con =
[Link](

"jdbc:mysql://localhost:3306/college",

"root",

"password"
);

PreparedStatement ps =
[Link](

"INSERT INTO teacher VALUES(?,?,?,?)"

);

[Link](1, tid);

[Link](2, name);

[Link](3, salary);

[Link](4, subject);

[Link]();

[Link]("<h3>Teacher Record Inserted


Successfully!</h3>");

[Link]();

} catch(Exception e) {

[Link](e);

%>

</body>
</html>

b) Write a java program to display the even


numbers between 1 to 100. Each number
should display after 5 seconds. [use sleep()]

class EvenNumbers {

public static void main(String args[]) {

try {

for (int i = 1; i <= 100; i++) {

if (i % 2 == 0) {

[Link](i);

[Link](5000); // 5 seconds
delay

} catch (InterruptedException e) {

[Link](e);

}
c) Write a java a program to accept details of
employee (Eid, Name, Salary) from user and
store it into the database.

CREATE TABLE employee (

eid INT,

name VARCHAR(50),

salary DOUBLE

);

import [Link].*;

import [Link];

class EmployeeDB {

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

[Link]("Enter Employee ID: ");

int eid = [Link]();

[Link]();

[Link]("Enter Name: ");

String name = [Link]();


[Link]("Enter Salary: ");

double salary = [Link]();

try {

[Link]("[Link]");

Connection con =
[Link](

"jdbc:mysql://localhost:3306/college",

"root",

"password"

);

PreparedStatement ps =
[Link](

"INSERT INTO employee VALUES(?,?,?)"

);

[Link](1, eid);

[Link](2, name);

[Link](3, salary);

[Link]();
[Link]("Employee Record
Inserted Successfully!");

[Link]();

} catch(Exception e) {

[Link](e);

Q4) Attempt any two of the


following.
a) Explain the life cycle of
thread.
A Thread is a lightweight sub-process that allows a program to perform multiple
tasks simultaneously (multithreading).

During execution, a thread passes through different states. This process is called the
Thread Life Cycle.

✅ Thread States in Java


Java defines the following thread states (as per [Link]):

New

Runnable

Running

Blocked / Waiting
Timed Waiting

Terminated (Dead)

🔹 1) New State
A thread is in New state when it is created but not yet started.

Thread object is created using new keyword.

start() method has not been called.

Example:

Thread t = new Thread();

✔ Thread is in New state.

🔹 2) Runnable State
After calling start(), thread moves to Runnable state.

It is ready to run and waiting for CPU allocation.

Thread scheduler decides which thread will execute.

Example:

[Link]();

✔ Thread enters Runnable state.

🔹 3) Running State
When thread scheduler selects the thread from Runnable state.

Thread executes the run() method.

It is actively using CPU.

✔ Running state is controlled by JVM scheduler.


🔹 4) Blocked / Waiting State
A thread enters this state when:

It is waiting for a resource (like lock).

It calls wait().

It is waiting for another thread to complete (join()).

Example:

synchronized(obj) {
[Link]();
}

✔ Thread waits until notified.

🔹 5) Timed Waiting State


Thread enters timed waiting when:

sleep() is called

wait(time) is called

join(time) is called

Example:

[Link](5000);

✔ Thread waits for specified time.

🔹 6) Terminated (Dead) State


When run() method completes.

Or thread stops due to exception.

✔ Thread cannot be restarted once terminated.


🔹 Thread Life Cycle Diagram
(Text Representation)
New
↓ start()
Runnable
↓ (CPU allocated)
Running
↓ sleep()/wait()/join()
Waiting / Blocked
↓ notify()/time over
Runnable
↓ run() completes
Terminated

🔹 Methods Affecting Thread


Life Cycle
Metho
Purpose
d
Moves thread from New →
start()
Runnable
run() Contains execution code
sleep() Moves thread to Timed Waiting
wait() Moves thread to Waiting
notify() Wakes waiting thread
join() Waits for another thread
Pauses current thread
yield()
temporarily

🔹 Important Points for Exams


start() creates a new thread; run() does not.

After termination, thread cannot restart.

Scheduler controls Runnable → Running transition.

sleep() does not release lock; wait() releases lock.


🔹 Conclusion
The Thread Life Cycle describes how a thread moves through different states from
creation to completion. Understanding these states is essential for writing efficient
multithreaded Java applications.

b) Write a java program to accept n


numbers from user store them into the
linkedlist collection and display only
negative integers.
import [Link];

import [Link];

class NegativeNumbers {

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

LinkedList<Integer> list = new


LinkedList<Integer>();

[Link]("Enter how many numbers: ");


int n = [Link]();

// Accept numbers

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

[Link]("Enter number: ");

int num = [Link]();

[Link](num);

// Display negative numbers

[Link]("Negative Numbers are:");

for (Integer num : list) {

if (num < 0) {

[Link](num);

c) Write a JSP program to display all the


perfect numbers between 1 to n in blue
color.
<html>

<head>
<title>Perfect Number Input</title>

</head>

<body>

<h2>Enter a Number</h2>

<form action="[Link]"
method="post">

Enter n: <input type="number"


name="num" required>

<input type="submit" value="Find


Perfect Numbers">

</form>

</body>

</html>

<%@ page language="java" %>

<html>

<head>

<title>Perfect Numbers</title>

</head>

<body>

<%
int n =
[Link]([Link]("num
"));

%>

<h2>Perfect Numbers between 1 and <%= n


%> :</h2>

<font color="blue">

<%

for(int i = 1; i <= n; i++) {

int sum = 0;

for(int j = 1; j <= i/2; j++) {

if(i % j == 0) {

sum += j;

if(sum == i) {

[Link](i + " ");

}
}

%>

</font>

</body>

</html>

Q5) Attempt any one of the


following.
a) JDBC Process in Details
✅ What is JDBC?
JDBC (Java Database Connectivity) is a Java API that enables Java applications to
connect and interact with databases.

It allows operations like:

Insert

Update

Delete

Retrieve data

Package used: [Link]

✅ Steps in JDBC Process


The JDBC process consists of 6 main steps:
Step 1: Import Required Packages
Import JDBC classes.

import [Link].*;

Step 2: Load and Register the Driver


Load database driver into memory.

[Link]("[Link]");

✔ Registers driver with DriverManager.

Step 3: Establish Connection


Create connection between Java application and database.

Connection con = [Link](


"jdbc:mysql://localhost:3306/college",
"root",
"password"
);

✔ Returns a Connection object.

Step 4: Create Statement


Used to send SQL queries to database.

Types of statements:

Statement
Use
Type
Simple SQL
Statement
queries
PreparedStatem Precompiled
ent queries
CallableStateme
Stored procedures
nt

Example:
PreparedStatement ps = [Link](
"INSERT INTO student VALUES(?,?,?)"
);

Step 5: Execute Query


Two main methods:

Method Used For


executeQuery(
SELECT statement
)
executeUpdate INSERT, UPDATE,
() DELETE

Example:

[Link]();

Step 6: Process ResultSet (For SELECT)


ResultSet rs = [Link]();

while([Link]()) {
[Link]([Link](1));
}

Step 7: Close Connection


Always close resources.

[Link]();

✅ JDBC Flow Diagram (Text


Representation)
Java Application

Load Driver

Create Connection

Create Statement

Execute Query

Process Result

Close Connection

✅ Advantages of JDBC
Platform independent

Secure (PreparedStatement prevents SQL injection)

Supports transaction management

Scalable

✅ Conclusion
The JDBC process provides a structured way to connect Java applications with
databases using drivers and APIs.

b) Inter-Thread
Communication in Details

✅ What is Inter-Thread Communication?


Inter-thread communication is a mechanism where:

Multiple threads communicate with each other to avoid


problems like race conditions and busy waiting.

It is used when:

One thread produces data

Another thread consumes data


Example: Producer-Consumer problem

✅ Why It Is Needed?
Without communication:

Threads may access shared data incorrectly

Can cause data inconsistency

May lead to CPU wastage (busy waiting)

✅ Methods Used in Inter-Thread


Communication
All methods belong to Object class:

Method Purpose
wait() Makes thread wait
Wakes one waiting
notify()
thread
Wakes all waiting
notifyAll()
threads

✅ Important Rules
Must be called inside synchronized block

Works on object lock

Thread must own the object's monitor

✅ Example: Producer-
Consumer Program
class Shared {
int data;
boolean valueSet = false;
synchronized void produce(int x) throws Exception {
if(valueSet)
wait();

data = x;
[Link]("Produced: " + x);
valueSet = true;
notify();
}

synchronized void consume() throws Exception {


if(!valueSet)
wait();

[Link]("Consumed: " + data);


valueSet = false;
notify();
}
}

Producer Thread
class Producer extends Thread {
Shared s;
Producer(Shared s) { this.s = s; }

public void run() {


try {
for(int i=1; i<=5; i++)
[Link](i);
} catch(Exception e) {}
}
}

Consumer Thread
class Consumer extends Thread {
Shared s;
Consumer(Shared s) { this.s = s; }

public void run() {


try {
for(int i=1; i<=5; i++)
[Link]();
} catch(Exception e) {}
}
}

Main Method
class Test {
public static void main(String args[]) {
Shared s = new Shared();
new Producer(s).start();
new Consumer(s).start();
}
}

✅ How It Works
Producer produces data.

Consumer waits if no data available.

wait() pauses thread.

notify() wakes waiting thread.

Ensures proper synchronization.

✅ Advantages of Inter-Thread
Communication
Prevents busy waiting

Improves performance

Ensures data consistency

Useful in real-time systems

✅ Difference Between sleep()


and wait()
sleep() wait()
Belongs to Thread Belongs to Object
class class
Does not release lock Releases lock
Used for
Used for time delay
communication

✅ Conclusion
Inter-thread communication allows multiple threads to coordinate efficiently using
wait(), notify(), and notifyAll() to avoid conflicts and ensure synchronized
execution.

You might also like