0% found this document useful (0 votes)
5 views29 pages

Java Programming

The document provides a detailed explanation of Java's primitive data types, interfaces, packages, exception handling, thread creation, hierarchical inheritance, prime number checking, mouse listeners, and event handling. It covers the characteristics, usage, and examples of each topic, emphasizing the structure and functionality of Java programming. Key concepts such as the 'throws' keyword, event sources, and mouse listener methods are also discussed to illustrate Java's event-driven capabilities.

Uploaded by

Vaishnavi Pujari
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)
5 views29 pages

Java Programming

The document provides a detailed explanation of Java's primitive data types, interfaces, packages, exception handling, thread creation, hierarchical inheritance, prime number checking, mouse listeners, and event handling. It covers the characteristics, usage, and examples of each topic, emphasizing the structure and functionality of Java programming. Key concepts such as the 'throws' keyword, event sources, and mouse listener methods are also discussed to illustrate Java's event-driven capabilities.

Uploaded by

Vaishnavi Pujari
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

7-Marks Question

1) Explain each of the primitive datatypes present in java? Discuss in detail.


Ans. Java provides eight primitive datatypes which are the most basic data types used to store
simple values. These types are predefined by the language and are stored directly in memory.
They are not objects and therefore are faster to access.
The eight primitive datatypes are:
1) byte
• Size: 1 byte (8 bits)
• Range: -128 to +127
• Used when memory saving is important in large arrays.
• Example:byte age = 20;
2) short
• Size: 2 bytes (16 bits)
• Range: -32,768 to +32,767
• Used in place of int when memory constraint exists.
• Example:short temperature = 150;
3) int
• Size: 4 bytes (32 bits)
• Range: -2,147,483,648 to +2,147,483,647
• Default datatype for integer values.
• Example:int salary = 50000;
4) long
• Size: 8 bytes (64 bits)
• Range: very large range (~ ±9 quintillion)
• Used when int is not sufficient.
• Example:long population = 7800000000L;
5) float
• Size: 4 bytes
• Stores single precision decimal values.
• Ends with f or F.
• Example:float percentage = 82.5f;
6) double
• Size: 8 bytes
• Stores double precision floating numbers.
• Default type for decimal values.
• Example:double pi = 3.1415926535;
7) char
• Size: 2 bytes
• Stores single Unicode character (letters, symbols).
• Enclosed in single quotes.
• Example:char grade = 'A';
8) boolean
• Stores only true or false values.
• Used in logical conditions and decision-making.
• Size is JVM dependent.
• Example:boolean isValid = true;
2) What is interface? Explain it with example.
Ans. In Java, an interface is a blueprint of a class that contains only abstract methods (before
Java 8) and constants. It specifies a set of methods that a class must implement. An interface
is used to achieve abstraction and multiple inheritance in Java.
Interfaces cannot have method implementations (except default and static methods
introduced in Java 8). A class that uses an interface must provide implementation for all its
methods using the implements keyword.
Features of Interface:
• All methods are public and abstract by default.
• Variables in an interface are public, static, and final.
• A class can implement multiple interfaces, allowing Java to support multiple inheritance.
• Interfaces help in achieving loose coupling in applications.
Syntax:
interface InterfaceName {
// constant fields
// abstract methods
}
Program:
interface Animal {
void sound(); // abstract method
void type();
}
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
}
public void type() {
[Link]("Domestic Animal");
}
}
public class TestInterface {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
3) What is package? Explain different types of Packages.
Ans. A package in Java is a mechanism to group related classes, interfaces, and sub-packages
into a single unit. Packages help organize large applications, avoid naming conflicts, provide
access protection, and make code modular and maintainable.
• Avoiding name conflicts (two classes with the same name can exist in different packages)
• Providing access control using public, protected, and default access
• Reusability: packaged code can be imported and used anywhere
• Encouraging modular programming
Advantages of Packages in Java:
• Organization and Modularity:
Packages group related classes and interfaces, creating a clear and logical structure for your
codebase. This improves readability, maintainability, and makes it easier to locate specific
components.
• Namespace Management and Naming Conflicts:
Packages prevent naming conflicts between classes with the same name in different
packages. For example, [Link] and [Link] can coexist because they belong to
distinct packages.
• Access Control and Encapsulation:
Packages work in conjunction with access modifiers (like public, protected, and
default/package-private) to control the visibility and accessibility of classes, fields, and
methods. This promotes encapsulation and data hiding by restricting access to internal
implementation details.
• Code Reusability:
Packages facilitate code reuse by allowing you to easily import and utilize classes from
existing packages in your own projects. This saves development time and promotes
consistency.
• Easier Maintenance:
Grouping related classes simplifies maintenance and updates, as changes to a specific module
are localized within its package.
Disadvantages/Considerations of Packages in Java:
• Package Structure Overhead:
For very small, simple programs, the overhead of creating and managing packages might
seem unnecessary. However, as projects grow, the benefits quickly outweigh this minor
initial effort.
• Default Package Limitations:
While Java allows classes without an explicit package declaration (the "default package"),
this practice is generally discouraged for larger projects. Classes in the default package
cannot be imported by classes in named packages, limiting reusability and organization.
• Potential for Deep Nesting:
Overly deep or complex package hierarchies can sometimes make navigation and
understanding of the code structure more challenging. Careful design of the package
structure is important.
• Import Statements:
While import statements are essential for using classes from other packages, a large number
of imports can sometimes make a source file appear cluttered. However, IDEs typically
manage these automatically.
Types of packages:
1. Built-in Packages
Built-in Packages comprise a large number of classes that are part of the Java API. Some of
the commonly used built-in packages are:
• [Link]: Contains language support classes(e.g, classes that define primitive data types,
math operations). This package is automatically imported.
• [Link]: Contains classes for supporting input/output operations.
• [Link]: Contains utility classes that implement data structures such as Linked Lists and
Dictionaries, as well as support for date and time operations.
• [Link]: Contains classes for creating Applets.
• [Link]: Contains classes for implementing the components for graphical user
interfaces (like buttons, menus, etc).
Program:
import [Link]; // built-in package
public class GFG{
public static void main(String[] args) {
// using Random class
Random rand = new Random();
// generates a number between 0–99
int number = [Link](100);
[Link]("Random number: " + number);
}
}
[Link]-Defined packages:
User-defined packages are packages created by programmers to group related classes and
interfaces. They help in organizing project code, improving readability, and avoiding naming
conflicts. When a package is created by the user, it must be declared using the package
keyword at the top of the source file.
User-defined packages make large applications modular and easier to maintain.
Program 1:
package mypackage; // creating package
public class Hello {
public void display() {
[Link]("Hello from user-defined package");
}
}
Program 2:
import [Link];

