Java Programming456 QB
Java Programming456 QB
QUESTION BANK
19CS14403 JAVA PROGRAMMING
PART-A (ONE MARK QUESTIONS)
I.Choose the correct answer
1) Which package contains the Random class?
a) java.util package
b) java.lang package
c) java.awt package
d) java.io package
2) What do you mean by nameless objects?
a) An object created by using the new keyword.
b) An object of a superclass created in the subclass.
c) An object without having any name but having a reference.
d) An object that has no reference.
3) Which of the following exception is thrown when divided by zero statement is executed?
a) Null Pointer Exception
b) Number Format Exception
c) Arithmetic Expression
4) What do you mean by chained exceptions in Java?
a) Exceptions occurred by the Virtual Machine Error
b) An exception caused by other exceptions
c) Exceptions occur in chains with discarding the debugging information
d) None of the above
5) Which of the following option leads to the portability and security of Java?
a) Byte code is executed by JVM
b) The applet makes the Java code secure and portable
c) Use of exception handling
d) Dynamic binding between objects
6) Which of the following is not a Java features?
a) Dynamic
b) Architecture Neutral
c) Use of pointers
d) Object-oriented
7) _____ is used to find and fix bugs in the Java programs.
a) JVM
b) JRE
c) JDK
d) JDB
8) What does the expression float a = 35 / 0 return?
a) 0
b) Not a Number
c) Infinity
d) Run time exception
9) Evaluate the following Java expression, if x=3, y=5, and z=10:
++z + y - y + z + x++
a) 24
b) 23
c) 20
d) 25
10) Which of the following for loop declaration is not valid?
a) for ( int i = 99; i >= 0; i / 9 )
b) for ( int i = 7; i <= 77; i += 7 )
c) for ( int i = 20; i >= 2; - -i )
d) for ( int i = 2; i <= 20; i = 2* i )
11) Which option is false about the final keyword?
a) A final method cannot be overridden in its subclasses.
b) A final class cannot be extended.
c) A final class cannot extend other classes.
d) A final method can be inherited.
12) Which of the following is a mutable class in java?
a) java.lang.String
b) java.lang.Byte
c) java.lang.Short
d) java.lang.StringBuilder
13) Number of primitive data types in Java are?
a) 6
b) 8
c) 9
d) 10
14)What is the size of float and double in java?
a) 32 and 64
b) 32 and 32
c) 64 and 64
d) 64 and 32
1. The compiler converts source code files into byte code file.
4. It is not possible to define, a method in the subclass that has the same name, same
5. A constructor must have the same name as the class it is declared within.
11.An exception is an object that is generated when a run time error occurs.
12.A class declaration can include both abstract and final modifiers.
14.If a class contains an abstract method, that class itself must also be declared abstract.
15.If a class implements an interface, it must implement all the methods declared by that
interface.
16.If a class definition does not explicitly put a class into a package, the class belongs to the
default package.
1 A 7 D 13 B 19 C 25 A
2 D 8 C 14 A 20 A 26 D
3 C 9 D 15 D 21 D 27 C
4 B 10 A 16 B 22 D 28 D
5 A 11 C 17 D 23 B 29 C
6 C 12 D 18 A 24 D 30 D
1. Extends
2. Keyword
3. Single inheritance
4. Object
5. Initialize objects
6. Equals ()
7. Multiple, single
8. Import keyword
10. Package
11. Code
22. ==
23. Multi-platform
26. Class
1 T 5 T 9 F 13 T 17 T
2 T 6 T 10 T 14 F 18 T
3 F 7 T 11 F 15 T 19 F
4 T 8 T 12 F 16 T 20 F
21 T
2 marks (ALL UNITS)
(UNIT 1 TO 4)
1)What is an array?
• In Java, an array is a data structure that allows you to store multiple values
of the same data type in a contiguous memory block.
• Arrays in Java are widely used for storing and manipulating collections of
data.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection framework
is used in Java which grows automatically.
3)What is strings?
• String Pool, also known as SCP (String Constant Pool), is a special storage
space in Java heap memory that is used to store unique string objects.
• Whenever a string object is created, it first checks whether the String object
with the same string value is already present in the String pool or not, and
if it is available, then the reference to the string object from the string pool
is returned.
• Otherwise, the new string object is added to the string pool, and the
respective reference will be returned.
5) Is String immutable in Java? If so, then what are the benefits of Strings being
Immutable?
• Yes, Strings are immutable in Java. Immutable objects mean they can't be
changed or altered once they've been created.
• However, we can only modify the reference to the string object.
• String objects in Java are immutable and final, so we can't change their
value after they are created.
• Each time we manipulate a string, a new String object is created, and all
previous objects will be garbage, placing a strain on the garbage collector.
• This is why The Java team developed StringBuffer.
• A StringBuffer is a mutable object, meaning it can be changed, but the
string is an immutable object, so it cannot be changed once it has been
created.
}
8)How to reverse an array?
package arrays;
import java.util.Scanner;
while(start<end)
{
temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
for(int i:arr)
{
System.out.println(i);
}
}
}
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
10) What is multithreading?
• Yes, calling run() method directly is valid, but it will not work as a thread
instead it will work as a normal object.
• There will not be context-switching between the threads.
• When we call the start() method, it internally calls the run() method, which
creates a new stack for a thread while directly calling the run() will not
create a new stack.
14)What is Synchronization?
• In Java, when we create the threads, they are supervised with the help of a
Thread Scheduler, which is the part of JVM.
• Thread scheduler is only responsible for deciding which thread should be
executed.
Java thread scheduler also works for deciding the following for a thread:
• It selects the priority of the thread.
• It determines the waiting time for a thread
• It checks the Nature of thread
15) What is race-condition?
16)What is ThreadPriority?
Priorities in threads is a concept where each thread is having a priority which in
layman’s language one can say every object is having priority here which is
represented by numbers ranging from 1 to 10.
• The default priority is set to 5 as excepted.
• Minimum priority is set to 1.
• Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:
1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY
17)What is deadlock?
20)What is Swing?
• Swing is a Java library used to create graphical user interfaces (GUIs) for
desktop applications.
• It provides a set of components like buttons, text fields, and windows that
developers can use to build interactive and visually appealing software
interfaces.
21)What is AWT?
22)What is JDBC?
26)What is Socket?
30)What is TCP?
• TCP, or Transmission Control Protocol, is one of the core protocols of the
Internet Protocol (IP) suite.
• It operates at the transport layer of the OSI model and plays a crucial role in
providing reliable and connection-oriented communication between devices
on a network.
31)What is encryption?
Java API, which stands for "Application Programming Interface," refers to a set of
pre-defined classes, methods, and interfaces provided by the Java programming
language for developers to use when building Java applications.
• Servlets are a key part of the Java Platform, Enterprise Edition (Java EE),
and they are commonly used to create web applications.
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.
Custom tag libraries, often referred to simply as tag libraries, are a feature in web
development that allows developers to define and use their own custom tags in JSP
(JavaServer Pages) and other Java-based web frameworks.
Implicit objects in web development are predefined objects that are automatically
available to server-side scripts (e.g., in JavaServer Pages or JSP, Active Server
Pages or ASP, and other similar technologies) without the need for explicit
declaration.
10 marks(UNIT-1 TO 4)
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
Active: When a thread invokes the start() method, it moves from the new state to the
active state. The active state contains two states within it: one is runnable, and the
other is running.
History of Java
o Runnable: A thread, that is ready to run is then moved to the runnable state.
In the runnable state, the thread may be running or may be ready to run at any
given instant of time. It is the duty of the thread scheduler to provide the thread
time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each
individual thread. Each and every thread runs for a short span of time and
when that allocated time slice is over, the thread voluntarily gives up the CPU
to the other thread, so that the other threads can also run for their slice of time.
Whenever such a scenario occurs, all those threads that are willing to run,
waiting for their turn to run, lie in the runnable state. In the runnable state,
there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the
running state. Generally, the most common change in the state of a thread is
from runnable to running and again back to runnable.
For example, a thread (let's say its name is A) may want to print some data from the
printer. However, at the same time, the other thread (let's say its name is B) is using
the printer to print some data. Therefore, thread A has to wait for thread B to use the
printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable
to perform any execution and thus never consume any cycle of the Central
Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread
scheduler reactivates thread A, which is in the waiting or blocked state.
When the main thread invokes the join() method then, it is said that the main thread
is in the waiting state. The main thread then waits for the child threads to complete
their tasks. When the child threads complete their job, a notification is sent to the
main thread, which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the
thread scheduler to determine which thread to choose and which one to reject, and
the chosen thread is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread
(its name is A) has entered the critical section of a code and is not willing to leave
that critical section. In such a scenario, another thread (its name is B) has to wait
forever, which leads to starvation. To avoid such scenario, a timed waiting state is
given to thread B. Thus, thread lies in the waiting state for a specific span of time,
and not forever. A real example of timed waiting is when we invoke the sleep()
method on a specific thread. The sleep() method puts the thread in the timed wait
state. After the time runs out, the thread wakes up and start its execution from when
it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead thread.
In Java, thread priorities are used to indicate the relative importance of one thread
compared to another within the same program. Thread priorities can influence how
the operating system schedules threads for execution, but they do not guarantee
strict ordering or deterministic behavior.
Synchronization
Synchronization in the context of multithreaded programming refers to the
coordination and control of multiple threads to ensure proper and safe execution in
shared resources and critical sections. Without synchronization, when multiple
threads access and manipulate shared data concurrently, it can lead to race
conditions, data corruption, and unexpected behavior. Synchronization
mechanisms prevent these issues by ensuring that only one thread can access a
critical section of code or a shared resource at a time.
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
9)Explain the difference between Thread class and Runnable interface.
In Java, both the Thread class and the Runnable interface are used to create and
manage threads for concurrent execution. However, they have distinct purposes
and usage patterns. Let's delve into the differences between the two:
Thread Class:
1. Inheritance: The Thread class is a concrete class in Java's java.lang package.
When you want to create a new thread, you can directly subclass the Thread
class and override its run() method, which contains the code that the thread
will execute.
2. Limitation: Java only supports single inheritance, so if you extend the
Thread class, you cannot extend another class, limiting your flexibility in
terms of code reuse.
3. Thread Control: Since the Thread class encapsulates both the thread's
behavior and its management, it provides methods to directly control the
thread, such as start() to begin execution and join() to wait for the thread to
complete.
4. Thread Instance: Each thread corresponds to an instance of the Thread class.
This means that if you want to create multiple threads, you need to create
multiple instances of the Thread class.
5. Less Flexible Resource Sharing: Sharing resources between threads created
using the Thread class can be more challenging, as the thread instances
themselves encapsulate both behavior and execution.
Stream Filtering:
Stream filtering refers to the process of extracting, modifying, or manipulating
specific elements from a data stream based on certain criteria. Data streams can be
sequences of characters, bytes, or any other type of data that can be processed
sequentially. Stream filtering is a common technique used to process large datasets
efficiently without loading the entire dataset into memory at once.
In Java, stream filtering is typically associated with the Java Streams API
introduced in Java 8. Java Streams provide a powerful and functional way to
process collections and other data sources. Streams allow you to apply various
operations such as filtering, mapping, sorting, and reducing on data in a concise
and expressive manner.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
In this example, the filter operation is used to select only the even numbers from
the list of integers.
Piping:
Piping refers to the practice of connecting the output of one process or function as
the input to another, forming a chain of processing steps. Each step in the pipeline
performs a specific operation on the data and passes the modified data to the next
step. Piping is a powerful way to combine multiple operations into a single
sequence, making complex data transformations more manageable and readable.
In this example:
The result is a new list containing the filtered, transformed, and sorted words.
While this isn't exactly the same as piping in Unix shells, it offers a similar concept
of chaining operations to process data. Java's Stream API provides a powerful and
expressive way to achieve such data transformations in a functional and efficient
manner.
In summary, Swing builds upon AWT and provides a more extensive and flexible
set of GUI components, a pluggable look and feel mechanism, and a more
advanced event handling model. Swing components are lightweight and platform-
independent, offering greater consistency across different operating systems.
Despite the emergence of newer UI frameworks like JavaFX, Swing is still widely
used and supported in Java applications.
import javax.swing.*;
frame.pack();
frame.setVisible(true);
});
}
}
In this example, a basic Swing application creates a JFrame window with a JLabel
component.
Swing has been a fundamental part of Java GUI development for many years.
While newer UI frameworks like JavaFX have gained popularity, Swing remains
relevant and continues to be used in various applications and projects.
13)Write about the key features of JavaSwing.
Java Swing is a GUI (Graphical User Interface) toolkit for Java applications. It
provides a rich set of components and tools to create interactive and visually
appealing graphical user interfaces. Swing is built on top of the Abstract Window
Toolkit (AWT) but offers several enhancements and improvements over AWT.
Here are the key features of Java Swing:
1. Lightweight Components:
Swing components are lightweight and platform-independent. Unlike AWT, which
relies on native components, Swing components are implemented purely in Java.
This ensures consistent behavior and appearance across different platforms.
4. Layout Managers:
Swing provides layout managers that help you arrange components within
containers. Layout managers handle tasks like component positioning, sizing, and
alignment. Common layout managers include FlowLayout, BorderLayout,
GridLayout, and BoxLayout.
5. Customizability:
Swing components are highly customizable. You can modify their appearance by
setting properties, changing colors, fonts, and other visual attributes. Additionally,
you can create custom components by extending existing ones or implementing
Swing interfaces.
6. Event Handling:
Swing offers a flexible event handling model. You can attach event listeners to
components to respond to user interactions such as button clicks, mouse events,
and keyboard input. This model enables more precise control over how events are
processed.
7. Double Buffering:
Swing components use double buffering by default, which reduces flickering and
enhances the rendering of complex UIs. Double buffering involves rendering
components off-screen before displaying them, resulting in smoother animations
and improved performance.
8. Thread Safety:
Swing follows a single-threaded model, where all UI-related operations must be
performed on the event dispatch thread (EDT). Swing provides mechanisms to
ensure thread safety and synchronization of UI updates, helping to prevent
concurrent access issues.
11. Accessibility:
Swing components include built-in accessibility features, allowing visually
impaired users to interact with applications using screen readers and other assistive
technologies.
frame.setVisible(true);
}
}
1. The main method initializes the Swing components on the Event Dispatch
Thread (EDT) using SwingUtilities.invokeLater() to ensure proper GUI
initialization.
2. The createAndShowGUI method sets up the main frame for the user
registration form with a 6x2 grid layout.
3. Labels, text fields, radio buttons, and a button are created to gather user
input.
4. Event listeners are added to the submit button to process form data when
clicked.
5. Form data (name, email, password, gender) is collected from the
components.
6. The form data is printed to the console for demonstration purpose.
import java.sql.*;
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create a statement
Statement statement = connection.createStatement();
// Close resources
resultSet.close();
statement.close();
connection.close();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
In this example, we use the MySQL JDBC driver to connect to a MySQL database,
execute a SELECT query, and print the retrieved data. The general workflow
applies to other database systems as well.
JDBC is a foundational technology for Java applications that need to interact with
databases. It provides a standardized way to manage connections, execute queries,
and handle data, making it an essential tool for building database-driven
applications.
1. Driver Manager:
The DriverManager class acts as a central hub for managing database drivers. It's
responsible for loading and registering appropriate database drivers dynamically.
The driver manager allows applications to work with different database systems
without needing to modify code extensively. You use the DriverManager to obtain
a Connection to the database using the URL, username, and password.
2. Connection Pooling:
JDBC encourages the use of connection pooling to manage database connections
efficiently. Connection pooling involves creating and maintaining a pool of
database connections that can be reused. This minimizes the overhead of
establishing and closing connections for every database operation, improving
performance and resource management.
3. Resource Management:
JDBC emphasizes proper resource management to avoid resource leaks and
potential performance degradation. Resources like Connection, Statement, and
ResultSet must be explicitly closed when they are no longer needed. Failing to
close these resources can lead to memory leaks and increased resource
consumption.
4. SQL Statements:
JDBC supports three types of SQL statements: Statement, PreparedStatement, and
CallableStatement. Each type has its own purpose and usage:
6. Error Handling:
JDBC uses the SQLException class to handle database-related errors. Handling
exceptions is crucial for diagnosing and resolving issues that may occur during
database operations. Proper error handling helps ensure robustness and stability in
your applications.
8. Batch Processing:
JDBC supports batch processing, where multiple SQL statements are grouped
together and executed in a batch. This can significantly improve performance when
you need to perform repetitive tasks, such as inserting multiple rows into a table.
1. Data Storage and Retrieval: Applications often need to store and retrieve
data from databases to maintain information about users, products,
transactions, etc.
2. Reporting and Analysis: Database connectivity enables applications to
retrieve and analyze data for generating reports, statistics, and insights.
3. Authentication and Authorization: User authentication and authorization
information is often stored in databases, requiring connectivity for user
management.
4. E-commerce and Transactions: Online stores and financial applications rely
on database connectivity to manage orders, payments, and inventory.
5. Content Management: Content management systems use databases to store
articles, images, videos, and other media files.
Steps in Database Connectivity:
1. Loading the Driver: To establish a connection to a database, you need to
load the appropriate JDBC driver class. The driver class is provided by the
database vendor and implements the JDBC standard.
2. Establishing Connection: Once the driver is loaded, you use the
DriverManager.getConnection() method to establish a connection to the
database. You provide the connection URL, username, and password as
arguments.
3. Creating Statements: After obtaining a connection, you create a Statement or
PreparedStatement object. These objects allow you to execute SQL queries
and commands against the database.
4. Executing Queries: You execute SQL queries using the executeQuery()
method for SELECT statements and executeUpdate() for INSERT,
UPDATE, and DELETE statements. The results of a SELECT query are
returned as a ResultSet object.
5. Processing Results: When you execute a SELECT query, the result set
contains the retrieved data. You can iterate through the result set and extract
values using methods like getString(), getInt(), etc.
6. Closing Resources: After using the database resources, it's crucial to close
them properly to release database connections and resources. Failing to close
resources can lead to resource leaks.
7. Handling Exceptions: Database operations can result in exceptions due to
various reasons such as connection issues, query errors, or database
constraints. Proper error handling using try-catch blocks ensures graceful
error reporting and recovery.
JDBC and Database Connectivity:
JDBC is a Java API that provides a standard way to connect to relational databases
and perform database operations using Java code. It simplifies database
connectivity by offering a consistent interface for different databases. Developers
use JDBC to execute SQL queries, retrieve data, update records, and manage
transactions.
UNIT-4 TO 8
CLIENT SIDE:
import java.io.*;
import java.net.*;
// Read messages from the user and send them to the server
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
String message;
while (true) {
System.out.print("You: ");
message = userInput.readLine(); // Read user input
out.println(message); // Send message to the server
if (message.equalsIgnoreCase("bye")) {
break; // Exit the loop if the user types "bye"
}
// Close resources
userInput.close();
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SERVER SIDDE:
import java.io.*;
import java.net.*;
// Close resources
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
19)Explain Secure sockets.
Secure Socket Layer (SSL) provides security to the data that is transferred
between web browser and server. SSL encrypts the link between a web server and
a browser which ensures that all data passed between them remain private and
free from attack.
Secure Socket Layer Protocols:
• SSL record protocol
• Handshake protocol
• Change-cipher spec protocol
• Alert protocol
SSL Protocol Stack:
The SSL (Secure Sockets Layer) record protocol is a key component of the
SSL/TLS (Transport Layer Security) protocol suite, which is used to secure data
transmission over the internet. The SSL record protocol is responsible for
fragmenting, compressing (optional), encrypting, and authenticating data to ensure
the confidentiality, integrity, and authenticity of information exchanged between a
client and a server. It operates at the transport layer of the OSI model and is used to
establish secure communication channels between web browsers and web servers,
among other applications.
HANDSHAKE PROTOCOL:
The handshake protocol is an essential part of the SSL/TLS (Secure Sockets
Layer/Transport Layer Security) protocol suite, which is used to establish secure
communication channels over the internet. The handshake protocol's primary
purpose is to enable the client and server to authenticate each other, negotiate
encryption algorithms, and establish session keys for secure data exchange.
ALERT PROTOCOL:
The Alert Protocol is a crucial component of the SSL/TLS (Secure Sockets
Layer/Transport Layer Security) protocol suite, used to establish secure
communication channels over the internet. The primary purpose of the Alert
Protocol is to provide a means for communicating various alert and error messages
between the client and server during the SSL/TLS handshake and data exchange
phases. These alert messages can inform both parties about issues that may arise
during the secure communication.
20)Explain TCP.
TCP, or Transmission Control Protocol, is one of the core protocols of the Internet
Protocol (IP) suite. It operates at the transport layer of the OSI model and plays a
crucial role in providing reliable and connection-oriented communication between
devices on a network. Here's a detailed explanation of TCP:
1. Connection-Oriented Communication: TCP is a connection-oriented
protocol. This means that before data transfer begins, a connection is
established between the two devices (sender and receiver). This connection
setup is known as the "TCP handshake."
• Three-Way Handshake: To establish a connection, a three-way
handshake takes place:
• SYN (Synchronize): The sender (client) initiates the
connection by sending a SYN packet to the receiver (server).
• SYN-ACK (Synchronize-Acknowledge): The receiver
acknowledges the request and sends its own SYN packet back
to the sender.
• ACK (Acknowledge): The sender acknowledges the
acknowledgment, and the connection is established. Data
transfer can now begin.
2. Reliable Data Transfer: TCP ensures reliable data transfer. It achieves this
by implementing various mechanisms:
• Sequence Numbers: TCP assigns a sequence number to each byte of
data being sent. This enables the receiver to reconstruct the data in the
correct order.
• Acknowledgments (ACKs): After receiving data, the receiver sends
an acknowledgment to the sender to confirm the receipt of data up to a
certain sequence number.
• Retransmission: If the sender doesn't receive an acknowledgment
within a specific timeout period, it assumes the data was lost in transit
and retransmits it.
• Flow Control: TCP implements flow control to prevent
overwhelming the receiver with data. The receiver can inform the
sender of its current buffer space, allowing for efficient data
transmission.
3. Error Checking: TCP uses a checksum mechanism to verify the integrity of
data during transmission. If the checksum doesn't match at the receiver's
end, the data is considered corrupt, and a request is made to retransmit it.
4. Orderly Data Transmission: TCP guarantees that data sent by the sender
will be received by the receiver in the same order it was sent. This is crucial
for applications where data integrity and order matter, such as web
browsing, email, and file transfers.
5. Full Duplex Communication: TCP enables full-duplex communication,
meaning both the client and server can send and receive data simultaneously.
This allows for efficient bidirectional communication.
6. Port Numbers: TCP uses port numbers to specify which application or
service should receive the data on the receiving end. This enables multiple
applications to run simultaneously on a device and receive data on their
respective ports.
7. Connection Termination: When data exchange is complete, a connection
termination process takes place, allowing both sides to release the resources
used for the connection.
8. Flow Control: TCP includes flow control mechanisms to ensure that data is
transmitted at a rate that the receiver can handle. This prevents congestion
and buffer overflows.
TCP is commonly used for applications that require reliable and error-checked
communication, such as web browsing, email, file transfers, and most online
services. While TCP provides a high level of reliability, it may introduce some
additional overhead due to its connection-oriented nature and the various
mechanisms in place to ensure data integrity and order.
3. Scalability: These applications are built in a way that allows them to handle
more work by adding more computers to the network. This is like having more
workers to do a job when it gets busier.
4. Reliability and Fault Tolerance: Even if one of the computers in the network
fails, the application keeps working. It's like having backup plans so that the whole
system doesn't break if something goes wrong.
7. Security: Since the computers are connected over a network, security is crucial.
It's like making sure that only authorized people can access your files and
information.
1. Client:
• The client is a device or software application that requests services,
resources, or data from a server.
• It can be a personal computer, smartphone, tablet, or any other device
capable of connecting to a network.
• Clients are typically responsible for presenting information to the
user, such as user interfaces, and processing user input.
• They send requests to servers and receive responses.
2. Server:
• The server is a powerful computer or software application that
provides services, resources, or data to clients over a network.
• Servers are designed to handle multiple client requests
simultaneously, making them capable of serving multiple clients
concurrently.
• They store and manage data, perform calculations, and execute tasks
on behalf of clients.
• Servers are often dedicated to specific tasks, such as web servers,
database servers, email servers, file servers, and more.
• Scalability: Servers can handle multiple clients, making it easy to scale the
system as the number of clients increases.
• Centralized Data Management: Servers centralize data storage, making it
easier to maintain and secure data.
• Resource Sharing: Clients can access and share resources hosted on servers,
such as files, databases, and services.
• Client Diversity: Clients can be diverse, ranging from different platforms
and devices, as long as they can communicate with the server using standard
protocols.
To use Java Servlets, you need a Java servlet container, such as Apache Tomcat,
Jetty, or WildFly, which provides the runtime environment for servlet execution.
Servlets are a fundamental building block for developing Java-based web
applications, and they are commonly used in conjunction with other Java EE
technologies like JSP, EJB, and JDBC to create robust, scalable, and feature-rich
web applications.
In some architectures, you may find additional tiers, such as caching layers,
security layers, or messaging layers, depending on the specific requirements of the
application.
Unit-1 1
2 Mark
Abstraction, encapsulation, polymorphism, and inheritance are the four main theoretical
principles of object-oriented programming
The Procedural Programming follows a Top-Down approach. The Object Oriented Programming
follows a Bottom-Up approach. This programming model does not give importance to data. It prioritizes
the functions along with the sequence of actions that needs to follow.
By using Java, we can develop a variety of applications such as enterprise applications, network
applications, desktop applications, web applications, games, android app, and many more.
We have discussed about 8 Elements of the Structure of the Java Program below. These are
Section Documentation, Package Disclosure, Import Declarations, Connector Section, Category
Definition, Class constants and variables, Method Class Main and Techniques and conduct.
Objects are instances or references of a class. So we can call the methods and variables present
in this class with the help of their objects.
Java was originally developed by James Gosling at Sun Microsystems. It was released in May
1995 as a core component of Sun Microsystems' Java platform. The original and reference
implementation Java compilers, virtual machines, and class libraries were originally released by Sun
under proprietary licenses.
The two most important benefits of the JVM are the possibility to write a code once and run
everywhere, and automatic memory management.
The JDK is a development environment for building applications, applets, and components using
the Java programming language.
• Simple.
• Object-Oriented.
• Portable.
• Platform Independent.
• Secured.
• Robust.
Unit-2 1
2 Mark
Constructor in java is used to create the instance of the class. Constructors are almost similar to
methods except for two things - its name is the same as the class name and it has no return type.
Primitive Data Types. The eight primitives defined in Java are int, byte, short, long, float, double,
Boolean and char. These aren't considered objects and represent raw values.
Identifiers in Java are a sequence of characters to identify something in a program. They are
names given to a class, variable, package, method, or interface and allow the programmer to refer to
the specific item from any place in the program.
4. What is the naming convention of a Java program?
For variables, the Java naming convention is to always start with a lowercase letter and then
capitalize the first letter of every subsequent word.
In Java, there are four kinds of expression statements: assignment expressions, such as a += 5 , b
*= 7 , or c = 3. Prefix and postfix increment and decrement, such as ++a , --b , c++ , d--
An operator is called a unary, binary, or ternary operator based on the number of operands. If
an operator takes one operand, it is called a unary operator; if it takes two operands, it is called a binary
operator; if it takes three operands, it is called a ternary operator.
Specific conversions on primitive types are called the widening primitive conversions:
Control flow statements let you control the flow of the execution of the code in your program.
In Java programming language, you can control the flow of execution of the code by placing the decision
making, branching, looping, and adding conditional blocks.
An array constructor can be used to define only an ordinary array with elements that are not a
row type. An array constructor cannot be used to define an associative array or an ordinary array with
elements that are a row type.
Unit-3 1
2 Mark
Both exceptions and errors are the subclasses of a throw able class. The error implies a problem
that mostly arises due to the shortage of system resources. On the other hand, the exceptions occur
during runtime and compile time.
The Abstract class and Interface both are used to have abstraction. An abstract class contains an
abstract keyword on the declaration whereas an Interface is a sketch that is used to implement a class.
Java.lang package
The top three classes in this hierarchy (the Throw able, Error, and Exception classes) are all defined in
the java. Lang package (which is automatically imported into every class file)
The access specifies used with classes are private, protected and public. While in Interface only
one specified is used- Public.
User-defined exceptions are also referred to as custom exceptions. The exceptions created per
our use case and thrown using the throw keyword are user-defined exceptions, and such exceptions are
derived classes of the Exception class from the java.
There are three types of encapsulation, namely Member variable encapsulation, Function
encapsulation and Class encapsulation.
8. What is enrichment in Java?
The process of replacing objects to refs and refs to objects is called "Enrichment" and can be
done in two different ways.
Meanwhile, exceptions indicate exceptional conditions - problems for which the developer may
not have accounted. You can use assertions for internal logic checks within your code, unchecked
exceptions for error conditions outside your immediate code's control, and checked exceptions for
business and recoverable errors.
In order to create a custom exception, we need to extend the Exception class that belongs to
java. Lang package. Example: We pass the string to the constructor of the super class- Exception which is
obtained using the “get Message ()” function on the object created.
Unit-4 1
2 Mark
A thread in Java is the direction or path that is taken while a program is being executed.
Generally, all the programs have at least one thread, known as the main thread,
System.out.println("thread is running...");
}
public static void main(String args[]){
t1.start();
Threads are scheduled to run based on their scheduling priority. Each thread is assigned a
scheduling priority. The priority levels range from zero (lowest priority) to 31 (highest priority). Only the
zero-page thread can have a priority of zero.
isAlive () just returns a Boolean that indicates whether the thread is alive, the status of the
thread - it returns true or false, indicating whether the thread is "done". . join() makes the current
thread you are in wait until the thread that you're calling . join() on has completed.
This method is used to find out if a thread has actually been started and has yet not terminated.
Note: While returning this function returns true if the thread upon which it is called is still running. It
returns false otherwise
Process Synchronization means sharing system resources by processes in a such a way that,
Concurrent access to shared data is handled thereby minimizing the chance of inconsistent data.
Create a file object by passing the required file path as a parameter. Read the contents of each
file using Scanner or any other reader. Append the read contents into a StringBuffer. Write the
StringBuffer contents into the required output file.
10. What is a real example of multithreading in Java?
A very good example of thread-based multithreading is a word processing program that checks
the spelling of words in a document while writing the document. This is possible only if each action is
performed by a separate thread.
Unit-5 1
2 Mark
Network programming is the procedure of writing programs that run on multiple devices
(computers) that are linked together via a network. To allow for low-level communication details, Java
encapsulates classes and interfaces.
Concurrency is the ability to run several or multi programs or applications in parallel. The
backbone of Java concurrency is threads (a lightweight process, which has its own files and stacks and
can access the shared data from other threads in the same process)
A thread is a unit of control within a process: when a thread runs, it executes a function in the
program - the “main thread” executes the “main” function and other threads execute other functions.
An interrupt is an indication to a thread that it should stop what it is doing and do something
else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very
common for the thread to terminate.
Overview. Inter Thread Communication, as the name implies, is a method that allows many
synchronized threads to communicate or interact with one another. In Java, there are two ways to
implement inter-thread communication: using wait () and notify() methods and using the higher-level
constructs of the java.
6. What is communication between threads?
Inter-thread Communication
All the threads in the same program share the same memory space. If an object is accessible to
various threads then these threads share access to that object's data member and thus communicate
each other. The second way for threads to communicate is by using thread control methods.
Provides the classes necessary to create an applet and the classes an applet uses to
communicate with its applet context. Contains all of the classes for creating user interfaces and for
painting graphics and images.
TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to as
TCP/IP.
A more reliable distinction is that a client initiates a conversation, while a server waits for clients
to start conversations with it. In some cases, the same program may be both a client and a server.
Part –B
10 Mark
Unit -1
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
What is JVM?
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation provider
is independent to choose the algorithm. Its implementation has been provided by Oracle and
other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.
What it does
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution
engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it
is loaded first by the classloader. There are three built-in classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension
classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like
java.lang package classes, java.net package classes, java.util package classes, java.io package
classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of
System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads
the classfiles from classpath. By default, classpath is set to current directory. You can change the
classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.
Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null
These are the internal classloaders provided by Java. If you want to create your own classloader, you
need to extend the ClassLoader class.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method
data, the code for methods.
3) Heap
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.
PC (program counter) register contains the address of the Java virtual machine instruction currently
being executed.
7) Execution Engine
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte
code that have similar functionality at the same time, and hence reduces the amount of time
needed for compilation. Here, the term "compiler" refers to a translator from the instruction set
of a Java virtual machine (JVM) to the instruction set of a specific CPU.
Java Native Interface (JNI) is a framework which provides an interface to communicate with another
application written in another language like C, C++, Assembly etc. Java uses JNI framework to send
output to the Console or interact with OS libraries.
12. Explain the Installation of the JDK on Microsoft Windows Platforms?
JDK installers now support only one version of any Java feature release. You can't install multiple
versions of the same feature release.
For example, you can't install jdk-20 and jdk-20.0.1 simultaneously. If you attempt to install jdk-
20.0.1 after jdk-20 is installed, the installer uninstalls jdk-20 and installs jdk-20.0.1.
You run a self-installing executable file to unpack and install the JDK on Windows computers.
Install JDK on Windows computers by performing the actions described in the following topics:
You must have administrator privileges to install the JDK on Microsoft Windows.
1. Start the JDK 20 installer by double-clicking the installer's icon or file name in the download
location.
2. Follow the instructions provided by the installer.
3. After the installation is complete, delete the downloaded file to recover disk space.
Unit -2
Array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently
than they do in C/C++. Following are some important points about Java arrays.
Java Expression
Variables, operators, literals, and method calls make up a Java expression. Operands and operators are
used to build expressions. An expression’s operators specify which operations should be applied to the operands.
The precedence and associativity of the operators govern the order in which they are evaluated in an expression.
Take an example:
int marks;
marks =95;
result = a + b - 3.4;
if (num1 == num2)
Types of Expressions
While an expression typically yields a result, this is not always the case. In Java, there are a few types of
expressions:
Unit -3
Exception Handling in Java is one of the effective means to handle runtime errors so that the regular
flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such
as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory
leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control
of the programmer, and we should not try to handle errors.
All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy.
One branch is headed by Exception. This class is used for exceptional conditions that user programs should
catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-
time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError
is an example of such an error.
Exception handling in java is one of the powerful mechanisms to handle runtime errors caused by
exceptions. Exception handling plays an important role in software development. This article helps you understand
java exception, exception in java, java exception handling, java exception hierarchy, types of exception in java, and
many more.
Exception handling in java helps in minimizing exceptions and helps in recovering from exceptions. It is
one of the powerful mechanisms to handle runtime exceptions and makes it bug-free. Exception handling helps in
maintaining the flow of the program. An exception handling is defined as an abnormal condition that may happen
at runtime and disturb the normal flow of the program.
What is an Exception?
An expectation is an unexpected event that occurs while executing the program, that disturbs the normal flow of
the code.
Let’s say,
statement
statement
statement
exception ………… an exception occurred, then JVM will handle it and will exit the prog.
statement
statement
statement
1. JVM
If an exception is not handled explicitly, then JVM takes the responsibility of handling the exception.
Once the exception is handled, JVM will halt the program and no more execution of code will take place
• Example:
import java.util.*;
class Main {
System.out.println(5/0);
System.out.println("End of program!");
Runtime Error:
at Main.main(File.java:5)
Unit -4
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time than
process.
1) It doesn't block the user because threads are independent and you can perform multiple operations at the
same time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways:
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be
achieved by using the following three ways:
Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock
associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the
object's lock before accessing them, and then release the lock when it's done with them.
Unit-5
This article describes a very basic one-way Client and Server setup where a Client connects, sends
messages to the server and the server shows them using a socket connection. There’s a lot of low-level stuff
that needs to happen for these things to work but the Java API networking package (java.net) takes care of all of
that, making network programming very easy for programmers.
Client-Side Programming
Establish a Socket Connection
To connect to another machine we need a socket connection. A socket connection means the two
machines have information about each other’s network location (IP Address) and TCP port. The java.net.Socket
class represents a Socket. To open a socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
• The first argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where code will run on
the single stand-alone machine).
• The second argument – TCP Port. (Just a number representing which application to run on a server. For
example, HTTP runs on port 80. Port number can be from 0 to 65535)
Communication
To communicate over a socket connection, streams are used to both input and output the data.
The socket connection is closed explicitly once the message to the server is sent.
In the program, the Client keeps reading input from a user and sends it to the server until “Over” is typed
Java Implementation
• Java
import java.net.*;
// establish a connection
try {
System.out.println("Connected");
socket.getOutputStream());
catch (UnknownHostException u) {
System.out.println(u);
return;
catch (IOException i) {
System.out.println(i);
return;
while (!line.equals("Over")) {
try {
line = input.readLine();
out.writeUTF(line);
catch (IOException i) {
System.out.println(i);
try {
input.close();
out.close();
socket.close();
catch (IOException i) {
System.out.println(i);
Server Programming
Communication
After finishing, it is important to close the connection by closing the socket as well as input/output streams
In this Java network programming tutorial, you will learn how to develop a socket server program to implement fully
functional network client/server application. You will also learn how to create a multi-threaded server.
The ServerSocketclass is used to implement a server program. Here are the typical steps involve in developing a
server program:
The steps 1 to 5 can be repeated for each new client. And each new connection should be handled by a separate
thread.
- ServerSocket(int port): creates a server socket that is bound to the specified port number. The maximum
number of queued incoming connections is set to 50 (when the queue is full, new connections are
refused).
- ServerSocket(int port, int backlog): creates a server socket that is bound to the specified port number
and with the maximum number of queued connections is specified by the backlog parameter.
- ServerSocket(int port, int backlog, InetAddress bindAddr): creates a server socket and binds it to the
specified port number and a local IP address.
Use the first constructor for a small number of queued connections (less than 50) and any local IP address
available.
Use the second constructor if you want to explicitly specify the maximum number of queued requests.
And use the third constructor if you want to explicitly specify a local IP address to be bound (in case the computer
has multiple IP addresses).
And of course, the first constructor is preferred for simple usage. For example, the following line of code creates a
server socket and binds it to the port number 6868:
Once a ServerSocket instance is created, call accept() to start listening for incoming client requests:
Note that the accept() method blocks the current thread until a connection is made. And the connection is
represented by the returned Socket object.