OOP notes
OOP notes
INTRODUCTION
Very Short Answer Type Questions
1. Which one of the following statements is wrong?
o Answer: (b) The dynamic method dispatch is not carried out at the run time.
o Explanation: Dynamic method dispatch is a core concept in OOP that determines
which method to call at runtime based on the actual object type, even if the
reference is of a superclass. This is how polymorphism works in Java.
2. Out of the following, which one is not correctly matched?
o Answer: (a) Int - 24 bits
o Explanation: In Java, an int data type typically occupies 32 bits of memory.
3. In which memory a String is stored, when we create a string using the new operator?
o Answer: Heap Memory
o Explanation: When you create a String object using the new operator, it is
allocated memory from the heap, which is the dynamic memory area in Java.
4. Out of the following, which one is not correctly matched?
o Answer: (b) FORTRAN - Object Oriented Language
o Explanation: FORTRAN is a procedural programming language, not an object-
oriented one.
5. Consider the following 2 statements (S1 and S2):
o S1: C++ uses compiler only
o S2: Java uses compiler and interpreter both
o Answer: True
o Explanation: Both statements are true. C++ primarily uses a compiler for
compilation, while Java uses a compiler to generate bytecode, which is then
executed by the Java Virtual Machine (JVM), an interpreter.
1. Object-Oriented Programming (OOP):
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design
around objects rather than functions and logic. An object represents a real-world entity with
properties (attributes) and behaviors (methods). OOP focuses on designing reusable and
modular code.
Key Concepts of OOP:
• Class: A blueprint for creating objects, defining attributes and methods.
• Object: An instance of a class.
• Encapsulation: Wrapping data (attributes) and methods (behaviors) together in a single
unit (class).
• Inheritance: Mechanism to create a new class based on an existing class, reusing code
and extending functionality.
• Polymorphism: The ability of methods to behave differently based on the object or data
type.
• Abstraction: Hiding implementation details and exposing only essential features.
Conclusion:
• OOP provides a structured way to design software by modeling it as a collection of
interacting objects, which improves code reusability, maintainability, and scalability.
• In contrast, Procedural Programming is simpler and better for smaller applications but
becomes harder to manage as complexity grows.
Here are the detailed answers to your queries:
2. Concrete Invariant
A concrete invariant is a condition or property that holds true for the concrete state of an
object throughout its lifecycle.
It ensures that the internal representation of the object remains valid during all operations.
Definition:
• A condition on the concrete state that must be satisfied for the abstraction function to
work correctly.
• It guarantees the integrity of the concrete representation.
Example:
For a queue implemented using an array:
• The concrete invariant could be:
o "The rear index should always be greater than or equal to the front index."
o "The queue should never overflow or underflow."
3. Short Note on Abstraction
Definition:
Abstraction is the process of hiding implementation details and exposing only the essential
features of an object. It simplifies complex systems by allowing users to focus on what the
object does rather than how it is implemented.
Features:
• Hides Complexity: Users interact with high-level interfaces without knowing the internal
implementation.
• Promotes Modularity: Systems can be designed as a collection of well-defined abstract
components.
• Supports Reusability: Abstract components can be reused in different contexts.
Example:
In Java, consider the List interface:
• Users can use methods like add(), remove(), and get() without knowing whether the
underlying implementation is ArrayList, LinkedList, or something else.
Summary Table
Specifications of an ADT
The specification of an ADT consists of:
1. Data Structure: Specifies the type of data it holds and how the data is logically organized
(e.g., sequential, hierarchical).
2. Operations: Defines the methods available for manipulating the data.
3. Preconditions and Postconditions: Specifies the conditions before and after the
operations.
Example: Stack Specification
• Data: A collection of elements in LIFO order.
• Operations:
o push(x): Adds element x to the top of the stack.
o pop(): Removes and returns the top element.
o peek(): Returns the top element without removing it.
• Preconditions/Postconditions:
o Before pop, the stack should not be empty.
o After push, the stack size should increase by 1.
ADTs are essential in designing robust and efficient algorithms by focusing on the behavior of
data structures rather than their implementation.
FEATURES OF OOPs
1. Difference Between Early Binding and Late Binding (Static vs. Dynamic Binding)
If you’d like examples or further clarification on any topic, feel free to ask!
1. Difference Between Early Binding and Late Binding (Static vs. Dynamic Binding)
// Static method
static void incrementCounter() {
counter++;
}
void showCounter() {
System.out.println("Counter: " + counter);
}
Example.incrementCounter();
e1.showCounter(); // Output: Counter: 2
}
}
Output:
Counter: 1
Counter: 2
// Constructor
Car(String brand) {
this.brand = brand;
}
void display() {
System.out.println("Car brand: " + brand);
}
Association
Definition:
Association represents a relationship between two objects. It defines how objects are
connected and interact with each other.
Types of Association:
1. Unidirectional: One object knows about the other.
2. Bidirectional: Both objects know about each other.
Example:
class Student {
String name;
Student(String name) { this.name = name; }
}
class Course {
String title;
Course(String title) { this.title = title; }
}
Aggregation
Definition:
Aggregation is a special type of association that represents a "whole-part" relationship
where the parts can exist independently of the whole.
Key Features:
• "Has-a" relationship: A department "has-a" teacher.
• Both entities can exist independently.
Example:
class Teacher {
String name;
Teacher(String name) { this.name = name; }
}
class Department {
String deptName;
List<Teacher> teachers;
Example:
abstract class Animal {
abstract void sound();
void eat() { System.out.println("Eating..."); }
}
|
interface Animal {
void sound();
}
Example:
throw new ArithmeticException("Error");
``` |
```java
void myMethod() throws IOException, SQLException { }
b) final vs finally
EXAMPLE:
final int x = 10;
``` |
```java
try {
// code
} finally {
System.out.println("Always executed");
}
2. Package Example
Arithmetic Operations Class
Save this file in a package arithmetic.
package arithmetic;
3. Exceptions
Definition:
An exception is an event that disrupts the normal flow of a program's execution.
System-Defined Exception Example:
public class Main {
public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
}
}
User-Defined Exception Example:
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
5. == vs equals
Aspect == equals
Purpose Compares reference or memory Compares content of objects.
location.
Usage Used for primitive types and reference Used for object content
comparison. comparison.
Example:
String a = "hello";
String b = "hello";
System.out.println(a == b); // true (same memory)
``` |
```java
String a = new String("hello");
String b = new String("hello");
System.out.println(a.equals(b)); // true (same content)
1. Differences
a) throw vs throws
b) final vs finally
Example:
final int x = 10;
``` |
```java
try {
// code
} finally {
System.out.println("Always executed");
}
2. Package Example
Arithmetic Operations Class
Save this file in a package arithmetic.
package arithmetic;
3. Exceptions
Definition:
An exception is an event that disrupts the normal flow of a program's execution.
System-Defined Exception Example:
public class Main {
public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
}
}
User-Defined Exception Example:
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
5. == vs equals
Aspect == equals
Purpose Compares reference or memory Compares content of objects.
location.
Usage Used for primitive types and reference Used for object content
comparison. comparison.
Example:
String a = "hello";
String b = "hello";
System.out.println(a == b); // true (same memory)
``` |
```java
String a = new String("hello");
String b = new String("hello");
System.out.println(a.equals(b)); // true (same content)
1. try and catch Blocks
Definition:
The try block is used to enclose the code that might throw an exception. The catch block is
used to handle exceptions that occur in the try block. If an exception occurs in the try block,
control is transferred to the catch block where the exception is handled.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Handling the exception
}
Is it Essential to Catch All Types of Exceptions?
It is not essential to catch all exceptions. In Java, unchecked exceptions (e.g.,
RuntimeException, Error) do not need to be caught or declared in the throws clause.
However, checked exceptions (e.g., IOException, SQLException) must either be caught or
declared.
If you don't handle the checked exceptions, the compiler will generate an error. For
unchecked exceptions, it's optional to catch them.
Example:
class Example {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
}
Output:
Cannot divide by zero
b) Encapsulation
Encapsulation is the concept of bundling data (variables) and methods that operate on the
data into a single unit (class). It restricts direct access to some of the object’s components,
which helps protect the integrity of the data by restricting unauthorized access and
modification. Access to the data is provided through public methods (getters and setters).
Example:
class Person {
private String name; // Private variable
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String name) {
this.name = name;
}
}
d) Co-Variant Return
Co-Variant Return is a feature in Java that allows a subclass to override a method and return
a type that is a subtype of the return type declared in the superclass method.
Example:
class Animal {
Animal getAnimal() {
return new Animal();
}
}
e) Polymorphism
Polymorphism is the ability of an object to take on many forms. In Java, polymorphism
allows methods to perform different tasks based on the object that is calling them. It is
achieved through method overriding (runtime polymorphism) and method overloading
(compile-time polymorphism).
Example:
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
f) Abstract Class
An abstract class is a class that cannot be instantiated directly. It can have abstract methods
(without a body) that must be implemented by subclasses. It can also have concrete
methods with implementation.
Example:
abstract class Animal {
abstract void sound(); // Abstract method
g) Dynamic Binding
Dynamic binding (or late binding) refers to the process of associating a method call with the
method definition at runtime rather than at compile-time. It is primarily used in method
overriding.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
h) Method Overriding
Method overriding occurs when a subclass provides its own implementation of a method
that is already defined in its superclass. The method signature in the subclass must match
the method signature in the superclass.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
i) Properties of OOP
The main properties of Object-Oriented Programming (OOP) are:
1. Encapsulation: Bundling of data and methods in a class, hiding the internal details from
outside.
2. Abstraction: Hiding the complex implementation details and showing only the necessary
features.
3. Inheritance: Mechanism to create a new class from an existing class, inheriting its
attributes and behaviors.
4. Polymorphism: Ability of different objects to respond to the same message in different
ways.
j) Interface
An interface is a reference type in Java, it is similar to a class, but it can contain only
constants, method signatures, default methods, and static methods. Interfaces cannot have
instance fields. A class implements an interface, thereby inheriting the abstract methods of
the interface.
Example:
interface Animal {
void sound();
}
l) Encapsulation
Encapsulation refers to the concept of wrapping data (attributes) and methods that operate
on that data into a single unit, or class. It restricts direct access to some of an object's
components and can prevent unintended interference and misuse of the data.
Example:
class Person {
private String name; // private variable
private int age; // private variable
m) Inheritance
Inheritance is the mechanism in object-oriented programming that allows one class
(subclass) to inherit the properties and methods from another class (superclass). It
promotes code reusability and method overriding.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
INHERITENCE IN OO DESIGN
Certainly, let's break down the answers and explanations for the given object-oriented
programming questions:
1. Exception is defined in:
• Answer: (b) java.lang package
• Explanation: Exceptions in Java are handled using the java.lang package. It provides the
necessary classes and interfaces for creating, throwing, and catching exceptions.
2. Which is a valid declaration within an interface?
• Answer: (a) public static short stop = 23;
• Explanation: In an interface, all variables are implicitly public, static, and final. Therefore,
the only valid declaration among the options is "public static short stop = 23;".
3. What is the narrowest valid return Type for method A in line 3?
Java
public class Returnit {
return Type method A (byte x, double y) /*Line 3*/
{
return (long)x/y*2;
}
}
• Answer: (d) double
• Explanation: The expression (long)x/y*2 involves a division between a long and a
double. In Java, when dividing a long by a double, the result is automatically promoted
to a double. Therefore, the narrowest valid return type for method A is double.
4. Runtime binding occurs:
• Answer: (c) class and interface
• Explanation: Runtime binding, also known as dynamic binding, occurs when a method
call is resolved at runtime. This happens when the actual object type is determined at
runtime, which can be the case with both classes and interfaces.
5. Abstract class is used for:
• Answer: (a) inheritance only
• Explanation: Abstract classes cannot be instantiated directly. They are primarily used as
a base class for other classes to inherit from.
6. What is an example of polymorphism?
• Answer: (c) Method overloading
• Explanation: Method overloading is a form of polymorphism where multiple methods
with the same name but different parameter lists exist in a class. This allows the same
method name to be used for different purposes based on the arguments provided.
7. The relation between classes can be represented by:
• Answer: (d) inheritance
• Explanation: Inheritance is a fundamental concept in object-oriented programming that
establishes a hierarchical relationship between classes. A subclass inherits properties
and behaviors from its superclass.
8. Method overloading occurs only when:
• Answer: (a) the names and the type signature of two methods are not identical
• Explanation: Method overloading requires that the methods have the same name but
different parameter lists (type signature). If the names and type signatures are identical,
it would lead to ambiguity and compilation errors.
1. Benefits of Using Design Patterns
Design patterns are reusable solutions to common problems in software design. They offer
several benefits:
1. Code Reusability
o Provides a proven solution that can be reused in different projects or situations.
2. Standardized Approach
o Offers a standard way of solving design problems, improving communication
among developers.
3. Ease of Maintenance
o Simplifies debugging and maintenance due to well-defined structures.
4. Scalability
o Helps in designing scalable and extendable systems by adhering to tried and
tested principles.
5. Improved Productivity
o Saves time by providing pre-defined templates for solving recurring problems.
6. Encourages Best Practices
o Promotes the use of object-oriented principles such as encapsulation,
inheritance, and polymorphism.
Summary Table:
Structural Patterns:
1. Adapter Pattern:
Converts one interface into another expected by a client.
Example: Using legacy code with modern systems.
2. Facade Pattern:
Provides a simplified interface to a larger body of code.
Example: Simplifying subsystems in a library.
3. Decorator Pattern:
Dynamically adds behavior to an object without affecting other objects.
Example: Adding scrollbars to a window.
Behavioral Patterns:
1. Observer Pattern:
Defines a one-to-many dependency where if one object changes state, all its dependents
are notified.
Example: Event listener systems.
2. Strategy Pattern:
Allows a family of algorithms to be defined and makes them interchangeable.
Example: Payment gateways (credit card, PayPal, etc.).
3. Command Pattern:
Encapsulates a request as an object, thereby allowing users to parameterize clients.
Example: Undo operations in text editors.
@Override
public void display() {
System.out.println("Displaying " + fileName);
}
}
@Override
public void display() {
if (realImage == null) {
realImage = new RealImage(fileName); // Lazy initialization
}
realImage.display();
}
}
interface B {
void methodB();
}
class C implements A, B {
@Override
public void methodA() {
System.out.println("Method A from Interface A");
}
@Override
public void methodB() {
System.out.println("Method B from Interface B");
}
}
Example:
class Parent {
void display() {
System.out.println("Parent class method");
}
}
Cons:
1. Overhead:
Can lead to over-engineering if not used judiciously.
2. Complexity:
Beginners may find design patterns challenging to understand.
3. Learning Curve:
Requires prior experience with OOP concepts to implement effectively.
4. Misuse:
Incorrect application can lead to suboptimal designs.
Certainly, let's break down the answers and explanations for the given object-oriented
programming questions:
1. JVM is an abstract machine. It is a specification that provides runtime environment in which
java bytecode can be executed.1
• Explanation: This is a correct statement. The Java Virtual Machine (JVM) is a virtual
machine that executes Java bytecode. It is not a physical machine but a specification that
defines the rules for how Java bytecode should be executed. Different implementations
of the JVM exist for different operating systems and hardware platforms, but they all
adhere to the same specification.
2. Java virtual machine is:
• Answer: (a) platform dependent totally
• Explanation: While the JVM is designed to provide platform independence for Java
programs, it is itself not entirely platform-independent. Different JVMs are required for
different operating systems and hardware architectures.
3. Java compiler is written in which language?
• Answer: The Java compiler was originally written in C, using some C++ libraries.
• Explanation: The original Java compiler was created using C and some C++ libraries. This
allowed for efficient compilation and portability across different platforms.
4. JVM is platform independent or not?
• Answer: The JVM is not platform independent.
• Explanation: As mentioned earlier, different JVMs are required for different platforms.
While Java programs compiled into bytecode can run on any platform with a compatible
JVM, the JVM itself is not platform-independent.
5. When finalize() method is called in java before an object is garbage collected.
• Explanation: The finalize() method is a method in Java that is called by the garbage
collector before an object is garbage collected. This method is intended to provide a final
opportunity for an object to clean up resources before it is reclaimed by the garbage
collector. However, the finalize() method is not guaranteed to be called before an object
is garbage collected, and its use is generally discouraged in favor of other resource
management techniques.
1. What is JVM (Java Virtual Machine)?
The Java Virtual Machine (JVM) is an abstract computing engine that enables Java programs to
run on any platform. It is responsible for executing the bytecode generated by the Java
compiler. The JVM is part of the Java Runtime Environment (JRE) and provides core
functionalities like memory management, garbage collection, and platform independence.
Example:
class GarbageDemo {
@Override
protected void finalize() throws Throwable {
System.out.println("Object is garbage collected");
}
What is JVM?
To summarize, the JVM:
• Executes Java programs.
• Converts bytecode into machine-specific code.
• Provides features like memory management and garbage collection.
5. What is a Thread?
A thread in Java is a lightweight process that enables concurrent execution of tasks. A thread is
part of a program that runs independently of other parts, making multitasking possible.
Threads are managed by the Java Virtual Machine (JVM), and they share the same memory
space.
Key Differences:
• Extending Thread: Cannot extend any other class.
• Implementing Runnable: Allows extending another class.
Example:
class FinalizeDemo {
@Override
protected void finalize() throws Throwable {
System.out.println("Object is being garbage collected.");
}
Important Notes:
• The finalize() method is deprecated since Java 9 due to its unpredictability and potential
performance issues.
• Alternative: Use try-with-resources or explicit resource management.
Example in Java:
// Model
class Data {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
// View
class DisplayView {
public void printDetails(String name) {
System.out.println("Name: " + name);
}
}
// Controller
class Controller {
private Data model;
private DisplayView view;
// Main Class
public class Main {
public static void main(String[] args) {
Data model = new Data();
DisplayView view = new DisplayView();
Controller controller = new Controller(model, view);
controller.setName("John Doe");
controller.updateView();
}
}
Output:
Name: John Doe
MVC Application Life Cycle
The Model-View-Controller (MVC) application life cycle involves the sequence of steps and
interactions that occur from the moment a user initiates a request to the point where a
response is rendered back to the user. It is commonly used in frameworks like Spring MVC or
ASP.NET MVC. Here is an overview of the life cycle:
1. User Request
• The life cycle starts when a user sends a request (e.g., clicks a link, submits a form, or
interacts with a UI element).
• The request is sent to the Controller via a Router or Front Controller, depending on the
framework.
2. Routing
• The Front Controller (e.g., DispatcherServlet in Spring MVC) receives the request and
determines which specific Controller should handle it.
• The routing logic maps the request URL to the appropriate Controller and action
method.
3. Controller Execution
• The Controller acts as the mediator between the Model and View.
• It processes the request, interacts with the Model to fetch or update data, and prepares
data for the View.
o Input Handling: It captures user input from the request (e.g., query parameters,
form data).
o Business Logic: It calls the appropriate methods in the Model.
4. Model Interaction
• The Model represents the application's data and business logic.
• It retrieves data from the database, applies business rules, or updates data as requested
by the Controller.
• After processing, the Model returns the data to the Controller.
5. View Selection
• The Controller determines which View to render based on the request and the data
received from the Model.
• It passes the prepared data to the View.
6. View Rendering
• The View is responsible for presenting the data to the user in the desired format (e.g.,
HTML, JSON, XML).
• It uses the data provided by the Controller to render the response.
7. Response to User
• The rendered View is sent back to the user as a response (e.g., web page, API response).
• The life cycle ends here.
Explanation
1. Command Line Program:
o The args array holds the arguments.
o You can loop through args to access individual arguments.
2. Array Program:
o The Arrays.sort() method is used to sort arrays in ascending order.
o Arrays.toString() is used to display the array in a readable format.
2. a) Thread Life Cycle
The thread life cycle in Java describes the various states a thread goes through during its
execution. Java threads are managed by the JVM and can exist in one of the following states:
1. New State
• A thread is created using the Thread class but hasn’t started yet.
Code:
• Thread t = new Thread();
2. Runnable State
• After calling the start() method, the thread moves to the Runnable state. It is ready to
run but waiting for CPU time.
Code:
• t.start();
3. Running State
• The thread is actively executing. It enters this state when the CPU assigns processor
time.
4. Blocked/Waiting State
• The thread is temporarily inactive and waiting for some condition to be met (e.g.,
waiting for a resource or a signal).
5. Terminated State
• The thread finishes its task and is no longer active. It cannot be restarted.
Code:
• System.out.println("Thread is terminated");
2. b) Wrapper Classes
What Are Wrapper Classes?
• Wrapper classes provide a way to use primitive data types (int, char, double, etc.) as
objects.
• Java provides a wrapper class for each primitive type. For example:
o int -> Integer
o char -> Character
o double -> Double
Example:
int num = 10;
3. Short Notes
a) Virtual Method Table
• A Virtual Method Table (VMT) is a mechanism used in object-oriented programming to
support dynamic method dispatch.
• Each class has a table storing addresses of methods to ensure runtime polymorphism.
• Advantage: Allows overriding methods to be determined at runtime.
2. Memory Allocation
1. Static Allocation:
o Done at compile-time (e.g., static variables).
2. Dynamic Allocation:
o Done at runtime (e.g., objects created using new).
3. Garbage Collection
• Automatically removes unused or unreachable objects to free up memory.
• Relieves programmers from manual memory management (like in C/C++).
@Override
protected void finalize() {
System.out.println("Garbage Collector called!");
}
}
Output:
Garbage Collector called!
Certainly, let's break down the answers and explanations for the given object-oriented
programming questions:
1. Which method is used to set the graphics current color to the specified color in the graphics
class?
• Answer: void setColor(Color c)
• Explanation: In Java's Graphics class, the setColor(Color c) method is used to set the
current color that will be used for subsequent drawing operations.
2. What is the length of the application box made by the following Java program?
Java
import java.awt.*;
import java.applet.*;
• frame.add(button);
• frame.setSize(300, 300); // Frame size
• frame.setLayout(null);
• frame.setVisible(true);
• }
• }
Event Listener
• Definition: An event listener in Java is an interface that listens for specific events, such
as button clicks, mouse movements, or keyboard actions. When an event occurs, the
listener's method is executed.
• Key Points:
o Event listeners are part of Java's Event-Driven Programming model.
o Listeners implement specific interfaces like ActionListener, MouseListener, etc.
• Example of Event Listener:
import java.awt.*;
import java.awt.event.*;
public EventListenerExample() {
frame = new Frame("Event Listener Example");
button = new Button("Click Me");
button.setBounds(50, 100, 80, 30);
button.addActionListener(this); // Registering event listener
frame.add(button);
frame.setSize(300, 300);
frame.setLayout(null);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
6. What is Iterator?
Definition:
An Iterator is an interface in Java's Collections Framework that provides methods to traverse a
collection sequentially without exposing its underlying implementation. It is part of the java.util
package.
Features of Iterator:
1. Universal cursor for all Collection classes (except Map).
2. Supports methods:
o hasNext(): Checks if there are more elements to traverse.
o next(): Retrieves the next element.
o remove(): Removes the current element (optional).
Usage Works with all collections. Works with legacy classes like Vector and
Hashtable.
Blocking Queue:
• A thread-safe queue that blocks:
o When trying to add elements if the queue is full.
o When trying to retrieve elements if the queue is empty.
• Found in java.util.concurrent.
Key Implementations:
• ArrayBlockingQueue
• LinkedBlockingQueue
Example:
import java.util.concurrent.*;
Advantages:
1. Type Safety: Ensures that only specified types are allowed.
2. Code Reusability: Enables the use of the same code with different data types.
3. Compile-Time Checking: Catches errors during compilation.
public T getData() {
return data;
}
Key Points:
• Used in collections (ArrayList<T>, HashMap<K, V>).
• Eliminates the need for type casting.
• Enhances readability and maintainability of code.
1. Explanation of Three Events with Examples
Events in Java are actions generated by users (e.g., mouse clicks, key presses) or the program
itself. Java uses the event delegation model, where an event source generates an event, and an
event listener processes it.
1. ActionEvent
• Triggered when an action is performed, such as clicking a button.
• Listener: ActionListener.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
2. KeyEvent
• Triggered when a key is pressed, released, or typed.
• Listener: KeyListener.
Example:
import java.awt.event.*;
import javax.swing.*;
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
System.out.println("Key Typed: " + e.getKeyChar());
}
});
frame.add(textField);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
3. MouseEvent
• Triggered by mouse actions such as clicks, movement, or entering/exiting a component.
• Listener: MouseListener, MouseMotionListener.
Example:
import java.awt.event.*;
import javax.swing.*;
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")");
}
});
frame.add(label);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Growth Increases by 50% of its size. Doubles its size when full.
Mechanism
Legacy Status Part of Java Collections Considered legacy but still used.
Framework.
Example Code
ArrayList Example:
import java.util.*;
Summary
• Events like ActionEvent, KeyEvent, and MouseEvent allow interaction in GUI applications.
• ArrayList is preferred for non-thread-safe, high-performance applications, while Vector
is suitable for thread-safe requirements.