Java
Java
Java
Q2. Discuss any two swing components used to display highly formatted and iterative
information.
Ans: Java Swing was introduced as part of the Java Foundation Classes (JFC) in the late 1990s, aiming
to address the limitations of the earlier Abstract Window Toolkit (AWT). Unlike AWT, that relies on the
native platform's components for rendering, Swing is entirely written in Java, offering a consistent look
and feel across different operating systems.
Swing provides a comprehensive set of components for building GUIs, including buttons, text fields,
panels, and more. These components are highly customizable, allowing developers to create visually
appealing and user-friendly interfaces.
In Java Swing, two commonly used components for displaying highly formatted and iterative information
are:
1. JTable
JTable is a versatile component used for displaying data in a tabular (grid) format, and it is often used
when we need to display structured, iterative data with rows and columns, such as spreadsheets or
databases.
Output:
2. JList
JList is a component used to display a list of items, typically used for presenting a large number of
elements in a single-column or multi-column list. It is useful when the data is iterative (e.g., a list of
names, files, or options), and the display needs to be highly customizable.
Output:
Q3. Explain callback methods in Entity beans.
Ans: In Enterprise JavaBeans (EJB), Entity Beans represent persistent data objects that are typically
associated with a database. The concept of callback methods in Entity Beans refers to special
methods that are automatically invoked by the EJB container during specific lifecycle events of an entity
bean. These methods allow developers to run custom code when certain actions occur, such as when
an entity bean is created, loaded, updated, or removed.
These callback methods are primarily used to handle business logic or resource management in
response to lifecycle changes of the entity bean, such as preparing data before it’s stored or performing
clean-up after data is removed.
Callback is a mechanism by which the life cycle of an enterprise bean can be intercepted. EJB 3.0
specification has specified callbacks for which callback handler methods are created. EJB Container
calls these callbacks. We can define callback methods in the EJB class itself or in a separate class. EJB
3.0 has provided many annotations for callbacks.
Annotation Description
@PreDestroy Invoked when a bean is removed from the bean pool or is destroyed.
Annotation Description
@PreDestroy Invoked when a bean is removed from the bean pool or is destroyed.
Annotation Description
@PostConstruct Invoked when a bean is created for the first time.
@PreDestroy Invoked when a bean is removed from the bean pool or is destroyed.
Annotation Description
Invoked when a record is fetched from database and loaded into the
@PostLoad
entity.
Ans: In JavaServer Pages (JSP), implicit objects are predefined objects that the JSP container
automatically makes available to the page, allowing you to access various functionalities without
explicitly creating or instantiating them. These objects provide access to important resources, such as
request data, session information, application data, and more.
The request object allows you to access all the information sent by the client (browser) to the server.
This includes parameters, headers, and attributes sent via GET or POST methods.
Example:
Here, the value of the username parameter from the HTTP request is retrieved and displayed on
the page.
Common Methods:
o getParameter(String name): Gets the value of a request parameter.
o getHeader(String name): Retrieves the value of a request header.
o getAttribute(String name): Retrieves an attribute set in the request.
The response object is used to modify the HTTP response sent back to the client. You can use it to set
response headers, content type, and other output.
Example:
<%
response.setContentType("text/html");
response.getWriter().write("<h1>Hello, World!</h1>");
%>
In this example, the content type of the response is set to "text/html," and a message is sent to
the client.
Common Methods:
o setContentType(String type): Sets the content type for the response.
o getWriter(): Gets a PrintWriter object to send data to the client.
The out object is used to send output to the client (i.e., to write content that will be rendered in the
browser). It’s a shorthand for the JspWriter object.
Example:
<%
out.println("<h2>This is an example of JSP output.</h2>");
%>
Common Methods:
o println(String s): Writes the string to the output.
o write(String s): Writes the string to the response.
The session object is used to store data that should be available across multiple requests for the same
user. It is typically used to manage user-specific data like authentication details, preferences, etc.
Example:
<%
session.setAttribute("username", "JohnDoe");
%>
Here, a session attribute username is set for the current user session.
Common Methods:
o setAttribute(String name, Object value): Stores an object as a session attribute.
o getAttribute(String name): Retrieves a session attribute.
o invalidate(): Ends the session.
The application object allows access to application-wide parameters and attributes. It is shared across
all users and sessions within the application.
Example:
<%
application.setAttribute("appName", "My Web Application");
%>
Common Methods:
o setAttribute(String name, Object value): Sets an attribute for the application.
o getAttribute(String name): Retrieves an application attribute.
o getInitParameter(String name): Retrieves an initialization parameter from web.xml.
The config object provides access to the servlet configuration, which includes initialization parameters
and servlet-specific settings.
Example:
<%
String dbUrl = config.getInitParameter("dbUrl");
%>
Common Methods:
o getInitParameter(String name): Retrieves a servlet initialization parameter from web.xml.
The pageContext object provides a wide range of functionality, including access to all the other implicit
objects, as well as methods for working with the page's request, response, session, and more.
Example:
<%
pageContext.setAttribute("message", "Welcome to JSP!");
%>
Common Methods:
o setAttribute(String name, Object value): Sets a page context attribute.
o getRequest(), getResponse(), getSession(): Access various objects like request,
response, and session.
The exception object is available when an error occurs during the processing of a JSP page and it is
used in error pages defined with the errorPage attribute. It gives access to the exception object that
caused the error.
Example:
If an error occurs in another JSP page, the exception object will contain details of the exception.
Common Methods:
o getMessage(): Retrieves the exception message.
o printStackTrace(): Prints the exception's stack trace.
The page object refers to the instance of the JSP page itself. It is essentially a reference to the Servlet
that the JSP is compiled into. In practice, this object is rarely used directly.
Example:
<%
page.toString(); // Returns the string representation of the page object.
%>
You can use the page object if you need to reference the current JSP page object.
Common Methods:
o toString(): Returns a string representation of the page object.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The Client-Server model is a fundamental network architecture where two processes (the client and
server) communicate with each other. The client sends requests, and the server listens to those
requests, processes them, and responds accordingly.
1. Server: The server listens for client connections on a specific port. Once a connection is
established, the server processes requests and sends a response back to the client.
2. Client: The client establishes a connection to the server and can send requests. It then waits for
the server’s response.
1. Server Side:
The server creates a ServerSocket object that listens on a specified port.
o
When a client attempts to connect, the server accepts the connection using accept() and
o
obtains a Socket object to communicate with the client.
o The server reads data from the client, processes it, and sends back a response.
2. Client Side:
o The client creates a Socket object and connects to the server by specifying the server's IP
address and port.
o After the connection is established, the client can send data to the server and receive
responses.
Ans: To demonstrate a basic networking application using Java Socket programming, we'll create a
simple client-server application where the client sends a message to the server, and the server
responds back with a confirmation message. This is a basic example using TCP (Transmission
Control Protocol) socket.
1. Server Program
The server listens for client connections on a specific port. Once a connection is made, it reads the
client's message and sends a response back to the client.
import java.net.*;
try {
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
2. Client Program
The client connects to the server using the server's IP address and port number. It sends a message to
the server and waits for the response.
import java.net.*;
socket.close();
} catch (IOException e) {
e.printStackTrace();
Output
Server response: Server received your message: Hello, Server! This is the client.
This simple networking application demonstrates the basic use of Java Socket Programming to
establish a client-server communication using TCP sockets. The client sends a message to the
server, and the server processes it and sends a response back to the client. This forms the foundation
for building more complex networked applications like chat servers, web servers, and more.
Ans: A thread is a lightweight process that allows concurrent execution of two or more parts of a
program. A thread is a single path of execution within a program. When a program starts, it contains a
main thread, and any additional threads created by the program are referred to as child threads.
Threads are essential for performing multiple tasks at once, or multitasking, which can significantly
improve performance, especially for I/O-bound or CPU-bound tasks.
Java provides the Thread class and the Runnable interface to create and manage threads. Each thread
has its own execution stack, and threads can run concurrently (in parallel if the system has multiple
CPUs).
1. User Threads
2. Daemon Threads
1. User Threads
User threads, also known as application threads, are threads that are explicitly created by the
programmer to perform specific tasks. They play a direct role in the main functionality of the application.
User threads continue executing until their task is completed or until the application explicitly terminates
them.
Example:
2. Daemon Threads
Daemon threads are threads that provide support to user threads. They run in the background and are
considered "service" threads. Unlike user threads, daemon threads do not prevent the JVM from exiting,
even if they are still running. When all user threads have finished executing, the JVM terminates,
abruptly stopping any remaining daemon threads.
The life cycle of a JSP (JavaServer Page) involves a sequence of stages that are carried out from the
creation of the page to its destruction. The life cycle is managed by the Servlet container (like Apache
Tomcat), which is responsible for handling the requests and responses in the web application. Below is
a detailed explanation of the JSP life cycle, followed by the corresponding diagram.
+----------------------+
| 1. Request Arrives |
+----------------------+
|
v
+----------------------+
| 2. Translation |
| Phase | <--- First Time JSP Request
+----------------------+
|
v
+----------------------+
| 3. init() method | ---> Initialization Phase
+----------------------+
|
v
+----------------------+
| 4. service() method | ---> Request Processing Phase
+----------------------+
|
v
+----------------------+
| 5. destroy() method | ---> Destruction Phase
+----------------------+
The Servlet life cycle is similar to the JSP life cycle in terms of phases, but the main difference is that
JSP pages are first converted into Servlets and then the Servlet life cycle is invoked. Below is the life
cycle of a Servlet in detail.
+-----------------------+
| 1. Request Arrives |
+-----------------------+
|
v
+-----------------------+
| 2. Loading & Instantiation |
+-----------------------+
|
v
+-----------------------+
| 3. init() method | ---> Initialization Phase
+-----------------------+
|
v
+-----------------------+
| 4. service() method | ---> Request Handling Phase
+-----------------------+
|
v
+-----------------------+
| 5. destroy() method | ---> Destruction Phase
+-----------------------+
Conclusion
The life cycle of JSP starts with translating the JSP into a Servlet, followed by initialization,
request handling, and destruction. The life cycle phases of a JSP are managed by the web
container, and JSP pages are typically converted into servlets for request processing.
The life cycle of a Servlet involves loading, initialization, request handling, and destruction
phases, all of which are managed by the servlet container.
Both the JSP and Servlet life cycles are designed to ensure efficient handling of client requests and
resource management.
A program in JSP to show incorporation of static and dynamic content simultaneously in a web
page:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<p>This is a simple web page with both static and dynamic content.</p>
<hr>
<!-- Dynamic Content: Using JSP Expressions -->
<%
%>
<hr>
<%
%>
<ul>
<%
%>
</ul>
<hr>
<footer>
<p>Generated by JSP Application.</p>
</footer>
</body>
</html>
Expected Output:
When this JSP page is requested, the output in the web browser will look something like this:
This is a simple web page with both static and dynamic content.
Apple
Banana
Cherry
Date
Elderberry
Q9. Explain the life cycle of thread in detail and write source code to demonstrate the thread life
cycle.
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
(1) New: Whenever a new thread is created, it is always in the new state. For a thread in the new state,
the code has not been run yet and thus has not begun its execution.
(2) 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.
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.
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.
(3) Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either
the thread is in the blocked state or is in the waiting state.
(4) 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.
(5)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.
try {
e.printStackTrace();
try {
} catch (InterruptedException e) {
e.printStackTrace();
Multithreading is a programming concept where multiple threads are executed concurrently within a
program. A thread is the smallest unit of a CPU's execution. Multithreading allows a CPU to execute
multiple threads simultaneously, improving the efficiency of a program by making better use of system
resources.
In a single-threaded program, the CPU executes one task at a time. But in a multithreaded program,
multiple tasks (threads) can be executed at the same time. This is particularly useful in scenarios where
tasks are independent of each other and can be performed concurrently, such as handling multiple user
requests, performing background operations, or managing several tasks in parallel.
Benefits of Multithreading:
1. Better CPU Utilization: Multithreading helps in utilizing the CPU more effectively, especially in
multi-core processors, where threads can run in parallel.
2. Responsiveness: In GUI applications, multithreading ensures that the user interface remains
responsive while performing background tasks (e.g., file download or data processing).
3. Faster Execution: For certain problems, dividing a task into smaller subtasks and running them
concurrently can result in faster execution time.
Consider an example where we want to print numbers and letters at the same time. We can create two
threads: one that prints numbers and another that prints letters.
Code Example:
class NumberThread extends Thread {
public void run() {
// Print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
try {
Thread.sleep(500); // Sleep for 0.5 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Number: 1
Letter: A
Number: 2
Letter: B
Number: 3
Letter: C
Number: 4
Letter: D
Number: 5
Letter: E
When we call start() on a thread, it enters the Runnable state. The thread scheduler decides
when the thread actually starts executing.
Both threads (number and letter) are running concurrently, and they "interleave" their execution.
However, you cannot control exactly which thread runs first, as it depends on the thread
scheduler of the operating system.
The sleep() method in each thread causes the thread to pause for a specified period, allowing the
other thread to execute.
Types of Threads:
1. User Threads: These are threads that perform a specific task, like the NumberThread and
LetterThread in our example.
2. Daemon Threads: These are background threads that don't prevent the JVM from exiting. For
example, the garbage collection thread in Java is a daemon thread.
Thread Synchronization:
While multithreading is a powerful tool, it also comes with challenges, especially when multiple threads
access shared resources (such as variables or objects). In such cases, synchronization is necessary
to prevent data inconsistency or corruption. You can use synchronized blocks or methods to ensure that
only one thread accesses a resource at a time.
Conclusion:
Multithreading in Java allows for the efficient execution of multiple tasks concurrently. This is useful for
improving performance, responsiveness, and the overall user experience in many applications,
particularly in systems that perform tasks like file handling, networking, or processing large datasets.
The example provided demonstrates how two threads can execute in parallel, each performing a
different task.
(a) repaint()
(b) Applet
(c) J2EE
(d) RMI
How it works:
o The repaint() method doesn't directly paint the component; instead, it schedules a request
to the system to call the component's paint() method. The paint() method is where the
actual drawing or updating of the component happens.
o The repaint() method calls the paint() method asynchronously, typically after a short delay,
to ensure smooth graphics rendering.
o It can be used in a variety of scenarios, such as when you need to update the display of
graphics or when the state of the user interface changes and requires a refresh.
Example: In a custom JPanel, if you change the state and want to update the display, you might
call repaint().
int x = 50;
int y = 50;
@Override
super.paint(g);
An Applet is a small Java program that runs within a web browser or an applet viewer, typically
embedded in an HTML page. Applets were a popular way to create interactive applications that run on
the client side, like games, calculators, or animations. They were commonly used in the late 1990s and
early 2000s but have since been largely replaced by more modern technologies like JavaScript, HTML5,
and CSS3 due to security and compatibility issues.
Life Cycle:
o init(): Called when the applet is first loaded into memory. It is used to initialize the applet.
o start(): Called after the applet is loaded or whenever the applet is brought to the
foreground.
o paint(): Used to display content in the applet's window. It is called whenever the applet
needs to be redrawn.
ostop(): Called when the applet is no longer visible or when the browser navigates away
from the page containing the applet.
o destroy(): Called when the applet is about to be unloaded from memory.
Example: A simple applet that displays a message:
import java.applet.Applet;
import java.awt.Graphics;
Q12. What do you mean by Java Socket Programming? Explain TCP/IP client socket and TCP/IP
server socket.
Java Socket Programming refers to the use of Java classes to enable communication between
applications over a network using sockets. A socket is an endpoint for sending or receiving data across
a network, and it allows two machines or processes to communicate with each other.
Java provides a rich set of libraries in the java.net package to facilitate networking tasks such as:
Client: The application that initiates the communication by connecting to the server.
Server: The application that waits for incoming requests from clients and processes those
requests.
A TCP client socket is used by a client application to send data to a server over a TCP/IP connection.
It establishes a connection to the server by providing the server's IP address and port number.
Key Steps:
Create a Socket: A client creates a Socket object that represents the client-side endpoint of the
communication.
Connect to the Server: The client uses the server's IP address and port number to establish a
connection.
Send/Receive Data: After establishing the connection, the client can send or receive data using
input and output streams.
Close the Socket: Once the communication is complete, the client can close the socket to
release resources.
InputStream is = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String response = reader.readLine(); // Read server response
System.out.println("Server says: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
A TCP server socket is used by a server application to listen for incoming client requests. It creates a
server-side socket, listens for connections, and accepts incoming client connections.
Key Steps:
Create a ServerSocket: The server creates a ServerSocket object that listens for incoming client
connections on a specific port.
Wait for Client Connections: The server uses the accept() method to wait for client
connections.
Communicate with Client: Once a client connects, the server can send and receive data
through input and output streams.
Close the ServerSocket: After communication is completed, the server can close the
ServerSocket to release the resources.
OutputStream os = clientSocket.getOutputStream();
PrintWriter writer = new PrintWriter(os, true);
writer.println("Hello, Client! I received your message."); // Send a response to the client
} catch (IOException e) {
e.printStackTrace();
}
}
}
1. Client-Side:
o The client creates a socket connection to the server's IP address and port.
o It sends a message to the server and waits for a response.
o Once the communication is complete, the client closes the socket.
2. Server-Side:
o The server listens for client requests on a specific port using a ServerSocket.
o When a client connects, the server accepts the connection and establishes a
communication channel through a Socket.
o The server reads data from the client, processes it, and sends a response back.
o After communication, the server closes the client connection.
+-------------------+ +--------------------+
| TCP Client | | TCP Server |
+-------------------+ +--------------------+
| 1. Create Socket | ----(Request)--------> | 1. Create ServerSocket|
| 2. Connect to Server| | 2. Wait for Client |
| 3. Send Data | <----(Response)-------| 3. Accept Client |
| 4. Receive Data | | 4. Communicate with Client|
| 5. Close Connection | | 5. Close Client Socket |
+-------------------+ +--------------------+
Conclusion
Java Socket Programming enables communication between client and server over a network. The
TCP/IP protocol is one of the most commonly used methods for creating reliable, connection-oriented
communication.
TCP Client Socket: The client connects to a server, sends data, and receives responses.
TCP Server Socket: The server listens for incoming client connections, processes requests, and
sends responses back to clients.
The examples demonstrate basic client-server communication, but real-world applications often involve
more complex features, such as handling multiple clients, error handling, timeouts, and other advanced
networking concepts.
----------------------------------------------------------------------------------------------------------------------------- -----------
2022
Ans: A thread is a lightweight process, the smallest unit of execution within a program. Threads allow
for concurrent execution, enabling multiple tasks to be performed simultaneously, which is especially
useful in multi-core systems. Each thread has its own execution context, such as a program counter,
registers, and a stack, but they share the same memory space, making communication between
threads relatively easier compared to processes.
1. User Thread
2. Daemon Thread
1. User Thread
A User Thread is the standard thread type in Java. These threads are created by the user (i.e., the
programmer) and are responsible for executing the main tasks of an application. The Java Virtual
Machine (JVM) keeps running the program as long as there is at least one user thread active. Once all
user threads have finished executing, the program terminates.
Example:
In this example, MyThread is a user thread that prints a message when it is run.
2. Daemon Thread
A Daemon Thread is a special type of thread that runs in the background and provides services to user
threads. The key difference is that a daemon thread does not prevent the JVM from exiting when all
user threads have completed their execution. Once all user threads terminate, the JVM will
automatically terminate daemon threads. These threads are usually used for background tasks like
garbage collection, monitoring, etc.
Example:
In this example, MyDaemonThread runs in the background, but the JVM will terminate once the main
thread completes its execution, even if the daemon thread is still running.
Threads are a crucial part of multithreading in Java, enabling programs to perform tasks concurrently
and efficiently. The choice of using user or daemon threads depends on the nature of the task at hand.
Q3. What is Abstract Class? Write a program to define “arithmetic” abstract class to perform
arithmetic operation.
Ans: An abstract class in Java acts as a partially implemented class that itself cannot be instantiated.
An abstract class is declared using the “abstract” keyword in its class definition. It exists only for
subclassing purposes, and provides a template for its subcategories to follow. Abstract classes can
have implementations with abstract methods. Abstract methods are declared to have no body, leaving
their implementation to subclasses.
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Error: Division by zero
Division by zero: NaN
Q4. Write a program in java to count number of vowel and consonents in the given sentence
without library function.
Ans: program in java to count number of vowel and consonents in the given sentence without library
function:
import java.util.Scanner;
int vowelCount = 0;
int consonantCount = 0;
char ch = sentence.charAt(i);
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
ch = Character.toLowerCase(ch);
// Check if the character is a vowel
vowelCount++;
} else {
consonantCount++;
Output:
Number of vowels: 3
Number of consonants: 7
Q5. Create an Applet program to draw a circle and write hello, world inside the circle.
Ans: Applet program to draw a circle and write hello, world inside the circle is:
import java.applet.Applet;
import java.awt.Graphics;
@Override
g.setColor(java.awt.Color.BLUE);
// Draw a circle with center at (150, 100), width and height 200
g.setColor(java.awt.Color.RED);
<html>
<body>
</applet>
</body>
</html>
Q6. What is Constructor? How super keyword inherits the constructor in subclass?
Ans: A constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.
There are following rules for defining a constructor:
Syntax:
<class_name>(){}
2. Parameterized Constructor:- A constructor which has a specific number of parameters is called a
parameterized constructor.
In Java, the super keyword is used to refer to the parent class (superclass) and can be used in various
contexts such as:
When it comes to constructors, the super keyword is used to invoke the constructor of the
superclass from the subclass. However, constructors in Java are not inherited by subclasses. This
means that a subclass does not automatically inherit the constructor of its superclass. Instead, the
subclass must call the superclass constructor using super().
Example:
class Animal {
// Superclass constructor
Animal() {
System.out.println("Animal constructor called");
}
Output:
Q7. What is Final keyword? Write use of final keyword with suitable example.
Ans: The final keyword in Java is used to define constants, prevent method overriding, and prevent
inheritance of classes. It can be applied to variables, methods, and classes, and it enforces immutability
or restrictions in certain areas of a program.
1. Final Variable
When a variable is declared as final, its value cannot be changed once assigned. It must be initialized at
the time of declaration or inside the constructor (for instance variables).
2. Final Method
A final method cannot be overridden by any subclass. This is useful when you want to ensure that a
method in the superclass cannot be modified in subclasses.
System.out.println("Animal is speaking");
// public void speak() { // Error: Cannot override the final method from Animal
// System.out.println("Dog is barking");
// }
3. Final Class
A final class cannot be subclassed (inherited). This is used to prevent inheritance for certain classes to
maintain security or prevent unwanted modifications.
System.out.println("Vehicle class");
// System.out.println("Car class");
// }
// }
Ans: Polymorphism is one of the four core concepts of Object-Oriented Programming (OOP), the
other three being Encapsulation, Inheritance, and Abstraction. The term "polymorphism" comes
from the Greek words poly (meaning "many") and morph (meaning "forms"). In simple terms,
polymorphism allows objects to behave in different ways depending on their data type or class.
In Java, polymorphism is the ability for different classes to respond to the same method call in a way
that is specific to the type of object that invokes the method. In Java, polymorphism is primarily
achieved through method overriding and method overloading.
Output:
Sum of 2 integers: 30
Sum of 3 integers: 60
Sum of 2 doubles: 31.0
In Java, run-time polymorphism is based on the reference type of the variable, not the object type. This
means the method that is called depends on the actual object type (not the reference type).
// Subclass Dog
class Dog extends Animal {
// Method overriding in subclass
@Override
public void sound() {
System.out.println("Dog barks");
}
}
// Subclass Cat
class Cat extends Animal {
// Method overriding in subclass
@Override
public void sound() {
System.out.println("Cat meows");
}
}
Output:
Dog barks
Cat meows
Advantages of Polymorphism
1. Code Reusability: Polymorphism allows a single method to be used in different ways, promoting
code reusability.
2. Maintainability: It makes the code easier to maintain and extend, as new methods or classes
can be added without changing existing code.
3. Flexibility: It allows you to write more flexible code that works with objects of different types in a
unified way.
Conclusion
Polymorphism enables one interface to be used for different types of actions. The two primary
types of polymorphism in Java are:
1. Compile-time polymorphism (method overloading).
2. Run-time polymorphism (method overriding).
Both types are essential to achieve the dynamic behavior and flexibility in Java programs.
Through polymorphism, Java provides the capability to write more generic and reusable code,
which can handle objects of different types in a unified manner.
Q9. What is Interface? Write types of interface with structure and example.
Ans: An interface is a reference type, similar to a class, that can contain only constants, method
signatures, default methods, static methods, and nested types. It cannot contain instance fields
or constructors. Interfaces are used to specify a set of methods that a class must implement,
without providing the method implementations themselves.
An interface defines a contract for what a class can do, but not how it does it. When a class
implements an interface, it must provide concrete implementations for all of the methods declared in the
interface (unless the class is abstract).
Features of an Interface:
1. Methods in an Interface: By default, all methods in an interface are abstract (i.e., no body), but
since Java 8, interfaces can also contain default methods (methods with a body).
2. Constant Variables: All variables declared in an interface are implicitly public, static, and final
(i.e., constants).
3. Multiple Inheritance: A class can implement multiple interfaces, making it a form of multiple
inheritance (which is not possible with classes alone).
4. Cannot instantiate an Interface: You cannot create an object of an interface directly. Instead, a
class implements the interface and creates an object of that class.
1. Regular Interface
2. Default Interface
3. Static Interface
4. Functional Interface
A regular interface contains only abstract methods, which need to be implemented by the class that
implements the interface.
void eat();
}
The interface Animal declares two abstract methods: sound() and eat().
The class Dog implements the interface Animal and provides implementations for both methods.
A default interface method can have a body and provides a default implementation. This was introduced
in Java 8 to allow adding new methods to interfaces without breaking existing implementations.
Structure:
The interface Animal declares one abstract method (sound()) and one default method (sleep()).
The Dog class implements the Animal interface and only provides an implementation for the
sound() method. The default method sleep() is inherited directly from the interface.
In addition to abstract and default methods, Java 8 introduced the ability to define static methods in
interfaces. Static methods in interfaces must have a body, and they are called using the interface name.
Structure:
4. Functional Interface
A functional interface is an interface that contains exactly one abstract method. These interfaces are
used primarily in lambda expressions, method references, and constructor references. The
@FunctionalInterface annotation is used to indicate that an interface is meant to be a functional
interface.
Structure:
The interface Calculator contains a single abstract method add(), making it a functional
interface.
The subtract() method is a default method and is not counted as the abstract method.
In the main() method, a lambda expression (a, b) -> a + b is used to provide an implementation of
the add() method.
Conclusion:
Interfaces in Java play a crucial role in achieving abstraction, modularity, and multiple inheritance.
They allow us to define a contract for your classes, ensuring that certain methods are implemented
while allowing flexibility in the actual implementation. With the introduction of default and static methods
in Java 8, interfaces have become even more powerful and versatile.
Q10. What is exception? Discuss types of Exception handling and methods of Exception.
Ans: An exception in Java is an event that disrupts the normal flow of the program’s execution. It
is an unwanted or unexpected event that arises during the execution of a program, which can
cause the program to terminate abnormally or behave in unintended ways. Exceptions can occur
during various stages of the program, such as input/output operations, network communication,
database interactions, and so on.
In Java, exceptions are represented by instances of the Throwable class and its subclasses. These
exceptions can either be checked (i.e., the programmer must handle them) or unchecked (i.e., they
may or may not be handled).
Java provides a powerful mechanism for handling exceptions, called exception handling, which allows
the program to catch and resolve errors without crashing the program.
1. Checked Exceptions:
o These are exceptions that are checked at compile time. The compiler forces the
programmer to handle them using try-catch blocks or by declaring them in the method
signature using the throws keyword.
o Examples: IOException, SQLException, ClassNotFoundException, etc.
o Characteristics:
Must be handled or declared in the method signature.
Can be anticipated and recovered from.
2. Unchecked Exceptions:
o These are exceptions that occur at runtime and are not checked at compile time. They
are usually caused by logical errors or improper coding practices.
o Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException,
etc.
o Characteristics:
Do not need to be explicitly handled or declared.
Typically represent programming bugs, such as incorrect assumptions, invalid
operations, etc.
3. Errors:
o Errors are typically serious problems that a program cannot handle. They are not
exceptions but are subclasses of Throwable and usually arise due to issues like running
out of memory or problems with the Java Virtual Machine (JVM).
o Examples: OutOfMemoryError, StackOverflowError, etc.
o Characteristics:
Should not be caught or handled by normal exception handling mechanisms.
Usually represent system-level problems.
In Java, exception handling is accomplished using try-catch blocks and related mechanisms. Here's a
breakdown of the core elements of exception handling:
1. try Block:
o Code that might throw an exception is placed inside the try block. If an exception occurs,
the rest of the code inside the try block is skipped, and control is transferred to the
corresponding catch block.
2. catch Block:
o This block catches and handles exceptions thrown by the try block. You can catch specific
types of exceptions or use a general Exception class to catch any exception.
3. finally Block:
o The finally block is always executed, regardless of whether an exception is thrown or not.
It is used for cleanup operations, like closing files, releasing resources, or performing
necessary final actions.
4. throw Statement:
o The throw statement is used to explicitly throw an exception from a method or block of
code.
5. throws Keyword:
o The throws keyword is used in a method signature to declare that the method may throw
exceptions. This is typically used for checked exceptions.
This is the most common way to handle exceptions in Java. The try block contains the code that may
throw an exception, and the catch block catches the exception and handles it.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handling exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// Handling exception of type ExceptionType2
} finally {
// Code that will always execute (optional)
}
Output:
Error: Division by zero.
This block will always execute.
The throws keyword is used in method declarations to specify that a method may throw one or more
exceptions. It’s used with checked exceptions, which must either be handled or declared.
Syntax:
public void method() throws IOException, SQLException {
// Code that might throw IOException or SQLException
}
Example of throws Keyword:
import java.io.*;
Output:
An IOException occurred: File not found: nonexistentfile.txt
The finally block is used to execute important code such as cleanup operations (closing database
connections, file streams, etc.). The code inside the finally block is executed whether an exception
occurs or not.
Output:
Result: 5
Finally block always executes.
Methods of Exception
Java provides several methods in the Throwable class (which is the superclass of Exception and Error)
for working with exceptions:
1. getMessage():
o Returns the detail message (string) of the exception.
2. printStackTrace():
o Prints the stack trace (the method call stack) of the exception to the standard error stream.
3. toString():
o Returns a short description of the exception.
4. getCause():
o Returns the cause of the exception (if any).
5. getStackTrace():
o Returns an array of StackTraceElement objects representing the stack trace.
Output:
Exception message: / by zero
java.lang.ArithmeticException: / by zero
at ExceptionMethodsExample.main(ExceptionMethodsExample.java:4)
Q11. What is Swing? Write any four swing controls with structure and example.
Ans: Swing is a part of Java's Abstract Window Toolkit (AWT), but it is a more powerful
and flexible toolkit for building Graphical User Interfaces (GUIs). Swing provides a
rich set of graphical components such as buttons, text boxes, labels, menus, tables,
and more, which are used to create interactive and visually appealing desktop
applications. Unlike AWT, Swing components are platform-independent because they
do not rely on native OS controls.
Swing is part of the javax.swing package and is built on top of AWT, but provides a more sophisticated
and feature-rich set of components. It also allows for lightweight (pure Java) components, which
makes it more customizable and adaptable than AWT components.
Swing provides a set of pluggable look-and-feels (such as Metal, Nimbus, etc.), which can be used to
customize the appearance of your application.
A JButton is used to create a button that users can click to perform an action.
Structure:
JButton button = new JButton("Button Text");
Example:
import javax.swing.*;
import java.awt.event.*;
// Create a JButton
JButton button = new JButton("Click Me!");
JLabel is used to display a short string or an image on a GUI. It is a non-editable component and cannot
be interacted with directly.
Structure:
JLabel label = new JLabel("Label Text");
Example:
import javax.swing.*;
// Create a JLabel
JLabel label = new JLabel("Hello, Swing!");
Structure:
JTextField textField = new JTextField("Default Text");
Example:
import javax.swing.*;
// Create a JTextField
JTextField textField = new JTextField("Enter your name here");
JComboBox is a drop-down list that allows the user to select from a list of items.
Structure:
JComboBox<String> comboBox = new JComboBox<>(new String[] {"Option 1", "Option 2", "Option 3"});
Example:
import javax.swing.*;
// Create a JComboBox
JComboBox<String> comboBox = new JComboBox<>(new String[] {"Option 1", "Option 2", "Option
3"});
Conclusion:
Swing is a versatile and rich GUI toolkit that provides a wide range of components to create user-
friendly desktop applications in Java. The examples above demonstrate the basic usage of four
commonly used Swing controls—JButton, JLabel, JTextField, and JComboBox—that allow developers
to interact with the user in various ways. These components are fundamental for building sophisticated,
cross-platform graphical user interfaces in Java.