class Test {
public static void main(String[] args) {
Hello h = new Hello();
[Link]();
}
}
4) Define the usage of throws keyword in exception handling? Explain with an
example.
Ans. Usage of throws Keyword in Exception Handling
The throws keyword in Java is used in method declaration to specify the type of exceptions
that a method may throw. It informs the caller (another method) that the current method
might generate an exception, and the caller must handle it using try-catch or propagate it
further.
It is mainly used for checked exceptions such as IOException, SQLException, etc. Using
throws helps in separating exception handling code from business logic, making the program
cleaner.
Key Points:
• Used in method signature.
• Used to declare one or multiple exceptions.
• Helps to delegate exception handling to calling method.
• Improves code readability and modularity.
Syntax:
returnType methodName() throws ExceptionType {
// method body
}
Program:
class TestThrows {
static void checkAge(int age) throws ArithmeticException {
if(age < 18)
throw new ArithmeticException("Not eligible to vote");
}

public static void main(String[] args) {


try {
checkAge(15);
} catch(Exception e) {
[Link]("Exception caught: " + [Link]());
}
}
}
5) Explain in detail the process of creating thread with an example.
Ans. Thread in Java
A thread is a lightweight subprocess or a smallest unit of a process. In Java, multithreading is
the process of executing multiple threads concurrently to achieve better performance,
responsiveness, and CPU utilization.
Java provides built-in support for multithreading through the [Link] class and the
Runnable interface.
Process of Creating a Thread in Java
There are two ways to create a thread:
1. By extending the Thread class
2. By implementing the Runnable interface
1) Creating Thread by Extending Thread Class
Steps:
1. Create a class that extends Thread.
2. Override the run() method → this contains the code to be executed by the thread.
3. Create an object of that class.
4. Call the start() method → it internally calls run() in a separate call stack.
Program:
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
}
}
2) Creating Thread by Implementing Runnable Interface
Steps:
1. Create a class that implements Runnable.
2. Implement the run() method.
3. Create an object of that class.
4. Create a Thread object and pass the Runnable object to its constructor.
5. Call the start() method on the Thread object.
Program:
class MyTask implements Runnable {
public void run() {
for(int i = 1; i <= 5; i++) {
[Link]("Child Thread: " + i);
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyTask task = new MyTask(); // Step 1: create Runnable object
Thread t = new Thread(task); // Step 2: create Thread object
[Link](); // Step 3: start thread
for(int i = 1; i <= 5; i++) {
[Link]("Main Thread: " + i);
}
}
}
6) Write a java program to demonstrate hierarchical inheritance.
Ans. Hierarchical Inheritance in Java
Hierarchical inheritance is a type of inheritance in which one parent class is inherited by
multiple child classes.
This means several subclasses share the same base class. It is useful when multiple classes
need common properties or methods from a single superclass.
Program:
class Animal { // Parent class
void eat() {
[Link]("Animals eat food");
}
}
class Dog extends Animal { // First child class
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal { // Second child class
void sound() {
[Link]("Cat meows");
}
}
public class HierarchicalExample {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
Cat c = new Cat();
[Link]();
[Link]();
}
}
7) Write a java program to identify whether entered number is prime or not prime.
Ans. Prime Number Program in Java
A number is called a prime number if it is greater than 1 and has only two factors: 1 and
itself.
Example: 2, 3, 5, 7, 11 are prime numbers.
To check whether a number is prime or not, we divide it by all integers from 2 to n/2 or √n.
If any number divides it exactly, then it is not prime.
Program:
import [Link];
public class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
boolean isPrime = true;
if(num <= 1) {
isPrime = false;
} else {
for(int i = 2; i <= num/2; i++) {
if(num % i == 0) {
isPrime = false;
break;
}
}
}
if(isPrime)
[Link](num + " is a Prime Number");
else
[Link](num + " is Not a Prime Number");
}
}
8) What is listener? Explain different methods of mouse listener.
Ans.- A listener in programming (specifically within event-driven environments like Java
AWT/Swing) is an interface that an object implements to be notified when a specific event
occurs [1]. It acts as an observer waiting for a source object to generate an event, such as a
user action (like a mouse click, keyboard press, or button push), or a system event (like a
timer ticking).
When an event happens, the source object automatically calls a predefined method (an event
handler) in all registered listener objects.
Methods of Mouse Listener
The MouseListener interface in Java is part of the [Link] package and contains five
abstract methods that must be implemented by any class that wishes to handle basic mouse
events [1, 2]. These methods cover the fundamental interactions of a mouse button being
pressed and released.
The five methods are:
1. public void mouseClicked(MouseEvent e)
• Description: This method is invoked when the mouse button has been clicked
(pressed and released) on a component [1, 2]. It is a convenience method that
combines both the press and release actions into a single event.
2. public void mousePressed(MouseEvent e)
• Description: This method is invoked when a mouse button has been pressed down
on a component [1, 2]. This event fires as soon as the button goes down.
3. public void mouseReleased(MouseEvent e)
• Description: This method is invoked when a mouse button has been released after
being pressed on a component [1, 2]. This event fires when the button comes back
up.
4. public void mouseEntered(MouseEvent e)
• Description: This method is invoked when the mouse cursor enters the graphical
area of a component [1, 2].
5. public void mouseExited(MouseEvent e)
• Description: This method is invoked when the mouse cursor exits the graphical
area of a component [1, 2].
Handling More Events: MouseMotionListener
For events related to the mouse moving across the screen (without a button state change), a
separate interface is used: MouseMotionListener. It has two methods:
• public void mouseMoved(MouseEvent e): Called when the mouse cursor moves within a
component without a button pressed [3].
• public void mouseDragged(MouseEvent e): Called when the mouse cursor moves within
a component while a button is pressed [3].
By implementing these interfaces and registering the listener with a component
(using [Link](this);), developers can program highly interactive user
interfaces.
Program:
import [Link].*;
import [Link].*;

