Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
40 views36 pages

Java PDF

Uploaded by

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

Java PDF

Uploaded by

abhasmitaraul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

QUESTION-

Q-1. ) What is compile time polymorphism and its importance? Use the compile time
polymorphism in a Java program to create the objects.

Q-2= Discuss method loading and overriding with example in Java.

Q3- What is byte code in JVM?

Q4- What do you know to be multithreading?

Q4- Compare Swing API and AWT API.

Q-5. Differentiate any character stream classes in Java.

Q-6 Differentiate between String, StringBuffer, and StringBuilder.?

Q-7 Explain multi catch statement with an example.

Q-8.How can we make a thread to wait for specific time?

Q-9- Differentiate between Panel and Frame with example.

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.

Q-17- What is the Java Collections Framework?

Q19- comparison between Iterator and ListIterator in Java:

Q20- 5.Here's a simple Java program that demonstrates reading from and writing to a text file
using FileWriter and FileReader:

Q21- What is Serialization in Java?

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.

Q-25- Discuss method loading and overriding with example in Java.

Method Overloading:

Q26-Interface Inheritance and Polymorphism

Q27- Checked vs Unchecked Exceptions

Q-28: Event Delegation Model

Q-29- Applet Lifecycle

Q-30 Explain throws, throw, final, finally, finalize.

Q31- a Describe the different levels of access protection available in Java

ANSWER=--------------------------------------------------------------------------------------------------------------

Q-1. ) What is compile time polymorphism and its importance? Use the compile time
polymorphism in a Java program to create the objects.

✅ Q1: What is Compile Time Polymorphism and Its Importance?

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.

