Java PDF
Java PDF
Q-1. ) What is compile time polymorphism and its importance? Use the compile time
polymorphism in a Java program to create the objects.
Q 10- Write a Java program that takes user input for the radius of a circle and calculates its area.
Explain the process of user input, variable declaration, and mathematical calculations in your
program.
Q11- Define abstract classes in Java and explain their purpose in object-oriented programming.
Q12- Discuss the concept of multithreading in Java. Explain the advantages and challenges of
multithreading.
Q13- Explain the AWT class hierarchy in Java and discuss the role of different container classes.
Q-14- Discuss the significance of constructors and methods in Java. Develop a Java class that
includes constructors with different parameters and methods that perform user-specific tasks.
Q-15 Write Java program that demonstrates method overloading, method overriding, and dynamic
method dispatch:
Q-16- Implement comprehensive Java application using AWT that demonstrates an interactive user
interface with buttons, labels, text fields, and menus.
Q-16. Compare and contrast Swing components and AWT components in Java. Implement a Swing-
based application that incorporates various Swing controls and containers to create an intuitive
and user-friendly graphical user interface.
Q20- 5.Here's a simple Java program that demonstrates reading from and writing to a text file
using FileWriter and FileReader:
Q22-connect a Java application to a database using JDBC (Java Database Connectivity), follow
these standard steps:
Q-23- Explain how synchronized blocks work. Provide a scenario where they are useful.
Q-24-What is complex time polymorphism and its importance? Use the compile time
polymorphism to show the example of object.
Method Overloading:
ANSWER=--------------------------------------------------------------------------------------------------------------
Q-1. ) What is compile time polymorphism and its importance? Use the compile time
polymorphism in a Java program to create the objects.
Compile Time Polymorphism, also known as method overloading, occurs when multiple methods in
the same class have the same name but different parameters (type, number, or both). The method
that gets called is determined at compile time, based on the method signature.
1. Improves Readability: Methods with the same name indicate similar functionality.
2. Code Reusability: You can use the same method name for different parameter types or
counts.
3. Performance: Since it’s resolved at compile time, it is faster than runtime polymorphism.
4. Simplicity: Makes class d..esign cleaner by avoiding multiple unrelated method names.
Example-
class Calculator {
return a + b;--54
return a + b + c;
Definition:
Method overloading occurs within the same class when multiple methods have the same name
but different parameter lists (number, type, or both).
✅ Characteristics:
class Printer {
printer.print(123);
printer.print("Page", 5);
}
2-MARK
Multithreading is a programming concept that allows a program to execute multiple parts of its
code concurrently. In a multithreaded application, different threads (lightweight sub-processes)
can run independently within the same program, sharing the same memory space and resources.
This allows for better utilization of CPU resources, especially in modern multi-core processors. For
example, a web server might use multithreading to handle multiple client requests
simultaneously, or a graphical user interface (GUI) application might use one thread to handle
user input while another thread performs a time-consuming background task, keeping the UI
responsive. Java provides built-in support for multithreading through the Thread class and the
Runnable interface.
Feature AWT (Abstract Window Toolkit) Swing Nature Heavyweight components; relies on native
OS peers for rendering. Lightweight components; entirely written in Java, doesn't rely on native
peers. Look and Feel Platform-dependent; components look like native OS components.
Platform-independent; supports pluggable look and feel (e.g., Metal, Nimbus, Cross-Platform).
Functionality Provides basic GUI components; limited in functionality. Rich set of sophisticated
components (e.g., JTable, JTree, JSlider, JProgressBar). Performance Can be slower due to relying
on native calls. Generally faster as it renders its own components. Drawing Uses native OS
graphics for drawing. Uses Java2D API for drawing. Resources Consumes more system resources
due to native peers. Consumes fewer system resources. Examples Button, TextField, Frame, Panel
JButton, JTextField, JFrame, JPanel MVC Pattern Doesn't explicitly follow MVC (Model-View-
Controller) pattern. Explicitly follows MVC pattern, separating data from presentation.
Development Older GUI toolkit, less actively developed now. Newer and preferred GUI toolkit,
actively developed.
Character stream classes in Java are primarily designed for handling text data (characters). They
deal with characters using Unicode, making them suitable for internationalized applications. The
base abstract classes for character streams are Reader and Writer. Reader: This is the abstract
superclass for all character input streams. Subclasses like FileReader, BufferedReader,
InputStreamReader, StringReader, etc., are used to read character data from various sources. For
example, FileReader reads characters from a file, and BufferedReader provides buffered reading
for efficiency. Writer: This is the abstract superclass for all character output streams. Subclasses
like FileWriter, BufferedWriter, OutputStreamWriter, PrintWriter, StringWriter, etc., are used to
write character data to various destinations. For example, FileWriter writes characters to a file, and
PrintWriter provides convenient methods for printing formatted text. The key difference from
byte streams is that character streams handle character encoding and decoding automatically,
converting between bytes and characters based on the default or specified character set. This
ensures that text data is handled correctly regardless of the underlying byte representation.
The multi-catch statement (introduced in Java 7) allows you to catch multiple types of exceptions
in a single catch block, provided that the caught exceptions are not in an inheritance hierarchy
(i.e., one is not a subclass of another). This makes the code cleaner, more readable, and reduces
redundancy compared to having separate catch blocks for each exception type that perform the
same action.
Example:
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
try {
if (e instanceof InputMismatchException) {
} finally {
scanner.close();
You can make a thread wait for a specific amount of time using the Thread.sleep() method. This
method causes the currently executing thread to cease execution for a specified number of
milliseconds (and optionally nanoseconds).
Syntax:
Thread.sleep(long milliseconds)
Example:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
thread1.setName("MyThread");
thread1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
thread1.setName("MyThread");
thread1.start();
Example (Swing):
import javax.swing.*;
import java.awt.*;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
panel1.setBackground(Color.LIGHT_GRAY);
panel2.setBackground(Color.ORANGE);
panel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
panel2.add(new JTextField(15));
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.setVisible(true);
}
Q 10- Write a Java program that takes user input for the radius of a circle and calculates its
area. Explain the process of user input, variable declaration, and mathematical calculations
in your program.
To calculate the area of a circle in Java, we follow a few steps: taking input from the user, declaring
necessary variables, and performing the mathematical calculation using the formula:
import java.util.Scanner;
Q11- Define abstract classes in Java and explain their purpose in object-oriented
programming.
An abstract class in Java is a class that cannot be instantiated on its own and may contain abstract
methods (methods without a body) as well as concrete methods (methods with implementations).
It is declared using the keyword abstract.
Syntax:
void eat() {
1. Abstraction:
Abstract classes allow you to define a common blueprint for related classes without providing
complete implementations. This encourages design flexibility and hides complex implementation
details.
2. Code Reusability:
Common code can be implemented in the abstract class and reused by all subclasses.
3. Polymorphism:
Abstract classes allow polymorphic behavior where base class references can point to subclass
objects and invoke overridden methods.
4. Partial Implementation:
It allows the developer to provide a partial implementation while leaving other methods to be
defined by subclasses.
Example:
void sleep() {
System.out.println("Sleeping...");
void sound() {
System.out.println("Dog barks");
a.sound();
a.sleep();
Q12- Discuss the concept of multithreading in Java. Explain the advantages and challenges
of multithreading.
Syntax:
void eat() {
System.out.println("This animal eats food.");
}
}
1. Abstraction:
Abstract classes allow you to define a common blueprint for related classes without providing
complete implementations. This encourages design flexibility and hides complex implementation
details.
2. Code Reusability:
Common code can be implemented in the abstract class and reused by all subclasses.
3. Polymorphism:
Abstract classes allow polymorphic behavior where base class references can point to subclass
objects and invoke overridden methods.
4. Partial Implementation:
It allows the developer to provide a partial implementation while leaving other methods to be
defined by subclasses.
Example:
AWT (Abstract Window Toolkit) is a part of Java's standard library used for building graphical user
interfaces (GUIs). It is a platform-dependent API and relies on native code for rendering
components.
java.lang.Object
└── java.awt.Component
└── java.awt.Container
├── Panel
│ └── Applet
└── Window
├── Frame
└── Dialog
Key Classes:
1. Component: The abstract superclass for all GUI components (e.g., Button, Label,
TextField).
2. Container: A component that can contain other components (e.g., Panel, Frame).
3. Panel: A generic container that groups components together.
4. Applet: A special container for web-based applets (rarely used now).
5. Window: A top-level container without borders or menu bars.
6. Frame: A top-level window with a title and borders.
7. Dialog: A pop-up window for user interaction.
Role of Container Classes: Frame: Used to create main application windows. Panel: Helps organize
components inside containers. Dialog: Used for temporary messages or inputs. Layout Managers:
Containers use layout managers (like BorderLayout, FlowLayout) to manage the positioning of
components. (k) Write a Java program that demonstrates the use of adapter classes in event
handling.
Adapter classes in Java provide empty implementations of listener interfaces, allowing developers
to override only the methods they need.
import java.awt.*;
import java.awt.event.*;
f.setSize(300, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
});
Q-14- Discuss the significance of constructors and methods in Java. Develop a Java class
that includes constructors with different parameters and methods that perform user-
specific tasks.
Constructors are special methods used to initialize objects. When an object is created, the
constructor is called automatically. Constructors help in assigning initial values to instance
variables.
Constructors do not have a return type, not even void, and their name must match the class name.
Methods define the behavior of objects. They are blocks of code that perform specific tasks.
Methods help:
Encapsulate logic.
Reuse code.
String name;
int age;
public UserProfile() {
name = "Unknown";
age = 0;
name = userName;
age = userAge;
} else {
}
public static void main(String[] args) {
user1.displayProfile();
user1.checkAdult();
System.out.println("----------");
user2.displayProfile();
user2.checkAdult();
Q-15 Write Java program that demonstrates method overloading, method overriding, and
dynamic method dispatch:
class Animal {
void sound() {
void info() {
System.out.println("This is an animal.");
void sound() {
System.out.println("Dog barks");
System.out.println("This is a " + type + " and it is " + age + " years old.");
}
}
a.info();
a.info("Mammal");
d.info("Dog", 5);
import java.awt.*;
import java.awt.event.*;
TextField textField;
Label label;
Button button;
MenuBar menuBar;
Menu menu;
MenuItem menuItemExit;
public AWTInterfaceExample() {
setTitle("AWT UI Example");
add(textField);
button.addActionListener(this);
add(button);
menu.add(menuItemExit);
menuBar.add(menu);
setMenuBar(menuBar);
setSize(400, 300);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter() {
dispose();
});
new AWTInterfaceExample();
}
Q-16. Compare and contrast Swing components and AWT components in Java. Implement a
Swing-based application that incorporates various Swing controls and containers to create
an intuitive and user-friendly graphical user interface.
import javax.swing.*;
import java.awt.event.*;
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
panel.setLayout(null);
panel.add(nameLabel);
panel.add(nameText);
panel.add(emailLabel);
panel.add(emailText);
panel.add(genderLabel);
panel.add(male);
panel.add(female);
genderGroup.add(male);
genderGroup.add(female);
panel.add(submitButton);
submitButton.addActionListener(new ActionListener() {
JOptionPane.showMessageDialog(panel,
"User Details",
JOptionPane.INFORMATION_MESSAGE);
});
The Java Collections Framework (JCF) is a unified architecture for representing and manipulating
collections of objects in Java. It provides a set of interfaces (like List, Set, Map) and classes (like
ArrayList, LinkedList, HashSet, HashMap) to store and manage data efficiently.
he Java Collections Framework (JCF) is a unified architecture for representing and manipulating
collections of objects in Java. It provides a set of interfaces (like List, Set, Map) and classes (like
ArrayList, LinkedList, HashSet, HashMap) to store and manage data efficiently. Key benefits of JCF:
Reduces programming effort with reusable data structures. Improves performance through
optimized implementations. Provides interoperability between different data structures. ---
1. Differences between ArrayList, LinkedList, HashSet, and HashMap:
Feature ArrayList LinkedList HashSet HashMap Type List (ordered collection) List (ordered
collection) Set (unordered, unique elements) Map (key-value pairs) Duplicates Allowed Allowed
Not allowed Keys: Not allowed, Values: Allowed Order Maintains insertion order Maintains
insertion order No guaranteed order No guaranteed order Access Time Fast (index-based, O(1))
Slow (O(n)) Fast (O(1) average, O(n) worst) Fast (O(1) average, O(n) worst) Insert/Delete Slower
(shifting needed) Faster (no shifting) Fast (based on hash table) Fast (based on hash table)
Underlying Data Structure Dynamic array Doubly linked list Hash table Hash table Use Case Best
for random access & iteration Best for frequent insert/delete Best for unique elements Best for
key-value storage ---
Examples:
list.add("A");
list.add("B");
linkedList.add("X");
linkedList.add("Y");
set.add(20);
map.put(1, "Apple");
map.put(2, "Banana");
Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces,
and methods. They allow you to write type-safe and reusable code.
public T get() {
return value;
}
}
public class GenericExample {
public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
intBox.set(100);
System.out.println("Integer Value: " + intBox.get());
Box<String> strBox = new Box<>();
strBox.set("Hello Generics");
System.out.println("String Value: " + strBox.get());
}
}
Q19- comparison between Iterator and ListIterator in Java:
Feature Iterator ListIterator
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Example of ListIterator:
Q20- 5.Here's a simple Java program that demonstrates reading from and writing to
a text file using FileWriter and FileReader:
Java Program: Read and Write using FileReader and FileWriter
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadWriteExample {
public static void main(String[] args) {
String filename = "example.txt";
try (FileWriter writer = new FileWriter(filename)) {
writer.write("Hello, this is a sample text file.\n");
writer.write("It demonstrates FileReader and FileWriter in Java.");
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("Error while writing to file: " + e.getMessage());
}
try (FileReader reader = new FileReader(filename)) {
int character;
System.out.println("File content:");
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.out.println("Error while reading from file: " + e.getMessage());
}
}
}
Q21- What is Serialization in Java?
Serialization in Java is the process of converting an object into a byte stream so it
can be saved to a file or transferred over a network.
Deserialization is the reverse process—converting the byte stream back into an
object.
Why Use Serialization?
To persist object state (e.g., saving data to a file).
To transfer objects between JVMs (e.g., in RMI or network communication).
import java.io.*;
class Student implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
Example:
class Student implements Serializable {
int id;
String name;
}
2. Externalizable Interface
Purpose: Gives full control over serialization.
Package: java.io.Externalizable
Methods: You must implement two methods:
writeExternal(ObjectOutput out)
readExternal
To connect a Java application to a database using JDBC (Java Database Connectivity),
follow these standard steps:
2. Establish a Connection
Use DriverManager.getConnection() with the URL, username, and password.
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "root", "password");
Complete Example:
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
System.out.println(rs.getInt("id") + ": " + rs.getString("name"));
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Q-23- Explain how synchronized blocks work. Provide a scenario where they are useful.
Importance:
Flexibility and Extensibility: It allows for writing highly flexible and extensible code.
New subclasses can be added without modifying existing code that uses the superclass
reference.
Decoupling: It decouples the code that calls a method from the specific implementation
of that method. The calling code only needs to know about the superclass interface, not
the specific subclass details.
Code Reusability: Common behavior can be defined in a superclass, and specific
implementations can be provided by subclasses, promoting code reuse.
Achieving Abstraction: It enables abstraction by allowing a general interface (defined by
the superclass) to be used for various specific implementations.
Compile Time Polymorphism (Method Overloading / Static Method Dispatch):
Compile time polymorphism, or static method dispatch, occurs when the method call
resolution happens at compile time. This is primarily achieved through method
overloading, where multiple methods in the same class have the same name but
different parameters (different number, type, or order of arguments). The compiler
determines which overloaded method to call based on the method signature (name +
parameters) at compile time.
Method overloading is a feature in Java that allows a class to have multiple methods
with the same name, provided they have different method signatures. The method
signature includes the method name and the number, type, and order of its parameters.
The return type alone is not sufficient to distinguish overloaded methods. Overloading
is a form of compile-time polymorphism (static polymorphism).
Checked exceptions are exceptions that are checked at compile-time, while unchecked
exceptions are exceptions that are not checked at compile-time.
// Checked exception
public class Main {
public static void main(String[] args) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}
public class Main {
public static void main(String[] args) {
int[] array = new int[5];
System.out.println(array[10]); // Throws ArrayIndexOutOfBoundsException
}
}
Q-28: Event Delegation Model
The Event Delegation Model is a mechanism in Java where events are generated by
components and delegated to listener objects that handle the events. Here's a practical
example:
import java.awt.*;
import java.awt.event.*;
public class EventDelegationExample {
public static void main(String[] args) {
Frame frame = new Frame("Event Delegation Example");
Button button = new Button("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
};
frame.add(button);
frame.setSize(300, 200);
frame.setVisible(true);
Q-29- Applet Lifecycle
Adapter classes in Java are used to simplify event handling by providing a default
implementation of listener interfaces. They help by allowing developers to override
only the methods they need, rather than implementing all methods of the listener
interface.
The lifecycle of an applet includes the following stages:
1. *Initialization*: The applet is initialized by calling the `init()` method.
2. *Start*: The applet starts executing by calling the `start()` method.
3. *Paint*: The applet is painted or repainted by calling the `paint()` method.
4. *Stop*: The applet stops executing by calling the `stop()` method.
5. *Destroy*: The applet is destroyed by calling the `destroy()` method.
Here's a simple diagram:
+---------------+
| Initialize |
| (init()) |
+---------------+
|
|
v
+---------------+
| Start |
| (start()) |
+---------------+
|
|
v
+---------------+
| Paint |
| (paint()) |
+---------------+
|
|
v
+---------------+
| Stop |
| (stop()) |
+---------------+
|
|
v
+---------------+
| Destroy |
| (destroy()) |
+---------------+
Purpose: Used in a method signature to declare that a method might throw one or more
checked exceptions. It informs the calling code that it needs to handle these potential
exceptions.
Usage: Followed by a comma-separated list of exception classes.
throws does not cause an exception to be thrown; it merely indicates that the method
might throw it. The actual throwing still happens using the throw keyword within the
method's body.
Context: In the method signature.
Example:
import java.io.IOException;
import java.io.FileReader;
public class FileProcessor {
public void readFile(String filePath) throws IOException {
FileReader reader = new FileReader(filePath); // This line can throw
FileNotFoundException (an IOException)
reader.close();
}
public static void main(String[] args) {
FileProcessor processor = new FileProcessor();
try {
processor.readFile("non_existent.txt"); // Caller must handle the declared
IOException
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
Q31- a Describe the different levels of access protection available in Java:
In Java, access protection (also called access control or access modifiers) helps manage visibility
and accessibility of classes, methods, and variables. Java supports four types of access levels:
1. Private Access Modifier:
Declared using the private keyword. Members marked private are accessible only within the same
class. They are not visible to subclasses or classes in the same package. Example: private int data;
2. Default (Package-Private) Access Modifier:
When no access modifier is specified, Java applies default access. Default access allows class
members to be accessible within the same package only. This is also known as package-private
access. Example: int data; // default access
3. Protected Access Modifier:
Declared using the protected keyword. Accessible within the same package and also in
subclasses located in different packages. Useful when working with inheritance. Example:
protected int data;
4. Public Access Modifier:
Declared using the public keyword. Members marked public are accessible from any other class
in the Java project, regardless of package. Example: public int data; These modifiers provide
encapsulation and allow a programmer to control how the internal data of a class is accessed and
modified from other classes. b) Explanation and Code: Create a base class called Shape and a
subclass Rectangle using method overriding In Java, inheritance allows a class to inherit
properties and behavior (methods) from another class. The base class (or parent class) provides
basic functionality, and the subclass (or child class) can enhance or modify it using method
overriding. Explanation: Create a base class Shape with two methods: getxyvalue() – to accept
coordinates. showxyvalue() – to display the coordinates. Create a subclass Rectangle that extends
Shape. Add an extra method to accept and display the length and breadth. Override the method
showxyvalue() to include additional details.
// Base class Shape
class Shape {
int x, y;
Output:
t1.start();
t2.start();
}
}
Explanation:
MyRunnable implements Runnable.
Thread objects are created by passing the Runnable instance.
start() runs the run() method in a separate thread.
Q-34 Write a Java program to display the different car names using list object.
Java provides the List interface in the java.util package. We can use ArrayList to store
and display car names.
Java Program:
import java.util.*;
public class CarListExample {
public static void main(String[] args) {
List<String> cars = new ArrayList<>();
cars.add("Toyota");
cars.add("Honda");
cars.add("Ford");
cars.add("BMW");
cars.add("Tesla");
System.out.println("List of Car Names:");
for (String car : cars) {
System.out.println(car);
}
}
}
Output:
EXPLANATION
ArrayList is used to store car names.
Explanation:
Swing provides JList and JComboBox for displaying lists and dropdowns. JList is used
for displaying month names, and JComboBox for displaying days.
import javax.swing.*;
import java.awt.*;
setVisible(true);
}
1. Single Inheritance:
One subclass inherits from one superclass.
Diagram:
A
|
B
2. Multilevel Inheritance:
A class is derived from a class, which is also derived from another class.
Diagram:
A
|
B
|
C
3. Hierarchical Inheritance:
Multiple classes inherit from a single parent class.
Diagram:
A
/\
B C