class MouseEventDemo extends Frame implements MouseListener {


MouseEventDemo() {
addMouseListener(this);
setSize(300, 200);
setVisible(true);
}
public void mouseClicked(MouseEvent e) { [Link]("Mouse Clicked"); }
public void mousePressed(MouseEvent e) { [Link]("Mouse Pressed"); }
public void mouseReleased(MouseEvent e) { [Link]("Mouse Released"); }
public void mouseEntered(MouseEvent e) { [Link]("Mouse Entered"); }
public void mouseExited(MouseEvent e) { [Link]("Mouse Exited"); }

public static void main(String[] args) {


new MouseEventDemo();
}
}
9) Explain in brief about Events, Event sources and Event classes.
Ans. Events, Event Sources and Event Classes
In Java, event handling is an important part of GUI programming. When the user interacts
with GUI components such as clicking a button, moving the mouse, typing a key, etc., Java
generates events. These events are handled using the Event Delegation Model.
1) Events
An event is an object that represents an action performed by the user or the system. It
indicates that something has happened, such as a button click or a key press.
Examples of events:
• ActionEvent → button click
• KeyEvent → keyboard key press
• MouseEvent → mouse actions (click, drag, move)
• WindowEvent → window open, close, minimize
Events are handled using event listeners which contain methods that respond to events.
2) Event Sources
An event source is a GUI component that generates an event. Whenever a user performs an
action on the component, the component notifies the listener by sending an event object.
Examples of event sources:
Component Type
Button Generates ActionEvent
TextField Generates TextEvent
Frame / Window Generates WindowEvent
Mouse Generates MouseEvent
The event source must register a listener using methods like:
[Link](listenerObject);
3) Event Classes
Event classes are predefined classes in Java that represent different types of events. All event
classes are part of the package:
[Link]
Some commonly used event classes:
Event Class Purpose
ActionEvent Raised when a button is clicked
MouseEvent Mouse click, movement, press, release
KeyEvent Keyboard key pressed or released
WindowEvent Window open/close/minimize
ItemEvent Checkbox or list item selection changes
Each event class stores event details such as event source, time, location, and type of action.
Program:
import [Link].*;
import [Link].*;
class EventDemo extends Frame implements ActionListener {
Button b;
EventDemo() {
b = new Button("Click Me");
add(b);
[Link](this);
setSize(200, 150);
setLayout(new FlowLayout());
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked! Event Handled.");
}
public static void main(String[] args) {
new EventDemo();
}
}
10) Explain briefly about Adapter classes.
Ans. Adapter Classes in Java
Adapter classes are special classes in Java that provide empty implementations of all
methods present in a listener interface. They are used when a programmer does not want to
override all methods of a listener interface, but only a few of them.
Adapter classes belong to the [Link] package and help simplify event handling in
GUI applications. Without an adapter class, the programmer must implement all methods of a
listener interface even if only one is needed.
Why Adapter Classes Are Needed?
Some listener interfaces contain multiple abstract methods. For example:
• MouseListener → contains 5 methods
• KeyListener → contains 3 methods
If we implement these interfaces directly, we must override all methods. Adapter classes
solve this problem by offering default empty implementations.
Common Adapter Classes
Adapter Class Corresponding Listener
MouseAdapter MouseListener
KeyAdapter KeyListener
WindowAdapter WindowListener
FocusAdapter FocusListener
Program:
import [Link].*;
import [Link].*;
class AdapterDemo extends Frame {
AdapterDemo() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
});
setSize(250, 200);
setVisible(true);
}
public static void main(String[] args) {
new AdapterDemo();
}
}
11) What is JVM? Identify the role of JVM in java program execution.
Ans. JVM stands for Java Virtual Machine. It is a part of the Java Runtime Environment
(JRE) responsible for executing Java bytecode. The JVM acts as an execution engine that
converts the platform-independent .class (bytecode) file into machine-specific instructions.
JVM makes Java a platform-independent language, because once the program is compiled
into bytecode, it can run on any device that has a JVM installed, following the principle of:
“Write Once, Run Anywhere (WORA)”
Role of JVM in Java Program Execution
The JVM plays a crucial role in running Java applications. Its major responsibilities include:
1) Class Loading
• The JVM loads the .class file into memory using the ClassLoader subsystem.
• It verifies the class structure and ensures it follows Java rules.
2) Bytecode Verification
• JVM verifies the bytecode for security and correctness.
• Prevents harmful instructions and illegal code execution.
3) Execution of Bytecode
• JVM converts bytecode into machine-specific instructions using:
o Interpreter (executes one instruction at a time)
o JIT Compiler (Just-In-Time) for faster execution
4) Memory Management
• JVM manages memory using combined components:
o Heap
o Stack
o Method Area
o PC Register
o Native Method Stack
5) Garbage Collection
• JVM automatically removes unused objects from memory.
• Helps in efficient memory usage and avoids memory leaks.
Process Flow of JVM Execution
Java Source Code → (.java)
↓ Compile (javac)
Bytecode → (.class)
↓ Run
JVM → Machine Code → Output
Program:
class Hello {
public static void main(String[] args) {
[Link]("Welcome to JVM Execution");
}
}
12) Explain the role of interface in java.
Ans. Role of Interface in Java
In Java, an interface is a collection of abstract methods and constants that provides a
blueprint for classes. An interface represents a contract that a class must follow. It is used to
achieve abstraction, standardization, and multiple inheritance in Java.
An interface can contain abstract methods, default methods, static methods, and constants. A
class that implements an interface must provide definitions for all abstract methods.
Roles and Importance of Interfaces:
1) Achieves Multiple Inheritance
Java does not support multiple inheritance using classes, but multiple inheritance can be
achieved using interfaces. A class can implement multiple interfaces, increasing flexibility.
2) Supports Abstraction
Interfaces allow defining only method signatures without implementation. This hides internal
details and exposes only functionality.
3) Enables Polymorphism
An interface reference can store objects of any class that implements it. This supports runtime
polymorphism.
4) Provides Loose Coupling
Interfaces reduce dependency between components. The implementation can change without
affecting the code using the interface.
5) Standardization of Code
Interfaces define a common structure for different classes. For example, any class implementing
the Runnable interface must define the run() method.
Program:
interface Animal {
void sound(); // abstract method
}
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
}
}
public class TestInterface {
public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
}
13) IIIustrate all the looping statements in java with suitable example.
Ans. Java offers several looping statements to execute a block of code repeatedly based on a
specified condition. These statements are fundamental for controlling program flow and
handling iterative tasks.
1. for loop
The for loop is used when the number of iterations is known beforehand. It consists of
initialization, condition, and increment/decrement parts.
Program:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
[Link]("Iteration: " + i);
}
}
}
2. while loop
The while loop executes a block of code as long as a specified condition remains true. The
condition is checked at the beginning of each iteration.
Program:
public class WhileLoopExample {
public static void main(String[] args) {
int count = 0;
while (count < 3) {
[Link]("Count is: " + count);
count++;
}
}
}
3. do-while loop
The do-while loop is similar to the while loop, but it guarantees that the loop body will be
executed at least once, as the condition is checked after the first iteration.
Program:
public class DoWhileLoopExample {
public static void main(String[] args) {
int x = 0;
do {
[Link]("Value of x: " + x);
x++;
} while (x < 2);
}
}
4. Enhanced for loop (for-each loop)
The enhanced for loop is designed for iterating over elements of arrays and collections,
providing a more concise syntax.
Program:
public class ForEachLoopExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
[Link]("Number: " + num);
}
}
}
14) What is exception? How to handle exception in java?
Ans. An exception is an event that occurs during the execution of a program that disrupts the
normal flow of the program's instructions [1]. When an error occurs within a method, the
method creates an Exception object and hands it to the runtime system. This process is
called throwing an exception [1]. The exception object contains information about the nature
of the error, the state of the program when the error occurred, and potentially a stack trace to
help identify the source [1].
Exceptions in Java are hierarchical; all exception classes are derived from
the [Link] class, which has two direct subclasses: Error (for serious, often
unrecoverable system problems) and Exception (for conditions that a typical application can
handle) [1].
Handling Exceptions in Java
Exceptions in Java are handled using a robust mechanism involving five
keywords: try, catch, finally, throw, and throws [1]. The primary structure for handling
exceptions is the try-catch-finally block.
1. The try Block
The try block encloses the code segment that might throw an exception
Syntax:
try {
// Code that might throw an exception (e.g., division by zero, file not found)
}
2. The catch Block
Immediately following a try block, one or more catch blocks are used to handle a specific
type of exception that the try block might throw
Program:
try {
int result = 10 / 0; // This throws an ArithmeticException
} catch (ArithmeticException e) {
// Handle the specific exception here
[Link]("Error: Cannot divide by zero.");
}
3. The finally Block
The finally block contains code that will be executed regardless of whether an exception was
thrown or caught [1]. It is typically used for cleanup operations, such as closing files,
network connections, or releasing resources.
Program:
try {
// ... potentially error-prone code ...
} catch (Exception e) {
// ... error handling ...
} finally {
// Code that always runs
[Link]("This runs whether an exception occurred or not.");
// e.g., [Link]();
}
4. The throw Keyword
The throw keyword is used to explicitly throw an instance of an exception from within a
method [1]. This is often used to signal an error condition that the current method cannot
handle.
Program:
if (amount < 0) {
throw new IllegalArgumentException("Amount cannot be negative.");
}
5. The throws Keyword
If a method is capable of throwing an exception that it does not handle itself, it must declare
that exception using the throws keyword in its method signature [1]. This notifies the calling
method that it must provide a handler for that exception.
Program:
public void readFile(String path) throws FileNotFoundException {
// Code that might throw FileNotFoundException
}
15) What is Multi-threading? How to create thread? Explain with suitable example.
Ans. Definition
• Multi-threading is the ability of a CPU (or a single program) to execute multiple threads
concurrently.
• A thread is the smallest unit of execution within a process.
• Multi-threading improves performance by allowing tasks to run in parallel, making
applications more responsive.
• Common uses:
o Web servers handling multiple client requests
o Games running animations, sound, and user input simultaneously
o Background tasks like garbage collection in Java
Ways to Create Threads in Java:
1. Extending the Thread class
• Create a class that extends Thread.
• Override the run() method with the task code.
• Create an object of the class and call start() to begin execution.
• start() internally calls run() in a new thread.
Program:
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
}
}
public class ThreadExample1 {
public static void main(String[] args) {
MyThread t1 = new MyThread(); // create thread
[Link](); // start thread
[Link]("Main thread running...");
}
}
Explanation:
• [Link]() creates a new thread and executes run().
• The main thread continues independently, so outputs may interleave.
2. Implementing the Runnable interface
• Create a class that implements Runnable.
• Override the run() method.
• Pass the object to a Thread constructor.
• Call start() to begin execution.
Program:
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable thread is running...");
}
}
public class ThreadExample2 {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t2 = new Thread(r); // wrap Runnable in Thread
[Link](); // start thread
[Link]("Main thread running...");
}
}
Explanation:
• Runnable is preferred when the class already extends another class (since Java supports
single inheritance).
• It separates the task (Runnable) from the thread control (Thread).
16) How to use BufferedReader and BufferedWriter classes for input/output stream
handling.
Ans. BufferedReader and BufferedWriter in Java
Definition:
• BufferedReader and BufferedWriter are classes in [Link] package used for efficient
character stream handling.
• They use an internal buffer to reduce the number of I/O operations, making
reading/writing faster compared to unbuffered streams.
🛠 BufferedReader (for Input)
• Reads text from a character input stream efficiently.
• Common methods:
o readLine() → reads a line of text.
o close() → closes the stream.
Program:
import [Link].*;
public class BufferedReaderExample {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter your name:");
String name = [Link](); // read input line
[Link]("Hello, " + name);
[Link]();
}
}
🛠 BufferedWriter (for Output)
• Writes text to a character output stream efficiently.
• Common methods:
o write(String s) → writes a string.
o newLine() → writes a line separator.
o close() → closes the stream.
Program:
import [Link].*;
public class BufferedWriterExample {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"));
[Link]("This is written using BufferedWriter.");
[Link]();
[Link]("It is efficient for large data.");
[Link]();
[Link]("Data written to file successfully.");
}
}
Advantages of BufferedReader & BufferedWriter
• Efficiency: They use an internal buffer, reducing the number of disk/console accesses and
making I/O faster.
• Convenient Methods:
o BufferedReader provides readLine() for easy line-by-line reading.
o BufferedWriter provides newLine() for platform-independent line breaks.
• Large Data Handling: Suitable for reading/writing large text files efficiently.
• Flexibility: Can wrap around other readers/writers (e.g., FileReader, FileWriter,
InputStreamReader) to enhance performance.
• Reduced Overhead: Minimizes direct interaction with the underlying stream, improving
responsiveness.
Disadvantages of BufferedReader & BufferedWriter
• Character Data Only: They handle text (characters, strings) but not binary data like
images or audio.
• Extra Wrapping Needed: Must be combined with FileReader, FileWriter, or
InputStreamReader, making code slightly more complex.
• No Direct Support for Primitives: Cannot directly read/write integers, doubles, or
booleans; manual parsing is required.
• Manual Resource Management: Streams must be explicitly closed; forgetting to close can
cause memory leaks or file locks.
• Limited Functionality: Fewer methods compared to alternatives like Scanner (for input
parsing) or PrintWriter (for formatted output).
17) Explain event-handling mechanism using swing with example.
Ans. Event Handling Mechanism in Swing
Event handling in Swing is based on the Event Delegation Model, where an event is
generated by a GUI component and handled by an event listener. Event handling allows
interaction between the user and the GUI components such as buttons, text fields,
checkboxes, etc.
Swing uses the [Link] and [Link] packages to handle events.
Components of Event Handling:
Java Swing event handling consists of three main parts:
1) Event
An event is a user action such as button click, key press, or mouse movement.
Examples: ActionEvent, MouseEvent, KeyEvent.
2) Event Source
Event source is the component that generates the event.
Example components:
Component Event Type
JButton ActionEvent
JTextField ActionEvent
JFrame WindowEvent
3) Event Listener
A listener is an object that receives and handles the event.
It must implement a listener interface such as ActionListener, MouseListener, etc.
Listener is registered using methods like:
[Link](this);
Steps in Event Handling:
1. Create a GUI component.
2. Implement the listener interface.
3. Override the event-handling method (e.g., actionPerformed()).
4. Register the component with the listener.
Program:
import [Link].*;
import [Link].*;
class SwingEventDemo extends JFrame implements ActionListener {
JButton b;
SwingEventDemo() {
b = new JButton("Click Me");
add(b);
[Link](this); // register listener
setSize(300, 200);
setLayout(null);
[Link](100, 80, 100, 30);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
[Link](this, "Button Clicked!");
}
public static void main(String[] args) {
new SwingEventDemo();
}
}
14-Marks Question