✅ Importance of Compile Time Polymorphism

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 {

int add(int a, int b) {

return a + b;--54

int add(int a, int b, int c) {

return a + b + c;

double add(double a, double b) {


return a + b;

}public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator();

System.out.println("Sum of 2 and 3: " + calc.add(2, 3));

System.out.println("Sum of 2, 3 and 4: " + calc.add(2, 3, 4));

System.out.println("Sum of 2.5 and 3.5: " + calc.add(2.5, 3.5));

Q-2= Discuss method loading and overriding with example in Java.

🔹 1. Method Overloading (Compile-Time Polymorphism)

Definition:
Method overloading occurs within the same class when multiple methods have the same name
but different parameter lists (number, type, or both).

✅ Characteristics:

 Happens at compile time

 Increases code readability and reusability

 No need for inheritance

✅ Example of Method Overloading:

class Printer {

void print(String text) {

System.out.println("Printing text: " + text);

} void print(int number) {

System.out.println("Printing number: " + number);

} void print(String text, int number) {

System.out.println("Printing: " + text + " and " + number);

public class OverloadExample {

public static void main(String[] args) {


Printer printer = new Printer();

printer.print(123);

printer.print("Page", 5);

}
2-MARK

Q3- What is byte code in JVM?

Bytecode is an intermediate, platform-independent code generated by the Java compiler (javac)


from Java source code (.java files). It's essentially a set of instructions that the Java Virtual
Machine (JVM) can understand and execute. When you compile a Java program, it doesn't get
converted directly into machine code for a specific operating system and processor. Instead, it's
compiled into bytecode (.class files). This bytecode is then interpreted and executed by the JVM,
which acts as an abstraction layer between the Java program and the underlying
hardware/operating system. This "write once, run anywhere" capability is a core advantage of
Java, as the same bytecode can run on any platform for which a compatible JVM is available.

Q4- What do you know to be multithreading?

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.

Q4- Compare Swing API and AWT API.

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.

Q-5. Differentiate any character stream classes in Java.

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.

Q-6 Differentiate between String, StringBuffer, and StringBuilder.?

Feature String StringBuffer StringBuilder Mutability Immutable (cannot be changed after


creation). Mutable (can be changed after creation). Mutable (can be changed after creation).
Thread-Safety Thread-safe (as it's immutable, no synchronization issues). Thread-safe (methods
are synchronized). Not thread-safe (methods are not synchronized). Performance Less efficient
for repeated modifications (creates new objects). Slower than StringBuilder due to
synchronization overhead. Faster than StringBuffer (no synchronization overhead). Usage Ideal for
fixed, constant text. Preferred for multi-threaded environments where string modifications are
frequent. Preferred for single-threaded environments where string modifications are frequent.
Concatenation Uses + operator, concat() method (creates new String). Uses append(), insert()
methods (modifies existing object).

Q-7 Explain multi catch statement with an example.

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;

public class MultiCatchExample {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

try {

System.out.print("Enter an integer: ");

int num1 = scanner.nextInt();

System.out.print("Enter another integer: ");

int num2 = scanner.nextInt();

int result = num1 / num2;

System.out.println("Result: " + result);


String text = null;

System.out.println(text.length()); // This will cause NullPointerException

} catch (InputMismatchException | ArithmeticException | NullPointerException e) {

// This single catch block handles multiple exception types

System.err.println("An error occurred: " + e.getMessage());

if (e instanceof InputMismatchException) {

System.err.println("Please enter valid integer input.");

} else if (e instanceof ArithmeticException) {

System.err.println("Cannot divide by zero.");

} else if (e instanceof NullPointerException) {

System.err.println("A null reference was accessed unexpectedly.");

} finally {

scanner.close();

Q-8.How can we make a thread to wait for specific time?

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)

Thread.sleep(long milliseconds, int nanoseconds)

Example:

public void run() {

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

System.out.println(Thread.currentThread().getName() + ": " + i);

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println(Thread.currentThread().getName() + " was interrupted.");


Thread.currentThread().interrupt(); // Restore the interrupted status

public static void main(String[] args) {

SleepExample thread1 = new SleepExample();

thread1.setName("MyThread");

thread1.start();

System.out.println("Main thread continues...");

public void run() {

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

System.out.println(Thread.currentThread().getName() + ": " + i);

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println(Thread.currentThread().getName() + " was interrupted.");

Thread.currentThread().interrupt(); // Restore the interrupted status

public static void main(String[] args) {

SleepExample thread1 = new SleepExample();

thread1.setName("MyThread");

thread1.start();

System.out.println("Main thread continues...");

Q-9- Differentiate between Panel and Frame with example.


Feature Panel Frame Purpose A container for other GUI components; cannot be a top-level
window. A top-level, independent window that can contain other components. Border Does not
have a title bar, borders, or menu bars by default. Has a title bar, borders, resize corners,
minimize/maximize/close buttons. Top-Level Not a top-level container; must be placed inside
another container (like a Frame or another Panel). A top-level container; can exist independently.
Visibility Not directly visible on its own; serves as a grouping mechanism. Directly visible as a
distinct window on the screen. Window Events Doesn't generate window events (like closing,
minimizing). Generates window events. Adding Components Components are added directly to
the Panel. Components are typically added to its content pane. Example JPanel (Swing), Panel
(AWT) JFrame (Swing), Frame (AWT)

Example (Swing):

import javax.swing.*;

import java.awt.*;

public class FrameAndPanelExample {

public static void main(String[] args) {

JFrame frame = new JFrame("My Application Window");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 300);

frame.setLayout(new BorderLayout()); // Use a layout manager for the frame

JPanel panel1 = new JPanel();

panel1.setBackground(Color.LIGHT_GRAY);

panel1.setBorder(BorderFactory.createTitledBorder("Panel 1")); // Add a border for visibility

panel1.add(new JButton("Click Me!"));

panel1.add(new JTextField("Hello", 10));

JPanel panel2 = new JPanel();

panel2.setBackground(Color.ORANGE);

panel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));

panel2.add(new JLabel("Enter Name:"));

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:

\text{Area} = \pi \times \text{radius}^2

Here is the complete Java program:

import java.util.Scanner;

public class CircleArea {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the radius of the circle: ");

double radius = scanner.nextDouble();

double area = Math.PI * radius * radius;

System.out.println("The area of the circle is: " + area);

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:

abstract class Animal {

abstract void sound(); // Abstract method

void eat() {

System.out.println("This animal eats food.");

Purpose in Object-Oriented Programming (OOP):

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:

abstract class Animal {

abstract void sound();

void sleep() {

System.out.println("Sleeping...");

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

public class Test {

public static void main(String[] args) {

Animal a = new Dog();

a.sound();

a.sleep();

Q12- Discuss the concept of multithreading in Java. Explain the advantages and challenges
of multithreading.

Multithreading in Java is a programming concept where multiple threads (smaller units of a


process) run concurrently, sharing the same memory space. Java provides built-in support for
multithreading, making it easy to perform multiple tasks simultaneously and improve
performance. Key Concepts: Thread: A lightweight subprocess, the smallest unit of processing.
Main Thread: The initial thread started by the JVM. Thread Class: Used to create threads by
extending it. Runnable Interface: Used to create threads by implementing it. Example- 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:

abstract class Animal {


abstract void sound(); // Abstract method

void eat() {
System.out.println("This animal eats food.");
}
}

Purpose in Object-Oriented Programming (OOP):

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:

abstract class Animal {


abstract void sound();
void sleep() {
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
a.sleep();
}
}
Advantages of Multithreading:
1. Improved Performance: Multiple threads run concurrently, enhancing speed.
2. Resource Sharing: Threads share the same memory space, reducing overhead.
3. Better CPU Utilization: Threads keep the CPU busy, maximizing use.
4. Responsive Applications: Helps in building responsive GUIs and real-time systems.
5. Asynchronous Behavior: Allows background tasks like file loading or network calls.
Challenges of Multithreading:
1. Complexity: Writing and managing multithreaded code can be complicated.
2. Synchronization Issues: Access to shared resources must be carefully synchronized to
avoid conflicts.
3. Deadlocks: Improper handling of locks can lead to deadlocks.
4. Debugging Difficulty: Errors are harder to trace due to concurrent executions.
5. Overhead: Excessive thread creation can lead to performance issues.
Q13- Explain the AWT class hierarchy in Java and discuss the role of different container
classes.

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.

AWT Class Hierarchy Overview:

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.

Example using WindowAdapter:

import java.awt.*;

import java.awt.event.*;

public class AdapterExample {

public static void main(String[] args) {

Frame f = new Frame("Adapter Class Example");

f.setSize(300, 200);

f.setVisible(true);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

f.dispose(); // Close the window

});

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.

Significance of Constructors in Java:

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.

Default Constructor: Takes no parameters.


Parameterized Constructor: Accepts arguments to initialize the object with custom values.

Constructors do not have a return type, not even void, and their name must match the class name.

Significance of Methods in Java:

Methods define the behavior of objects. They are blocks of code that perform specific tasks.
Methods help:

Encapsulate logic.

Reuse code.

Organize complex programs into manageable sections.

Java Class Example:

public class UserProfile {

String name;

int age;

public UserProfile() {

name = "Unknown";

age = 0;

public UserProfile(String userName, int userAge) {

name = userName;

age = userAge;

public void displayProfile() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

public void checkAdult() {

if (age >= 18) {

System.out.println(name + " is an adult.");

} else {

System.out.println(name + " is not an adult.");

}
public static void main(String[] args) {

UserProfile user1 = new UserProfile();

user1.displayProfile();

user1.checkAdult();

System.out.println("----------");

UserProfile user2 = new UserProfile("Alice", 22);

user2.displayProfile();

user2.checkAdult();

Q-15 Write Java program that demonstrates method overloading, method overriding, and
dynamic method dispatch:

class Animal {

void sound() {

System.out.println("Animal makes a sound");

void info() {

System.out.println("This is an animal.");

void info(String type) {

System.out.println("This is a " + type + ".");

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

void info(String type, int age) {

System.out.println("This is a " + type + " and it is " + age + " years old.");

}
}

public class Main {

public static void main(String[] args) {

Animal a = new Animal();

a.info();

a.info("Mammal");

Animal ref; // superclass reference

Dog d = new Dog(); // subclass object

ref = d; // dynamic dispatch

ref.sound(); // calls Dog's overridden method at runtime

d.info("Dog", 5);

Q-16- Implement comprehensive Java application using AWT that demonstrates an


interactive user interface with buttons, labels, text fields, and menus.

Java Code Using AWT Components

import java.awt.*;

import java.awt.event.*;

public class AWTInterfaceExample extends Frame implements ActionListener {

TextField textField;

Label label;

Button button;

MenuBar menuBar;

Menu menu;

MenuItem menuItemExit;

public AWTInterfaceExample() {

setTitle("AWT UI Example");

label = new Label("Enter your name:");

label.setBounds(50, 100, 150, 20);


add(label);

textField = new TextField();

textField.setBounds(200, 100, 150, 20);

add(textField);

button = new Button("Click Me");

button.setBounds(200, 150, 80, 30);

button.addActionListener(this);

add(button);

menuBar = new MenuBar();

menu = new Menu("File");

menuItemExit = new MenuItem("Exit");

menuItemExit.addActionListener(e -> System.exit(0));

menu.add(menuItemExit);

menuBar.add(menu);

setMenuBar(menuBar);

setSize(400, 300);

setLayout(null);

setVisible(true);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

dispose();

});

public void actionPerformed(ActionEvent e) {

label.setText("Hello, " + textField.getText() + "!");

public static void main(String[] args) {

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.

1. Comparison Between Swing and AWT Components


Java provides two primary libraries for creating Graphical User Interfaces (GUIs): AWT (Abstract
Window Toolkit) and Swing. While both are used for developing windows-based applications,
they have distinct differences in architecture, capabilities, and usage. 1.1 AWT (Abstract Window
Toolkit) AWT is Java’s original platform-dependent GUI toolkit that uses the native GUI
components of the operating system. It provides basic building blocks such as buttons, labels,
text fields, etc. Heavyweight Components: AWT relies on native code, meaning each AWT
component is linked to a native GUI component (e.g., a Button in AWT corresponds to an OS
button). Platform Dependent: GUI appearance can vary across operating systems. Limited Set of
Components: Fewer GUI components and layout options. Performance: Slightly faster because it
uses native OS resources. Customization: Limited due to native dependency. 1.2 Swing Swing is a
part of the Java Foundation Classes (JFC) and is built on top of AWT. It provides a rich set of GUI
components and is entirely written in Java. Lightweight Components: Do not depend on the
native GUI; instead, they are rendered by Java itself. Platform Independent: Swing applications
have a consistent look and feel across all platforms. Rich Set of Components: Offers advanced
components such as tables (JTable), trees (JTree), and tabbed panes (JTabbedPane).
Customizable: Developers can change appearance using "Look and Feel" settings. Extensible:
Easier to extend and customize components. 1.3 Comparison Table ---
2. Swing-Based Application Implementation
Below is a simple Java application that uses Swing components and containers to create an
intuitive and user-friendly GUI.

import javax.swing.*;

import java.awt.event.*;

public class SwingFormApp {

public static void main(String[] args) {

JFrame frame = new JFrame("User Registration Form");

frame.setSize(400, 300);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();

frame.add(panel);

placeComponents(panel);

frame.setVisible(true);

private static void placeComponents(JPanel panel) {

panel.setLayout(null);

JLabel nameLabel = new JLabel("Name:");


nameLabel.setBounds(10, 20, 80, 25);

panel.add(nameLabel);

JTextField nameText = new JTextField(20);

nameText.setBounds(150, 20, 165, 25);

panel.add(nameText);

JLabel emailLabel = new JLabel("Email:");

emailLabel.setBounds(10, 50, 80, 25);

panel.add(emailLabel);

JTextField emailText = new JTextField(20);

emailText.setBounds(150, 50, 165, 25);

panel.add(emailText);

JLabel genderLabel = new JLabel("Gender:");

genderLabel.setBounds(10, 80, 80, 25);

panel.add(genderLabel);

JRadioButton male = new JRadioButton("Male");

male.setBounds(150, 80, 70, 25);

panel.add(male);

JRadioButton female = new JRadioButton("Female");

female.setBounds(230, 80, 100, 25);

panel.add(female);

ButtonGroup genderGroup = new ButtonGroup();

genderGroup.add(male);

genderGroup.add(female);

JButton submitButton = new JButton("Submit");

submitButton.setBounds(150, 120, 100, 25);

panel.add(submitButton);

submitButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String name = nameText.getText();

String email = emailText.getText();


String gender = male.isSelected() ? "Male" : female.isSelected() ? "Female" :
"Unspecified";

JOptionPane.showMessageDialog(panel,

"Name: " + name + "\nEmail: " + email + "\nGender: " + gender,

"User Details",

JOptionPane.INFORMATION_MESSAGE);

});

Q-17- What is the Java Collections Framework?

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:

ArrayList<String> list = new ArrayList<>();

list.add("A");

list.add("B");

LinkedList<String> linkedList = new LinkedList<>();

linkedList.add("X");

linkedList.add("Y");

HashSet<Integer> set = new HashSet<>();


set.add(10);

set.add(20);

HashMap<Integer, String> map = new HashMap<>();

map.put(1, "Apple");

map.put(2, "Banana");

Q-18- 3 use of Generics in Java?

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.

Why Generics Are Important:


1. Type Safety:
Generics ensure that you only use the correct type of objects. This avoids runtime
ClassCastException.
2. Code Reusability:
One generic class/method can work with different data types.
3. Elimination of Type Casting:
You don't need to cast objects when retrieving them.
4. Compile-time Checking:Errors are caught early during compilation instead of at
runtime.
Example: Generic Class
class Box<T> {
private T value;

public void set(T value) {


this.value = value;
}

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

Interface Location In java.util package In java.util package


Applicable To Works with all Collection types (List, Set, etc.) Works only with
List implementations (e.g., ArrayList)
Traversal Direction Only forward Both forward and backward
Methods for Traversal hasNext(), next() hasNext(), next(),
hasPrevious(), previous()
Add Elements Not supported add() method is available
Replace Elements Not supported set() method is available
Remove Elements remove() method is available remove() method is
available
Get Index Not available nextIndex(), previousIndex() available
Efficiency Lightweight, best for one-direction traversal More powerful,
but slightly heavier
---
Example of Iterator:

Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

Example of ListIterator:

ListIterator<String> lit = list.listIterator();


while (lit.hasNext()) {
System.out.println("Forward: " + lit.next());
}
while (lit.hasPrevious()) {
System.out.println("Backward: " + lit.previous());
}

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).

Java Program: Serialize and Deserialize an Object

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);
}
}

public class SerializationExample {


public static void main(String[] args) {
Student s1 = new Student("Ravi", 22);
String filename = "student.ser";
try (FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(s1);
System.out.println("Object serialized successfully.");
} catch (IOException e) {
e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis)) {
Student s2 = (Student) ois.readObject();
System.out.println("Object deserialized successfully.");
s2.display();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Q22-connect a Java application to a database using JDBC (Java Database Connectivity),


follow these standard steps:
1. Serializable Interface
Purpose: Default serialization mechanism.
Package: java.io.Serializable
Methods: It is a marker interface—it has no methods.
Behavior: The JVM automatically handles the serialization/deserialization process.
Control: Limited control over what and how data is serialized.
Customization: Can use transient keyword to exclude fields from serialization.

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:

1. Load the JDBC Driver


This step registers the JDBC driver with the driver manager.
Class.forName("com.mysql.cj.jdbc.Driver"); // For MySQL
> Modern JDBC drivers may auto-register, but this is still good practice.

2. Establish a Connection
Use DriverManager.getConnection() with the URL, username, and password.
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "root", "password");

3. Create a Statement or PreparedStatement


This object is used to send SQL queries to the database.
Statement stmt = conn.createStatement();
// OR
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id
= ?");

4. Execute the Query


For SELECT queries, use executeQuery().
For INSERT, UPDATE, or DELETE, use executeUpdate().
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
// OR
int rowsAffected = stmt.executeUpdate("UPDATE users SET name='John' WHERE
id=1");

5. Process the Results


Loop through the ResultSet for SELECT queries.
while (rs.next()) {
System.out.println(rs.getInt("id") + ": " + rs.getString("name"));
}

6. Close the Resources


Always close ResultSet, Statement, and Connection to prevent memory leaks.
rs.close();
stmt.close();
conn.close();

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.

What is a synchronized block? A synchronized block in Java is a block of code that is


synchronized on a specified object. It ensures that only one thread at a time can execute the
block of code for the given object lock. --- Syntax: synchronized (lockObject) { // critical section
code } lockObject is the object whose monitor (lock) is used to control access. Only one thread
can hold the lock at a time; others wait. --- Why use synchronized blocks? To prevent race
conditions and ensure thread safety when multiple threads access shared mutable data. More
fine-grained control compared to synchronized methods, as you can synchronize only the critical
part of code. --- Example Scenario: Bank Account Withdrawal Multiple threads trying to withdraw
money from the same account can cause inconsistent balance if not synchronized.
public class BankAccount {
private int balance = 1000;
public void withdraw(int amount) {
synchronized (this) {
if (balance >= amount) {
System.out.println(Thread.currentThread().getName() + " is withdrawing " +
amount);
balance -= amount;
System.out.println("Remaining balance: " + balance);
} else {
System.out.println("Insufficient balance for " +
Thread.currentThread().getName());
}
}
}
}
Q-24-What is complex time polymorphism and its importance? Use the compile time
polymorphism to show the example of object.
Complex Time Polymorphism (Runtime Polymorphism / Dynamic Method Dispatch):
Complex time polymorphism, more commonly known as runtime polymorphism or
dynamic method dispatch, is a fundamental concept in Object-Oriented Programming
(OOP) where the method call resolution (determining which specific method
implementation to execute) happens at runtime rather than at compile time. This is
achieved primarily through method overriding. When a superclass reference variable
holds an object of a subclass, and a method is called on that reference variable, the
actual method executed is determined by the type of the object being referred to, not
the type of the reference variable.

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.

Example of Object in Compile-Time Polymorphism (Method Overloading):


class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
}
Q-25- Discuss method loading and overriding with example in Java.
Method Overloading:

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).

Rules for Method Overloading:

Methods must have the same name.


Methods must have different parameter lists (different number of arguments, different
data types of arguments, or different order of arguments).
Return type and access modifiers can be the same or different.
Example of Method Overloading:
class Printer {
public void print(int num) {
System.out.println("Printing integer: " + num);
}
public void print(String text) {
System.out.println("Printing string: " + text);
}
public void print(int num, String text) {
System.out.println("Printing integer and string: " + num + ", " + text);
}
}
public class OverloadingExample {
public static void main(String[] args) {
Printer printer = new Printer();
printer.print(10);
printer.print("Hello Java!");
printer.print(20, "Overloaded");
}
}
Q26-Interface Inheritance and Polymorphism
public interface Shape {
void draw();
}
public class Circle implements Shape {
public void draw() {
System.out.println("Drawing a circle");
}
}
public class Rectangle implements Shape {
public void draw() {
System.out.println("Drawing a rectangle");
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();
shape1.draw();
shape2.draw();
}
}
Q27- Checked vs Unchecked Exceptions

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()) |
+---------------+

Q-30 Explain throws, throw, final, finally, finalize.


These five keywords/concepts are often confused due to similar spellings but serve
very distinct purposes in Java, primarily related to exception handling and object
lifecycle.
throw (Keyword):
Purpose: Used to explicitly throw an exception object from a method or any block of
code.
Usage: You create an instance of an exception class (which must be a subclass of
Throwable) and then use throw to signal that an exceptional condition has occurred.
throw is followed by an instance of Throwable.
Context: Inside a method where an error condition is detected.
Example:
public void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative.");
}
System.out.println("Age is valid: " + age);
}
throws (Keyword):

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;

// Method to accept coordinates


void getxyvalue(int a, int b) {
x = a;
y = b;
}

// Method to display coordinates


void showxyvalue() {
System.out.println("Coordinates: X = " + x + ", Y = " + y);
}
}

// Subclass Rectangle extending Shape


class Rectangle extends Shape {
int length, breadth;

// Method to set dimensions


void getLengthBreadth(int l, int b) {
length = l;
breadth = b;
}

// Overriding method to display coordinates and dimensions


void showxyvalue() {
// Call the base class method to show coordinates
super.showxyvalue();
// Display rectangle dimensions
System.out.println("Rectangle dimensions: Length = " + length + ", Breadth = " +
breadth);
}
Q-32-Explain how exception handling mechanism can be used in a Java program.
Exception Handling in Java is a mechanism used to handle runtime errors, ensuring normal flow
of program execution. It is achieved using try, catch, throw, throws, and finally blocks. Purpose of
Exception Handling: Prevents program termination when an error occurs. Helps maintain the flow
of execution. Enhances code clarity and robustness. Syntax and Keywords: try: Contains code that
might throw an exception. catch: Handles the exception. finally: Executes code after try/catch,
regardless of exception. throw: Used to explicitly throw an exception. throws: Declares exceptions
in method signature.
Example:

public class ExceptionExample {


public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero is not allowed.");
} finally {
System.out.println("This block always executes.");
}
}
}

Output:

Exception caught: Division by zero is not allowed.


Q33- Write a Java program to implement Runnable class to create a Thread.
In Java, to create a thread using the Runnable interface, you must:
Implement the Runnable interface.
Define the run() method.
Pass the instance to a Thread object.
Java Program

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running using Runnable interface: " +
Thread.currentThread().getName());
}
}
public class RunnableExample {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);

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:

List of Car Names:


Toyota
Honda
Ford
BMW
Tesla

EXPLANATION
ArrayList is used to store car names.

A for-each loop is used to display each name.


Q=35-Write a Java program to display the month names by JList and display the
Days by JComboBox.]

Explanation:

Swing provides JList and JComboBox for displaying lists and dropdowns. JList is used
for displaying month names, and JComboBox for displaying days.

Java Swing Program:

import javax.swing.*;
import java.awt.*;

public class DateDisplay extends JFrame {


public DateDisplay() {
setTitle("Month and Day Display");
setSize(300, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
String[] months = { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" };
JList<String> monthList = new JList<>(months);
monthList.setVisibleRowCount(5);
JScrollPane monthScroll = new JScrollPane(monthList);

// JComboBox for days


String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday" };
JComboBox<String> dayComboBox = new JComboBox<>(days);

add(new JLabel("Select a Month:"));


add(monthScroll);
add(new JLabel("Select a Day:"));
add(dayComboBox);

setVisible(true);
}

public static void main(String[] args) {


new DateDisplay();
}
}
Q-36- Explain the different types of inheritance with schematic diagrams and
examples. Write down a Java program that uses interface to obtain multiple
inheritance.
Types of Inheritance in Java:

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

5. Multiple Inheritance (using Interfaces):


6. A class implements multiple interfaces.
Diagram:
Interface A Interface B
\ /
\ /
Class C

You might also like