BSDVP ACADEMY
Java Programming
Basics of Java Programming
Java is a high-level, object-oriented programming language developed by Sun Microsystems
(now owned by Oracle). It follows the "Write Once, Run Anywhere" (WORA) principle,
meaning Java programs can run on any platform that has a Java Virtual Machine (JVM).
Key Features of Java
1. Simple & Easy to Learn – Syntax is similar to C and C++ but with more powerful features.
2. Object-Oriented – Everything in Java is based on objects and classes.
3. Platform-Independent – Java code runs on any OS with a JVM.
4. Robust & Secure – Features like exception handling and memory management make it
reliable.
5. Multithreading – Allows concurrent execution of multiple tasks.
6. Automatic Garbage Collection – Java manages memory automatically.
7. Rich API – Includes libraries for networking, database management, etc.
Basic Java Syntax
1. Hello World Program
java
CopyEdit
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
2. Data Types
o Primitive: int, char, double, boolean, float, long, short, byte
o Non-primitive: String, Arrays, Classes, Interfaces
3. Control Statements
o Conditional: if, if-else, switch
o Loops: for, while, do-while
o Jump Statements: break, continue, return
4. Classes and Objects
class Car {
String brand;
void showBrand() {
1|Page BSDVP ACADEMY
BSDVP ACADEMY
[Link]("Brand: " + brand);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
[Link] = "Toyota";
[Link]();
}
}
Method Overloading in Java
Method overloading allows multiple methods in the same class to have the same name but
different parameters (different number, type, or both). It improves code readability and
reusability.
Example of Method Overloading
class MathOperations {
// Overloaded method with two int parameters
int add(int a, int b) {
return a + b;
}
// Overloaded method with three int parameters
int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded method with double parameters
double add(double a, double b) {
return a + b;
2|Page BSDVP ACADEMY
BSDVP ACADEMY
}
}
public class Main {
public static void main(String[] args) {
MathOperations obj = new MathOperations();
[Link]("Sum (int, int): " + [Link](5, 10));
[Link]("Sum (int, int, int): " + [Link](5, 10, 15));
[Link]("Sum (double, double): " + [Link](5.5, 2.2));
}
}
Rules for Method Overloading
1. The method name must be the same.
2. Parameters must differ in number, type, or order.
3. Return type does not affect method overloading.
4. Methods can have different access modifiers (public, private, etc.).
Concepts of Inheritance in Java
Inheritance is one of the key principles of Object-Oriented Programming (OOP) in Java. It
allows one class (child or subclass) to inherit the properties and behaviors (fields and
methods) of another class (parent or superclass).
1. Why Use Inheritance?
Code Reusability – Avoids redundant code by allowing subclasses to reuse methods and
fields of the parent class.
Method Overriding – Allows modifying inherited methods to change behavior in a subclass.
Polymorphism – Enables a subclass object to be treated as an instance of its superclass.
Better Organization – Helps in structuring code in a hierarchical manner.
2. Syntax of Inheritance
In Java, inheritance is implemented using the extends keyword.
// Parent Class (Super Class)
3|Page BSDVP ACADEMY
BSDVP ACADEMY
class Animal {
void eat() {
[Link]("This animal eats food.");
}
}
// Child Class (Sub Class) inheriting from Animal
class Dog extends Animal {
void bark() {
[Link]("Dog barks.");
}
}
// Main Class
public class InheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Inherited method
[Link](); // Own method
}
}
Output:
This animal eats food.
Dog barks.
3. Types of Inheritance in Java
(i) Single Inheritance
One subclass inherits from one superclass.
class Parent {
void display() {
4|Page BSDVP ACADEMY
BSDVP ACADEMY
[Link]("This is the parent class.");
}
}
class Child extends Parent {
void show() {
[Link]("This is the child class.");
}
}
(ii) Multilevel Inheritance
A class inherits from another class, which itself is inherited from another class.
class Grandparent {
void greet() {
[Link]("Hello from Grandparent!");
}
}
class Parent extends Grandparent {
void work() {
[Link]("Parent is working.");
}
}
class Child extends Parent {
void play() {
[Link]("Child is playing.");
}
}
5|Page BSDVP ACADEMY
BSDVP ACADEMY
(iii) Hierarchical Inheritance
One parent class is inherited by multiple child classes.
class Vehicle {
void move() {
[Link]("Vehicle is moving.");
}
}
class Car extends Vehicle {
void drive() {
[Link]("Car is driving.");
}
}
class Bike extends Vehicle {
void ride() {
[Link]("Bike is riding.");
}
}
(iv) Multiple Inheritance (Not Supported in Java with Classes)
Java does not support multiple inheritance directly using classes to avoid ambiguity.
Instead, it allows multiple inheritance using interfaces.
interface A {
void methodA();
}
interface B {
void methodB();
}
6|Page BSDVP ACADEMY
BSDVP ACADEMY
// Class implementing both interfaces
class C implements A, B {
public void methodA() {
[Link]("Method A from Interface A");
}
public void methodB() {
[Link]("Method B from Interface B");
}
}
4. Method Overriding in Inheritance
A subclass can provide a new version of a method inherited from its parent class.
It is used for runtime polymorphism.
The method in the child class must have the same signature as in the parent class.
The @Override annotation is used to indicate method overriding.
Example of Method Overriding
class Animal {
void sound() {
[Link]("Animals make sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
7|Page BSDVP ACADEMY
BSDVP ACADEMY
public class TestOverride {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Upcasting
[Link](); // Calls overridden method in Dog
}
}
Output:
Dog barks
5. The super Keyword in Inheritance
Access parent class methods or constructors.
Invoke parent class constructor explicitly using super().
Avoids method hiding if parent and child class have the same method name.
Example: Using super
class Animal {
Animal() {
[Link]("Animal Constructor Called");
}
void display() {
[Link]("This is an animal.");
}
}
class Dog extends Animal {
Dog() {
super(); // Calls Animal constructor
[Link]("Dog Constructor Called");
}
void display() {
8|Page BSDVP ACADEMY
BSDVP ACADEMY
[Link](); // Calls parent class method
[Link]("This is a dog.");
}
}
public class SuperExample {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
}
}
Output:
Animal Constructor Called
Dog Constructor Called
This is an animal.
This is a dog.
6. Final Keyword in Inheritance
final keyword is used to prevent inheritance or method overriding.
final class cannot be inherited.
final method cannot be overridden.
Example: Preventing Inheritance
final class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
// This will cause a compilation error
// class Dog extends Animal {}
9|Page BSDVP ACADEMY
BSDVP ACADEMY
public class FinalExample {
public static void main(String[] args) {
Animal obj = new Animal();
[Link]();
}
}
Example: Preventing Method Overriding
class Animal {
final void sound() {
[Link]("Animals make sound");
}
}
class Dog extends Animal {
// This will cause a compilation error
// void sound() {
// [Link]("Dog barks");
// }
}
7. Abstract Classes in Inheritance
Abstract classes cannot be instantiated.
They may contain abstract methods (without body) that must be implemented in subclasses.
abstract class Animal {
abstract void makeSound(); // Abstract method
void sleep() {
[Link]("Animal sleeps");
}
}
10 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
class Dog extends Animal {
@Override
void makeSound() {
[Link]("Dog barks");
}
}
public class AbstractExample {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
[Link]();
}
}
Output:
Dog barks
Animal sleeps
8. Interfaces and Inheritance
Java supports multiple inheritance through interfaces.
An interface contains only abstract methods (before Java 8).
A class can implement multiple interfaces.
interface Animal {
void eat();
}
interface Pet {
void play();
}
11 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
class Dog implements Animal, Pet {
public void eat() {
[Link]("Dog eats food.");
}
public void play() {
[Link]("Dog plays with ball.");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
[Link]();
}
}
Output:
Dog eats food.
Dog plays with ball.
Conclusion
Inheritance enables code reuse, organization, and polymorphism.
Java does not support multiple inheritance with classes but allows it with interfaces.
Method Overriding, super, final, and abstract classes are key concepts in inheritance.
Method Overriding in Java
Method overriding in Java is a feature that allows a subclass to provide a specific
implementation of a method that is already defined in its superclass. The overridden method
in the subclass should have the same method signature (method name, return type, and
parameters) as the method in the superclass.
12 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
Key Rules for Method Overriding
1. The method must have the same name as in the parent class.
2. The method must have the same parameter list as in the parent class.
3. The method in the child class must have the same return type or a covariant return type (a
subclass of the return type in the parent class).
4. The overriding method cannot have a lower access modifier than the method in the parent
class.
o If the superclass method is public, the overridden method must be public.
o If the superclass method is protected, the overridden method can be protected
or public, but not private.
5. The method cannot be overridden if it is declared final or static in the superclass.
6. Constructors cannot be overridden.
7. The @Override annotation is used to indicate that a method is being overridden. It's
optional but recommended, as it helps catch errors at compile time.
Example of Method Overriding
// Parent class (superclass)
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
// Child class (subclass) overriding the makeSound() method
class Dog extends Animal {
@Override
void makeSound() {
[Link]("Dog barks");
// Main class to test overriding
public class OverrideExample {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Calls Animal's method
[Link]();
13 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
Animal myDog = new Dog(); // Calls Dog's overridden method
[Link]();
Output:
Animal makes a sound
Dog barks
Using super to Call Superclass Method
If you need to call the parent class method from the overridden method, use the super
keyword.
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
class Dog extends Animal {
@Override
void makeSound() {
[Link](); // Calls the superclass method
[Link]("Dog barks");
public class Test {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
14 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
Output:
Animal makes a sound
Dog barks
Method Overriding with Covariant Return Type
In Java 5 and later, the overridden method in the subclass can return a subtype of the return
type of the overridden method in the superclass.
class Parent {
Parent getObject() {
return new Parent();
class Child extends Parent {
@Override
Child getObject() {
return new Child(); // Covariant return type
Method Overriding vs Method Overloading
Feature Overriding Overloading
Definition Redefining a method from the Defining multiple methods with the same
superclass in the subclass name but different parameters
Class Requires inheritance Can be in the same class or different classes
relationship
Return Type Must be the same or covariant Can be different
Parameters Must be the same Must be different
Access Cannot be more restrictive than Can have any access modifier
Modifier the superclass method
Static Cannot be overridden Can be overloaded
Methods
Final Notes
Use overriding when you need to change the behavior of an inherited method.
Always use @Override to catch errors when overriding.
Be aware of access modifiers, final, and static methods, as they impact overriding behavior.
15 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
Java Programming: Interfaces and Packages
Java provides a robust structure for organizing and modularizing code using interfaces and
packages. These features promote reusability, maintainability, and better code management.
1. Interfaces in Java
An interface in Java is a reference type that defines a collection of abstract methods. It is
used to achieve abstraction and multiple inheritance in Java.
Key Features of Interfaces:
Defines abstract methods (methods without a body).
Can have default and static methods (from Java 8 onwards).
Helps achieve multiple inheritance (unlike classes, which allow single inheritance).
Cannot have instance variables but can have constants (static final variables).
Methods in an interface are implicitly public and abstract.
Syntax of an Interface:
interface Animal {
void makeSound(); // Abstract method
}
Implementing an Interface:
A class implements an interface using the implements keyword.
class Dog implements Animal {
public void makeSound() {
[Link]("Dog barks!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Output: Dog barks!
}
}
16 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
Multiple Interface Implementation:
interface Animal {
void makeSound();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
public void makeSound() {
[Link]("Dog barks!");
}
public void play() {
[Link]("Dog plays fetch!");
}
}
2. Packages in Java
A package is a group of related classes and interfaces. It helps avoid name conflicts and
makes code more modular and maintainable.
Types of Packages:
1. Built-in packages (e.g., [Link], [Link], [Link]).
2. User-defined packages (custom packages created by developers).
Creating a Package:
Use the package keyword at the beginning of a Java file
package mypackage; // Defining a package
17 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
public class Hello {
public void sayHello() {
[Link]("Hello from mypackage!");
Using a Package (Importing Classes from a Package):
import [Link]; // Importing the Hello class
public class Test {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
Importing All Classes from a Package:
import mypackage.*; // Imports all classes in 'mypackage'
Java Standard Packages:
Java provides many built-in packages, such as:
[Link] (Contains classes like ArrayList, HashMap).
[Link] (Contains classes for input/output operations).
[Link] (Networking-related classes).
[Link] (Database connectivity).
Key Differences Between Interfaces and Abstract Classes
Feature Interface Abstract Class
Methods Only abstract (default/static from Java 8) Can have abstract and concrete methods
Variables Public, static, and final by default Can have instance variables
Constructor No constructors allowed Can have constructors
Inheritance A class can implement multiple interfaces A class can extend only one abstract class
Purpose Defines a contract Serves as a base class for derived classes
18 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
Conclusion
Interfaces provide abstraction and enable multiple inheritance in Java.
Packages help organize code into manageable sections.
Using these features together improves code reusability, organization, and maintainability.
Java provides powerful I/O (Input/Output) Streams and Collections Framework to handle
data efficiently.
I/O Streams in Java
I/O Streams in Java allow reading and writing data from different sources such as files,
memory, and network.
Types of Streams
1. Byte Streams (For handling binary data)
o InputStream (Abstract class for reading data)
FileInputStream
ByteArrayInputStream
DataInputStream
o OutputStream (Abstract class for writing data)
FileOutputStream
ByteArrayOutputStream
DataOutputStream
2. Character Streams (For handling textual data)
o Reader
FileReader
BufferedReader
InputStreamReader
o Writer
FileWriter
BufferedWriter
OutputStreamWriter
3. Buffered Streams (Improve performance by using buffers)
o BufferedInputStream
o BufferedOutputStream
o BufferedReader
o BufferedWriter
4. Object Streams (For serialization/deserialization)
o ObjectInputStream
o ObjectOutputStream
Example: Reading a File Using BufferedReader
import [Link].*;
public class FileReadExample {
19 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
} catch (IOException e) {
[Link]();
Collections Framework in Java
The Java Collections Framework (JCF) provides data structures and algorithms for
efficient data manipulation.
Key Interfaces in Collections
1. List (Ordered collection, allows duplicates)
o Implementations: ArrayList, LinkedList, Vector, Stack
Example:
List<String> list = new ArrayList<>();
[Link]("Java");
[Link]("Python");
[Link]("C++");
[Link](list);
Set (No duplicates, unordered)
Implementations: HashSet, LinkedHashSet, TreeSet
Example
20 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
Set<Integer> set = new HashSet<>();
[Link](10);
[Link](20);
[Link](10); // Duplicate ignored
[Link](set);
Queue (FIFO structure)
Implementations: PriorityQueue, LinkedList
Example
Queue<String> queue = new LinkedList<>();
[Link]("Task1");
[Link]("Task2");
[Link]([Link]()); // Removes and returns Task1
Map (Key-value pairs, unique keys)
Implementations: HashMap, LinkedHashMap, TreeMap
Example:
Map<String, Integer> map = new HashMap<>();
[Link]("Apple", 3);
[Link]("Banana", 5);
[Link]([Link]("Apple")); // Output: 3
Iterating Through Collections
Using an Iterator:
Iterator<String> iterator = [Link]();
while ([Link]()) {
[Link]([Link]());
21 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
Using forEach:
[Link]([Link]::println);
Summary
I/O Streams help in reading and writing data from various sources (files, memory, network).
Collections Framework provides dynamic data structures such as List, Set, Queue, and
Map.
In Java, exception handling and multithreaded programming are two important concepts that allow
developers to write robust and efficient applications. Here's an overview of both:
1. Exception Handling in Java
Exception handling allows your program to deal with unexpected events or errors (like file
not found, network failure, etc.) without crashing.
Key Components of Exception Handling:
try block: This block contains code that might throw an exception.
catch block: This block handles the exception thrown by the try block.
finally block: This block is always executed, regardless of whether an exception was
thrown or not. It is typically used for cleanup code, like closing file streams or database
connections.
throw keyword: Used to explicitly throw an exception.
throws keyword: Used in method declarations to specify that a method might throw an
exception.
Example:
java
CopyEdit
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero.");
} finally {
[Link]("This will always execute.");
22 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
}
2. Multithreaded Programming in Java
Multithreading allows you to perform multiple tasks concurrently, improving the efficiency
of your program, especially when dealing with I/O-bound tasks or tasks that can be
performed independently.
Key Concepts in Multithreading:
Thread: A thread is a lightweight process. Each thread has its own path of execution.
Thread class: Java provides a Thread class that can be extended or implemented by
creating a new class to define the behavior of a thread.
Runnable interface: Instead of extending the Thread class, you can implement the
Runnable interface, which requires defining the run() method.
Methods to create threads:
1. By Extending the Thread class:
class MyThread extends Thread {
public void run() {
[Link]("Thread is running.");
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
[Link](); // Start the thread
23 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
[Link] Implementing the Runnable interface:
class MyRunnable implements Runnable {
public void run() {
[Link]("Thread is running.");
public class ThreadExample {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
[Link](); // Start the thread
Synchronization:
To prevent data inconsistency when multiple threads access shared resources,
synchronization is used to ensure only one thread can access the critical section at a time.
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
public synchronized int getCount() {
return count;
24 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
}
public class ThreadExample {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
// Create two threads to increment the counter
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
[Link]();
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
[Link]();
});
[Link]();
[Link]();
[Link](); // Wait for t1 to finish
[Link](); // Wait for t2 to finish
25 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
[Link]("Count: " + [Link]()); // Should be 2000
Thread Lifecycle:
1. New: A thread is created but not started.
2. Runnable: A thread is ready to run, but the scheduler decides when to execute it.
3. Blocked: A thread is waiting for a resource (e.g., I/O).
4. Terminated: A thread finishes execution.
Summary:
Exception handling helps you manage errors gracefully, keeping your program from crashing.
Multithreading allows concurrent execution of tasks, enhancing performance for certain
types of applications.
Synchronization ensures thread safety when multiple threads access shared resources.
Java applets were small programs written in Java that could be embedded in web pages and
run in a browser. They were typically used for things like games, animations, and interactive
features. Java applets ran inside a Java Virtual Machine (JVM) in a web browser, allowing
for cross-platform compatibility.
However, Java applets have become largely obsolete due to several reasons:
1. Security concerns: Applets could potentially be exploited by malicious users, so browser
vendors started disabling support for them.
2. Browser changes: Modern browsers no longer support the NPAPI (Netscape Plugin
Application Programming Interface) plugin, which was necessary to run Java applets.
3. HTML5, JavaScript, and CSS: These web technologies have replaced the need for Java
applets, as they are more secure, faster, and compatible with all modern browsers.
Java applets are no longer widely used, but if you're learning Java and want to understand
applets or if you're dealing with legacy systems, here's a simple example of how a Java applet
might have been structured:
Simple Java Applet Example
import [Link];
import [Link];
public class HelloWorldApplet extends Applet {
26 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
public void paint(Graphics g) {
[Link]("Hello, World!", 20, 20);
Key points:
Applet class: Java applets extend the Applet class.
paint() method: The paint() method is used to draw graphics on the applet window.
Graphics class: This class allows you to perform graphical operations, such as drawing text,
shapes, and images.
In modern Java development, applets are no longer recommended. If you're developing for
the web, you would typically use technologies like JavaScript, HTML5, CSS, or even
JavaFX (for rich desktop applications) instead.
In Java, AWT (Abstract Window Toolkit) and Event Handling are key concepts for creating graphical
user interfaces (GUIs). AWT is used to build GUI components, such as buttons, text fields, labels, and
windows, while event handling deals with responding to actions (events) like mouse clicks or
keyboard presses.
1. AWT (Abstract Window Toolkit)
AWT is a collection of libraries for building graphical user interfaces in Java. It provides a
set of GUI components that allow you to design windows-based applications.
Key Components of AWT:
Frame: Represents a top-level window.
Button: A button component that users can click.
Label: Displays text or images.
TextField: A single-line text box for user input.
TextArea: A multi-line text box for larger inputs.
Checkbox: A box that can either be checked or unchecked.
List: Displays a list of items.
Menu: A menu with items.
Example Code (AWT):
import [Link].*;
import [Link].*;
public class AWTExample {
27 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
public static void main(String[] args) {
Frame frame = new Frame("AWT Example");
Button button = new Button("Click Me");
[Link](100, 100, 80, 30);
[Link](button);
[Link](300, 300);
[Link](null);
[Link](true);
2. Event Handling
Event handling is how we manage actions (events) performed by users, such as button clicks,
mouse movements, or keyboard inputs. AWT provides the EventListener interface to listen
to these events.
Steps in Event Handling:
1. Source: The object where the event originates (e.g., a button).
2. Listener: The object that listens for the event and responds to it.
3. Event: The actual action that occurred (e.g., clicking a button).
Event Types:
ActionEvent: Triggered by actions like button clicks.
MouseEvent: Triggered by mouse actions like clicking or moving the mouse.
KeyEvent: Triggered by keyboard actions.
Example Code (Event Handling):
import [Link].*;
import [Link].*;
28 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
public class AWTEventExample {
public static void main(String[] args) {
Frame frame = new Frame("Event Handling Example");
Button button = new Button("Click Me");
[Link](100, 100, 80, 30);
// Adding action listener to the button
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked!");
});
[Link](button);
[Link](300, 300);
[Link](null);
[Link](true);
In the above example:
We create a Button and add an ActionListener to it.
When the button is clicked, the actionPerformed() method is called, and a message is
printed to the console.
29 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
Types of Event Listeners:
1. ActionListener: Listens for action events (e.g., button clicks).
2. MouseListener: Listens for mouse events (e.g., mouse clicks, entering/exiting).
3. KeyListener: Listens for keyboard events (e.g., key presses).
4. WindowListener: Listens for window-related events (e.g., opening, closing).
Example of Mouse Event Handling:
import [Link].*;
import [Link].*;
public class MouseEventExample {
public static void main(String[] args) {
Frame frame = new Frame("Mouse Event Example");
[Link](new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at: " + [Link]() + ", " + [Link]());
});
[Link](300, 300);
[Link](true);
30 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
In this example, a MouseListener is used to detect when the mouse is clicked inside the
frame, and it prints the mouse's coordinates.
Event Handling with Anonymous Inner Classes:
Instead of creating separate classes to implement listeners, Java allows us to use anonymous
inner classes, as seen in the previous examples. This makes the code more concise.
31 | P a g e BSDVP ACADEMY
BSDVP ACADEMY
� ONE APP TO LEARN EVERYTHING! �
Looking for the ultimate learning companion? Look no further! BSDVP Academy is your go-to app for
all your educational needs!
� Download BSDVP Academy NOW from the Google Play Store and unlock a world of knowledge at
your fingertips! �
Key Features:
� Comprehensive Study Materials & Short Notes
� ECET Test Series & Guidance
� Exam Updates & Results
� GATE Exam Support
� Job Alerts for Diploma Holders
� Perfect Your Resume
� Complete MS Office Package
� Stay Ahead with Education Updates
Why BSDVP Academy?
• Convenient: All-in-one app to cater to all your educational needs.
• Comprehensive: Covers everything from exams to job updates.
• Reliable: Stay up-to-date with the latest in your field.
______________
� Download now and take the first step towards a smarter future!
� BSDVP Academy
Android App– [Link]
Apple Iphone App- [Link]
� Available on Google Play Store.
32 | P a g e BSDVP ACADEMY