1) What is Stack? Explain the implementation of stack and different operations performed
on it.
Ans. A stack is a linear data structure that follows the Last In First Out (LIFO) principle,
meaning the last element added to the stack is the first one to be removed. It can be visualized as
a pile of plates, where new plates are added on top and removed from the top.
Implementation of Stack:
Stacks can be implemented using either arrays or linked lists.
• Using Arrays:
• A fixed-size array is used to store the stack elements.
• A top pointer (or index) keeps track of the topmost element.
• When the stack is empty, top is typically initialized to -1.
• Push: To add an element, top is incremented, and the element is placed
at STACK[top]. An overflow condition occurs if top reaches the maximum
capacity of the array.
• Pop: To remove an element, the element at STACK[top] is retrieved, and top is
decremented. An underflow condition occurs if top is -1 (empty stack).
• Using Linked Lists:
• Each element is a node in a singly linked list.
• A head pointer points to the topmost node of the stack.
• Push: A new node is created with the element, and its next pointer is set to the
current head. The head is then updated to point to the new node.
• Pop: The element from the head node is retrieved, and the head is updated to point
to the next node in the list. An underflow condition occurs if the head is NULL.
Operations Performed on Stack:
• Push(element):
Inserts an element onto the top of the stack.
• Algorithm (Array-based):
• If top == MAX_SIZE - 1, print "Stack Overflow" and return.
• Increment top.
• Set STACK[top] = element.
• Pop():
Removes and returns the topmost element from the stack.
• Algorithm (Array-based):
• If top == -1, print "Stack Underflow" and return an error or special value.
• Store STACK[top] in a temporary variable.
• Decrement top.
• Return the stored element.
• Peek() / Top():
Returns the topmost element without removing it.
• Algorithm (Array-based):
• If top == -1, print "Stack is empty" and return an error or special value.
• Return STACK[top].
• isEmpty():
Checks if the stack is empty.
• Algorithm (Array-based):
• If top == -1, return true.
• Else, return false.
• Size():
Returns the number of elements in the stack.
• Algorithm (Array-based):
• Return top + 1.
Program:
class Stack {
int arr[] = new int[5];
int top = -1;
void push(int x) {
if(top == [Link] - 1)
[Link]("Stack Overflow!");
else
arr[++top] = x;
}
int pop() {
if(top == -1) {
[Link]("Stack Underflow!");
return -1;
} else {
return arr[top--];
}
}
int peek() {
if(top == -1)
return -1;
else
return arr[top];
}
boolean isEmpty() {
return top == -1;
}
public static void main(String[] args) {
Stack s = new Stack();
[Link](10);
[Link](20);
[Link](30);
[Link]("Top Element: " + [Link]());
[Link]("Popped: " + [Link]());
[Link]("Top After Pop: " + [Link]());
}
}
Short Note(5-marks)

1) Exception Handling
Ans. Exception handling in Java is a mechanism to handle runtime errors and ensure normal
program execution without abrupt termination. An exception is an abnormal condition that
occurs during program execution, such as division by zero, invalid input, array index out of
bounds, or file not found.
Java provides a structured way to detect and handle such errors using the exception handling
model. The main objective is to maintain smooth program flow and provide meaningful error
messages to the user.
Java uses the following keywords for exception handling:
• try → Block of code where exception may occur
• catch → Handles the exception
• finally → Executes whether exception occurs or not
• throw → Used to explicitly throw an exception
• throws → Declares exceptions in method signature
Program:
class ExceptionExample {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int result = a / b; // risky code
[Link]("Result = " + result);
}
catch (ArithmeticException e) {
[Link]("Exception Occurred: Division by Zero!");
}
finally {
[Link]("Execution Completed.");
}
}
}
2) IP address classes
Ans. An IP address (Internet Protocol address) is a unique numerical label assigned to each
device connected to a network. IPv4 addresses are 32-bit numbers written in dot-decimal
format (example: [Link]). IPv4 addresses are divided into five classes (A–E) based on
the range and purpose.
IP Address Classes:
Default Subnet
Class Range Usage
Mask
[Link] to Used for very large networks
A [Link]
[Link] (millions of hosts)
[Link] to Used for medium-sized
B [Link]
[Link] networks
[Link] to
C [Link] Used for small networks
[Link]
[Link] to
D N/A Reserved for multicasting
[Link]
[Link] to Reserved for research and
E N/A
[Link] special purposes

3) Thread priorities
Ans. In Java, each thread has a priority level that helps the scheduler decide the order in
which threads are executed. Thread priority is represented as an integer value and determines
the relative importance of one thread over another. Threads with higher priority are given
preference by the CPU over lower-priority threads, although execution order is not
guaranteed because scheduling depends on the operating system.
Java thread priorities range between:
• MIN_PRIORITY = 1
• NORM_PRIORITY = 5 (default)
• MAX_PRIORITY = 10
Thread priority can be set using:
[Link](value);
Program:
class MyThread extends Thread {
public void run() {
[Link]("Running thread: " + [Link]().getName() +
" | Priority: " + [Link]().getPriority());
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
[Link](Thread.MIN_PRIORITY); // Priority 1
[Link](Thread.NORM_PRIORITY); // Priority 5 (default)
[Link](Thread.MAX_PRIORITY); // Priority 10
[Link]();
[Link]();
[Link]();
}
}
4) Graphics in swing
Ans. Graphics in Swing is used to draw shapes, text, and images on GUI components. Swing
provides a rich set of drawing tools through the [Link] class, which is used along
with Swing components such as JPanel, JFrame, and Canvas. To perform custom drawing,
the paint() or paintComponent() method is overridden, and a Graphics object is used to draw.
Using the Graphics class, we can draw lines, rectangles, circles, ovals, and set colors and
fonts for drawing. Swing uses a lightweight rendering mechanism, meaning components are
drawn using Java code rather than relying on the operating system.
Program:
import [Link].*;
import [Link].*;
class Drawing extends JPanel {
public void paintComponent(Graphics g) {
[Link](g);
[Link]("Hello Swing Graphics!", 50, 50);
[Link](40, 70, 100, 50);
}
}
public class GraphicsDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Graphics Example");
[Link](new Drawing());
[Link](300, 200);
[Link](true);
}
}
5) JIT
Ans. JIT stands for Just-In-Time Compiler, and it is a part of the Java Virtual Machine (JVM)
used to improve the performance of Java programs. Normally, Java bytecode is executed by
the JVM interpreter line by line, which can be slower. The JIT compiler speeds up execution
by converting frequently executed bytecode (hot code) into machine-level (native) code at
runtime.
Once the bytecode is compiled into native code, it is stored in memory and reused, so the
next execution is faster. This combined approach of interpretation + runtime compilation
gives Java both portability and high performance.
Features of JIT:
• Improves execution speed
• Converts bytecode into native machine code
• Optimizes commonly used instructions
• Works automatically inside JVM
6) Java Garbage Collection
Ans. Java Garbage Collection (GC) is an automatic memory management feature that
removes unused or unreachable objects from memory. When objects are no longer referenced
in a program, they become eligible for garbage collection. This process helps prevent
memory leaks and ensures efficient use of heap memory.
Garbage collection runs automatically by the JVM, but it can be suggested manually using:
[Link]();
Benefits:
• Frees unused memory automatically
• Improves performance and efficiency
• Prevents memory overflow and leaks
Program:
class Demo {
int id;
Demo(int id) {
[Link] = id;
[Link]("Object " + id + " created");
}
protected void finalize() {
[Link]("Object " + id + " destroyed");
}
public static void main(String[] args) {
Demo d1 = new Demo(1);
Demo d2 = new Demo(2);
d1 = null; // making object eligible for garbage collection
d2 = null;
[Link](); // request JVM to run garbage collector
}
}
7) Java Packages
Ans. A package in Java is a mechanism used to group related classes, interfaces, and sub-
packages. Packages help organize code in a structured manner and avoid class name
conflicts. They also provide access protection and improve code reusability.
Java packages are similar to folders in a file system where related files are stored together.
There are two types of packages:
1. Built-in (Predefined) Packages – provided by Java API
Examples:
o [Link] (Scanner, ArrayList)
o [Link] (File, BufferedReader)
o [Link] (GUI components)
2. User-defined Packages – created by the programmer using the package keyword.
Program:
package mypack;
public class Demo {
public void show() {
[Link]("Hello Package");
}
}
8) Date class in java
Ans. The Date class in Java is part of the [Link] package and is used to store and
manipulate date and time information. It represents date and time in milliseconds from
January 1, 1970 (Epoch time). Although newer classes like LocalDate and LocalTime exist in
Java (Java 8+), the Date class is still widely used in legacy applications.
The Date class provides methods to compare dates, display the current date and time, and
convert date objects into readable string format. Some commonly used methods are:
• getTime() → returns time in milliseconds
• before() and after() → compare two dates
• toString() → displays date in readable format
Program:
import [Link];
class DateDemo {
public static void main(String[] args) {
Date d = new Date();
[Link]("Current Date and Time: " + d);
}
}
9) Inner class
[Link] Inner Class in Java is a class that is declared inside another class. It helps group
classes that are logically related and provides better encapsulation and code organization.
Inner classes have access to the private members of the outer class, which improves
flexibility in object-oriented design.
Inner classes are mainly used when a class is useful only to one other class. They also
support writing more readable and maintainable code, especially when dealing with GUI
event handling and helper classes.
Types of Inner Classes:
Type Description
Member Inner Class Declared inside a class but outside methods
Local Inner Class Declared inside a method
Static Inner Class Declared as static, does not need outer class object
Anonymous Inner Class without a name, used for one-time use (commonly in
Class event handling)
Program:
class Outer {
private int data = 10;
class Inner {
void display() {
[Link]("Data: " + data);
}
}
}

You might also like