0% found this document useful (0 votes)
14 views15 pages

Java ActionListener and Event Handling Guide

The document covers various Java programming concepts including event handling using ActionListener, autoboxing and unboxing, the Character class, differences between List and Set, event classes in Java, JCheckBox and JRadioButton, and layout managers. It provides definitions, key points, example programs, and important methods for each topic. The information is aimed at enhancing understanding of Java's GUI components and collections framework.

Uploaded by

klike0282
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)
14 views15 pages

Java ActionListener and Event Handling Guide

The document covers various Java programming concepts including event handling using ActionListener, autoboxing and unboxing, the Character class, differences between List and Set, event classes in Java, JCheckBox and JRadioButton, and layout managers. It provides definitions, key points, example programs, and important methods for each topic. The information is aimed at enhancing understanding of Java's GUI components and collections framework.

Uploaded by

klike0282
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

Java Program: Event Handling by Implementing ActionListener

Definition:
Event handling in Java allows a program to respond to user actions like button clicks, key presses, or
mouse movements. The ActionListener interface is used to handle action events such as button clicks in
AWT or Swing applications. It contains one method, actionPerformed(ActionEvent e), which is
executed when an action occurs.
Steps to Handle Events using ActionListener:
1. Import [Link].* package.
2. Implement the ActionListener interface in your class.
3. Override the actionPerformed() method.
4. Register the listener using addActionListener() with the event source (e.g., Button).
Example Program:
import [Link].*; import [Link].*; public class ActionListenerExample extends Frame
implements ActionListener { TextField tf; Button b; ActionListenerExample() { tf = new TextField();
[Link](60, 50, 170, 20); b = new Button("Click Me"); [Link](100, 120, 80, 30);
[Link](this); // Register listener add(b); add(tf); setSize(300, 300); setLayout(null);
setVisible(true); } public void actionPerformed(ActionEvent e) { [Link]("Button Clicked!"); } public static
void main(String[] args) { new ActionListenerExample(); } }
Output:
When the user clicks the "Click Me" button, the text field displays the message: "Button Clicked!"
Key Points:
• ActionListener is used for handling button clicks and similar actions.
• The actionPerformed() method executes automatically when the event occurs.
• Multiple components can share the same listener.
• Used widely in both AWT and Swing GUI applications.
Autoboxing and Unboxing in Java
Definition:
Autoboxing is the automatic conversion by the Java compiler of a primitive type (e.g., int) into its
corresponding wrapper class object (e.g., Integer). Unboxing is the reverse — automatic conversion of a
wrapper object back to its primitive value.
Why it exists:
The Collections framework and many APIs work with objects, not primitives. Autoboxing/unboxing allows
primitives to be used where objects are required with minimal code.
Examples:
1) Autoboxing (primitive → wrapper):
int a = 10; Integer obj = a; // compiler does: [Link](a) 2) Unboxing (wrapper → primitive):
Integer obj = [Link](20); int b = obj; // compiler does: [Link]() 3) With Collections:
List list = new ArrayList<>(); [Link](5); // autoboxing from int to Integer int x = [Link](0); // unboxing from
Integer to int
Important Notes & Pitfalls:
• NullPointerException: Unboxing a null wrapper causes NPE. Example: Integer i = null; int x = i; // NPE.
• Performance: Boxing/unboxing creates objects and may affect performance. Use primitives in
performance-critical code.
• Equality: Beware of == with wrappers. Integer a = 1000, b = 1000; (a == b) may be false; use equals()
for value comparison. Note: JVM caches Integer values from -128 to 127, so == may be true for small
ints.
• Autoboxing conversions used by compiler: compiler inserts calls like [Link]() and
intValue() during boxing/unboxing.
Quick Example Program:
public class AutoBoxUnbox { public static void main(String[] args) { Integer iw = 10; // autoboxing int p =
iw + 5; // unboxing used in arithmetic [Link](p); // prints 15 Integer a = 128; Integer b = 128;
[Link](a == b); // usually false (different objects) [Link]([Link](b)); // true } }
Key Points to Remember:
• Autoboxing lets you write cleaner code when using collections/APIs that expect objects.
• Unboxing can throw NullPointerException if wrapper is null.
• Prefer primitives for heavy numeric computations; be mindful of overhead.
• Use equals() to compare wrapper values reliably.
Character Class in Java
Definition:
The Character class in Java is a wrapper class for the primitive data type char. It is part of the [Link]
package and provides several static methods to manipulate, test, and convert characters. This class is
used when working with objects instead of primitive char values, such as in Collections or Generics.
Purpose:
It allows easy handling of characters through methods that check character types, convert cases, and
handle Unicode values. It’s also useful for text processing, validation, and conversions.
Important Methods of Character Class:
Method Description Example
isLetter(char ch) Checks if the character is a letter. [Link]('A') → true
isDigit(char ch) Checks if the character is a digit. [Link]('5') → true
isWhitespace(char ch) Checks if the character is a space, tab, or newline. [Link](' ') → true
isUpperCase(char ch) Checks if the character is uppercase. [Link]('A') → true
isLowerCase(char ch) Checks if the character is lowercase. [Link]('b') → true
toUpperCase(char ch) Converts to uppercase. [Link]('a') → 'A'
toLowerCase(char ch) Converts to lowercase. [Link]('B') → 'b'
isLetterOrDigit(char ch) Checks if character is letter or digit. [Link]('A') → true
getNumericValue(char ch) Returns numeric value of a digit character. [Link]('7') → 7
compare(char x, char y) Compares two characters numerically. [Link]('A','B') → negative

Example Program:
public class CharacterExample { public static void main(String[] args) { char ch = 'a';
[Link]([Link](ch)); // true [Link]([Link](ch)); // A
[Link]([Link]('5')); // true } }
Key Points to Remember:
• Character class is immutable and part of [Link].
• Provides utility methods to test and convert characters.
• Supports Unicode, making it useful for multilingual applications.
• Frequently used for validation and parsing tasks.
• Autoboxing allows direct assignment: Character ch = 'A';
Difference Between List and Set in Java
Both List and Set are interfaces in the Java Collections Framework ([Link] package). They differ
in how they handle order, duplicates, and access to elements.

Feature List Set


Definition Ordered collection that allows duplicates. Unordered collection that does not allow dupli
Order Maintains insertion order. Does not guarantee order (depends on implem
Duplicates Allows duplicates. Automatically removes duplicates.
Indexing Supports index-based access. No indexing support.
Common Implementations
ArrayList, LinkedList, Vector, Stack HashSet, LinkedHashSet, TreeSet
Null Elements Can store multiple null values. Can store only one null (HashSet, LinkedHash
Performance Slower for searching (linear search). Faster for searching (hashing).
Usage When order or duplicates matter. When only unique elements are needed.

Example Program:
import [Link].*; public class ListSetExample { public static void main(String[] args) { List list = new
ArrayList<>(); [Link]("Apple"); [Link]("Banana"); [Link]("Apple"); // Duplicate allowed
[Link]("List: " + list); Set set = new HashSet<>(); [Link]("Apple"); [Link]("Banana");
[Link]("Apple"); // Duplicate ignored [Link]("Set: " + set); } } Output: List: [Apple,
Banana, Apple] Set: [Banana, Apple]
Key Points to Remember:
- List = Ordered, Duplicates Allowed
- Set = Unordered, Duplicates Not Allowed
- List supports index-based access
- Set is faster for searching (uses hashing)
- Common Implementations: ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet
Java Event Classes
Definition:
In Java, the Event Classes are part of the [Link] package and represent various types of user
interactions or system-generated events. These classes are used in the Event Delegation Model to
capture and handle events such as button clicks, key presses, mouse movements, window actions, etc.
Event Delegation Model:
This model is based on the idea that an event source generates an event and sends it to one or more
event listeners that handle the event. The listeners are registered to the source using methods like
addActionListener(), addKeyListener(), etc.
Common Event Classes in Java:
Event Class Description Example Event Source
ActionEvent Generated when a button is clicked or a menu item is
Button,
selected.
MenuItem
ItemEvent Generated when a checkbox or list item is selected/deselected.
Checkbox, Choice, List
AdjustmentEvent Occurs when the value of a scrollbar is changed. Scrollbar
TextEvent Generated when the value in a text field or area changes.
TextField, TextArea
FocusEvent Occurs when a component gains or loses focus. TextField, Button
KeyEvent Occurs when a key is pressed, released, or typed. Keyboard
MouseEvent Occurs when mouse is clicked, pressed, released, orMouse
moved.
WindowEvent Generated when a window is opened, closed, or activated.
Window, Frame, Dialog

Example Program:
import [Link].*; import [Link].*; public class EventExample extends Frame implements
ActionListener { Button b; EventExample() { b = new Button("Click Me"); [Link](this);
add(b); setSize(200, 200); setLayout(new FlowLayout()); setVisible(true); } public void
actionPerformed(ActionEvent e) { [Link]("Button Clicked!"); } public static void main(String[]
args) { new EventExample(); } }
Key Points to Remember:
• Event classes are found in the [Link] package.
• Each event class has corresponding listener interfaces like ActionListener, MouseListener, etc.
• The EventObject class is the superclass of all event classes.
• Event handling improves interactivity and GUI control in AWT/Swing applications.
• Use addXListener() methods to register listeners to event sources.
8. JCheckBox and JRadioButton in Java
Introduction:
In Java, JCheckBox and JRadioButton are part of the [Link] package used to create
interactive GUI components. They allow users to make selections within graphical user interfaces
(GUIs) in Swing-based applications.

1. JCheckBox:
A JCheckBox is a graphical component that represents an option that can be selected or
deselected. It allows multiple selections at once, meaning a user can select several checkboxes
simultaneously.
Common Methods:
- isSelected() – Returns true if the checkbox is selected.
- setSelected(boolean state) – Selects or deselects the checkbox.
- getText() – Returns the text of the checkbox.

2. JRadioButton:
A JRadioButton is used when only one option out of a group can be selected at a time. To group
multiple radio buttons together, we use the ButtonGroup class.
Common Methods:
- isSelected() – Checks if the radio button is selected.
- setSelected(boolean state) – Selects or deselects the button.
- setActionCommand(String cmd) – Sets a command string for the button.

Example Program:
import [Link].*; import [Link].*; public class CheckRadioExample { public static void
main(String[] args) { JFrame f = new JFrame("JCheckBox & JRadioButton Example"); JCheckBox
cb1 = new JCheckBox("Java"); JCheckBox cb2 = new JCheckBox("Python"); [Link](50,
50, 100, 30); [Link](50, 80, 100, 30); JRadioButton r1 = new JRadioButton("Male");
JRadioButton r2 = new JRadioButton("Female"); [Link](200, 50, 100, 30);
[Link](200, 80, 100, 30); ButtonGroup bg = new ButtonGroup(); [Link](r1); [Link](r2);
[Link](cb1); [Link](cb2); [Link](r1); [Link](r2); [Link](400, 200); [Link](null); [Link](true); }
}

Difference between JCheckBox and JRadioButton:

Feature JCheckBox JRadioButton


Selection Type Multiple selections allowed Only one selection allowed per group
Grouping No grouping needed Uses ButtonGroup to create exclusive options
Use Case When user can choose many options When user must choose one option

Key Points to Remember:


- JCheckBox → Used for multiple independent choices.
- JRadioButton → Used for mutually exclusive options.
- ButtonGroup helps enforce single selection among radio buttons.
- Both components are part of the Swing GUI toolkit in Java.
Layout Manager in Java
Definition:
A Layout Manager in Java is an object that controls the positioning and sizing of components within a
container (like Frame, Panel, or Applet). It automatically arranges GUI components to make the interface
responsive and organized, regardless of screen size or resolution.
All layout managers are part of the [Link] package.
Common Layout Managers: FlowLayout, BorderLayout, GridLayout, CardLayout, GridBagLayout, etc.
1. FlowLayout Manager:
• It arranges components in a single row, one after another, like words in a paragraph.
• When the row is filled, components move to the next line.
• It is the default layout manager for Panel and Applet.
• Components are centered by default, but alignment can be changed (LEFT, RIGHT, CENTER).
Constructors:
• FlowLayout()
• FlowLayout(int align)
• FlowLayout(int align, int hgap, int vgap)
Example of FlowLayout:
import [Link].*; public class FlowLayoutExample { public static void main(String[] args) { Frame f = new
Frame("FlowLayout Example"); [Link](new FlowLayout([Link])); for (int i = 1; i <= 5; i++)
[Link](new Button("Button " + i)); [Link](300, 150); [Link](true); } }
2. BorderLayout Manager:
• It divides the container into five regions: North, South, East, West, and Center.
• Only one component can be placed in each region.
• It is the default layout manager for Frame.
• The component in the Center region expands to fill available space.
Constructors:
• BorderLayout()
• BorderLayout(int hgap, int vgap)
Example of BorderLayout:
import [Link].*; public class BorderLayoutExample { public static void main(String[] args) { Frame f =
new Frame("BorderLayout Example"); [Link](new BorderLayout(10, 10)); [Link](new Button("North"),
[Link]); [Link](new Button("South"), [Link]); [Link](new Button("East"),
[Link]); [Link](new Button("West"), [Link]); [Link](new Button("Center"),
[Link]); [Link](300, 200); [Link](true); } }
Key Differences between FlowLayout and BorderLayout:
Aspect FlowLayout BorderLayout
Arrangement Components are arranged in a single row or multiple
Containerlines.
divided into five regions (N, S, E, W, Center)
Default For Panel and Applet Frame
Control Less control over size and position. More control using regions.
Use Case Simple component arrangement. Complex GUI layout with defined sections.

Key Points to Remember:


• Layout Managers simplify GUI design and make interfaces responsive.
• FlowLayout arranges components sequentially; BorderLayout divides the frame into fixed regions.
• You can use setLayout(null) to use absolute positioning, but it’s not recommended for complex GUIs.
Layout Managers in Java
Definition:
A Layout Manager in Java is an object that automatically arranges components in a container
(Frame, Panel, etc.) according to a specific layout rule. It helps in managing the size and position of
GUI elements dynamically.

Why Use Layout Managers?


They make GUIs platform-independent and responsive by adjusting component positions
automatically when the window is resized.

Layout Manager Description Default Container


FlowLayout Arranges components in a row, left to right. Panel
BorderLayout Divides container into North, South, East, West, Center regions.
Frame
GridLayout Divides area into equal-sized rows and columns. Panel
CardLayout Stacks multiple components (cards); one visible at a time.
Panel
GridBagLayout Flexible grid layout, allows custom row/column span. Panel
BoxLayout Arranges components horizontally or vertically. Swing
GroupLayout Used by GUI builders to align components [Link]
SpringLayout Positions components using spring-like constraints. Swing

Key Points:
- FlowLayout: Left to right arrangement (default for Panel).
- BorderLayout: 5 regions – North, South, East, West, Center (default for Frame).
- GridLayout: Uniform grid of rows × columns.
- CardLayout: Only one component visible at a time.
- GridBagLayout: Most flexible layout for advanced positioning.
- BoxLayout: Vertical or horizontal alignment.

Example (FlowLayout):
import [Link].*; public class FlowExample { public static void main(String[] args) { Frame f = new
Frame("FlowLayout"); [Link](new FlowLayout()); [Link](new Button("A")); [Link](new
Button("B")); [Link](200,150); [Link](true); } }
6. List Interface in Java
Definition:
The List interface in Java is part of the [Link] package and extends the Collection interface. It
represents an ordered collection of elements that allows duplicate values and provides
positional access using indexes. Lists maintain the insertion order and are widely used for storing
data dynamically.

Key Features of List Interface:


- Allows duplicate elements.
- Maintains insertion order.
- Provides index-based access (positions start from 0).
- Can store null values.
- Supports iteration using loops and iterators.

Common Implementations of List Interface:

Class Description
ArrayList Dynamic array that increases size automatically. Fast for searching and iteration.
LinkedList Doubly-linked list structure. Fast insertion and deletion operations.
Vector Synchronized dynamic array, thread-safe but slower than ArrayList.
Stack Subclass of Vector implementing LIFO (Last-In-First-Out) principle.

Common Methods of List Interface:


- add(E e) – Adds element to the list.
- add(int index, E e) – Inserts element at a specific position.
- get(int index) – Returns element at given index.
- set(int index, E e) – Replaces element at given index.
- remove(int index) – Removes element at specific index.
- size() – Returns number of elements in the list.
- clear() – Removes all elements.
- iterator() – Returns iterator for traversal.

Example Program:
import [Link].*; public class ListExample { public static void main(String[] args) { List list = new
ArrayList<>(); [Link]("Apple"); [Link]("Banana"); [Link]("Cherry"); [Link]("Apple"); // duplicate
allowed for(String s : list) [Link](s); } } Output:
Apple
Banana
Cherry
Apple

Key Points to Remember:


- List allows duplicates and maintains insertion order.
- Provides random access via index.
- ArrayList is best for frequent reads; LinkedList for frequent insertions.
- Vector and Stack are synchronized versions for thread-safe operations.
Java Program: Product CRUD using JDBC (Type-4) with Oracle
Overview:
This example demonstrates how to insert, delete, update, and display product records (pid, pname, price,
date_of_manufacture, date_of_expiry) using JDBC Type-4 driver for Oracle. Use PreparedStatement, handle dates
with [Link], and use try-with-resources to close resources.
SQL: Create table (run in Oracle SQL*Plus / SQL Developer):
CREATE TABLE product ( pid NUMBER PRIMARY KEY, pname VARCHAR2(100), price NUMBER(10,2), dom
DATE, doe DATE );
Notes on Connection:
• Driver class: [Link] (Type-4 thin driver).
• Typical URL (SID): jdbc:oracle:thin:@HOST:PORT:SID
• Typical URL (service name): jdbc:oracle:thin:@//HOST:PORT/SERVICE
• Replace HOST, PORT, SID/SERVICE, USERNAME, PASSWORD accordingly.
Java Program ([Link]):
import [Link].*; import [Link]; public class ProductCRUD { private static final String URL =
"jdbc:oracle:thin:@localhost:1521:XE"; // change as needed private static final String USER = "your_user"; private
static final String PASS = "your_password"; public static void main(String[] args) throws Exception { try (Scanner sc
= new Scanner([Link])) { [Link]("[Link]"); try (Connection con =
[Link](URL, USER, PASS)) { while (true) { [Link]("\n1-Insert 2-Update 3-Delete
4-Display 5-Exit"); int ch = [Link]([Link]()); if (ch == 5) break; switch (ch) { case 1 ->
insertProduct(con, sc); case 2 -> updateProduct(con, sc); case 3 -> deleteProduct(con, sc); case 4 ->
displayProducts(con); default -> [Link]("Invalid choice"); } } } } } private static void
insertProduct(Connection con, Scanner sc) throws SQLException { String sql = "INSERT INTO product(pid, pname,
price, dom, doe) VALUES (?, ?, ?, ?, ?)"; try (PreparedStatement ps = [Link](sql)) {
[Link]("Enter pid: "); int pid = [Link]([Link]()); [Link]("Enter pname: "); String
pname = [Link](); [Link]("Enter price: "); double price = [Link]([Link]());
[Link]("Enter DOM (yyyy-mm-dd): "); Date dom = [Link]([Link]()); [Link]("Enter
DOE (yyyy-mm-dd): "); Date doe = [Link]([Link]()); [Link](1, pid); [Link](2, pname);
[Link](3, price); [Link](4, dom); [Link](5, doe); int rows = [Link]();
[Link](rows + " row(s) inserted."); } } private static void updateProduct(Connection con, Scanner sc)
throws SQLException { String sql = "UPDATE product SET pname = ?, price = ?, dom = ?, doe = ? WHERE pid =
?"; try (PreparedStatement ps = [Link](sql)) { [Link]("Enter pid to update: "); int pid =
[Link]([Link]()); [Link]("Enter new pname: "); String pname = [Link]();
[Link]("Enter new price: "); double price = [Link]([Link]()); [Link]("Enter
new DOM (yyyy-mm-dd): "); Date dom = [Link]([Link]()); [Link]("Enter new DOE
(yyyy-mm-dd): "); Date doe = [Link]([Link]()); [Link](1, pname); [Link](2, price);
[Link](3, dom); [Link](4, doe); [Link](5, pid); int rows = [Link](); [Link](rows + "
row(s) updated."); } } private static void deleteProduct(Connection con, Scanner sc) throws SQLException { String
sql = "DELETE FROM product WHERE pid = ?"; try (PreparedStatement ps = [Link](sql)) {
[Link]("Enter pid to delete: "); int pid = [Link]([Link]()); [Link](1, pid); int rows =
[Link](); [Link](rows + " row(s) deleted."); } } private static void displayProducts(Connection
con) throws SQLException { String sql = "SELECT pid, pname, price, TO_CHAR(dom,'YYYY-MM-DD') dom,
TO_CHAR(doe,'YYYY-MM-DD') doe FROM product ORDER BY pid"; try (Statement st = [Link]();
ResultSet rs = [Link](sql)) { [Link]("%-6s %-20s %-10s %-12s %-12s%n", "PID", "PNAME",
"PRICE", "DOM", "DOE"); while ([Link]()) { [Link]("%-6d %-20s %-10.2f %-12s %-12s%n",
[Link]("pid"), [Link]("pname"), [Link]("price"), [Link]("dom"), [Link]("doe")); } } } }
Usage Notes:
• Ensure Oracle JDBC driver (ojdbc*.jar) is on the classpath.
• Use correct connection URL and credentials.
• Date input format: yyyy-mm-dd (used by [Link]()).
• Use transactions ([Link](false)) if you need atomic operations.
7. Runnable Interface in Java
Definition:
The Runnable interface in Java is part of the [Link] package and is used to define a task that
can be executed by a thread. It represents a single unit of work that can run concurrently with other
tasks. A class implementing Runnable must define the run() method, which contains the code that
will be executed by the thread.

Purpose:
- To create a thread by implementing the Runnable interface instead of extending the Thread class.
- Allows a class to extend another class while still enabling multithreading.
- Encourages better separation of task logic from thread management.

Runnable Interface Declaration:


public interface Runnable { public abstract void run(); }

Example Program:
class MyRunnable implements Runnable { public void run() { for(int i=1; i<=5; i++) {
[Link]([Link]().getName() + " - Count: " + i); try { [Link](500); }
catch(Exception e) {} } } } public class RunnableExample { public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "Thread-1"); Thread t2 = new Thread(new
MyRunnable(), "Thread-2"); [Link](); [Link](); } } Output:
Thread-1 - Count: 1
Thread-2 - Count: 1
... (execution order may vary)

Difference between Thread class and Runnable interface:

Thread Class Runnable Interface


Used by extending the Thread class. Used by implementing the Runnable interface.
Cannot extend any other class (single inheritance).
Can extend another class (flexible).
Thread code written inside run() of Thread subclass.
Thread code written inside run() of Runnable implementation.
Less flexible for multiple inheritance. More flexible and promotes reusability.

Key Points to Remember:


- Runnable is a functional interface (has one abstract method).
- Helps achieve multithreading by separating task logic from thread control.
- The run() method defines the task; the Thread object executes it.
- Recommended approach for concurrent programming in Java.
Thread and Thread Synchronization in Java
What is a Thread?
A Thread in Java is a lightweight sub-process or the smallest unit of a CPU’s execution. It enables a
program to perform multiple tasks simultaneously, a concept known as multithreading. Each thread runs
in parallel, sharing the same memory but executing independently.
Creating Threads in Java:
Threads can be created in two ways:
1. By extending the Thread class.
2. By implementing the Runnable interface.
Example of Creating a Thread:
class MyThread extends Thread { public void run() { for (int i = 1; i <= 5; i++) { [Link](i); } }
public static void main(String[] args) { MyThread t = new MyThread(); [Link](); // starts the thread } }
Thread Synchronization:
In multithreading, multiple threads may access shared resources simultaneously. This can cause data
inconsistency problems known as race conditions. To prevent this, Java provides synchronization,
which ensures that only one thread can access a shared resource at a time.
Types of Synchronization:
Type Description
Synchronized Method Only one thread can execute a synchronized method of an object at a time.
Synchronized Block Locks only a portion of the code to improve performance.
Static Synchronization Used to synchronize static methods — locks the class, not the instance.

Example of Thread Synchronization:


class Table { synchronized void printTable(int n) { for (int i = 1; i <= 5; i++) { [Link](n * i); } } }
class MyThread1 extends Thread { Table t; MyThread1(Table t) { this.t = t; } public void run() {
[Link](5); } } class MyThread2 extends Thread { Table t; MyThread2(Table t) { this.t = t; } public void
run() { [Link](10); } } public class TestSynchronization { public static void main(String[] args) { Table
obj = new Table(); new MyThread1(obj).start(); new MyThread2(obj).start(); } }
Output:
Each thread executes the printTable() method sequentially, avoiding mixed or inconsistent output.
Key Points to Remember:
• Threads enable concurrent execution of multiple tasks.
• Synchronization prevents data inconsistency and race conditions.
• synchronized keyword ensures only one thread can execute a block/method at a time.
• Overuse of synchronization may reduce performance.
Thread, Wrapper Classes, and Thread Life Cycle in
Java
1. Definition of Thread:
A Thread in Java is a lightweight sub-process or the smallest unit of CPU execution. It represents a
separate path of execution within a program. Multithreading allows multiple tasks to run
simultaneously, enhancing application performance and responsiveness.
Example:
class MyThread extends Thread { public void run() { [Link]("Thread running..."); } }
public class Demo { public static void main(String[] args) { MyThread t = new MyThread(); [Link](); }
}

2. Wrapper Classes:
Wrapper classes are object representations of primitive data types. They are defined in the
[Link] package and are used for converting primitive types into objects (Autoboxing) and vice
versa (Unboxing).
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

3. Thread Life Cycle:


A thread in Java goes through the following states during its life:
1. New – Thread object created but not started.
2. Runnable – Ready to run, waiting for CPU time.
3. Running – Actively executing code.
4. Blocked/Waiting – Waiting for resource or time delay.
5. Terminated – Thread has completed execution.
Lifecycle Diagram:
New → Runnable → Running → Waiting/Blocked → Terminated
Example:
class LifeCycle extends Thread { public void run() { [Link]("Thread running..."); } }
public class Test { public static void main(String[] args) { LifeCycle t = new LifeCycle(); [Link](); } }

Key Points:
- Threads allow multitasking within a single program.
- Wrapper classes convert primitives into objects.
- Thread Life Cycle → New → Runnable → Running → Waiting/Blocked → Terminated.
5. Type Casting in Java
Definition:
Type casting in Java is the process of converting one data type into another. It allows a variable
of one type to be treated as another type. Type casting is mainly used when assigning values
between different data types or working with inheritance.

Why Use Type Casting?


- To make data compatible for mathematical or logical operations.
- To reuse methods that expect a specific type.
- To achieve polymorphism in inheritance (object casting).

Types of Type Casting in Java:

Type Description Example


1. Implicit Casting (Widening)
Automatically converts a smaller data type into a larger data
inttype.
a = 10;
Donedouble
by compiler.
b = a;
2. Explicit Casting (Narrowing)
Manually converts a larger data type into a smaller data type.
double
Possible
x = 9.7;
dataintloss.
y = (int) x;
3. Upcasting (Object Casting)
Casting a subclass object to a superclass reference. Safe and
Parent
automatic.
p = new Child();
4. Downcasting (Object Casting)
Casting a superclass reference back to subclass. Must be explicit.
Child c = (Child) p;

Example Program:
public class TypeCastingExample { public static void main(String[] args) { int a = 10; double b = a; //
Implicit Casting double x = 9.8; int y = (int) x; // Explicit Casting [Link]("Implicit: " + b);
[Link]("Explicit: " + y); } } Output:
Implicit: 10.0
Explicit: 9

Key Points to Remember:


- Widening happens automatically (no data loss).
- Narrowing must be done manually (possible data loss).
- Upcasting is safe and implicit; Downcasting requires explicit cast.
- Type casting ensures compatibility between different data types and objects.
Types of Statements in JDBC
Definition:
In JDBC (Java Database Connectivity), a Statement is an object used to send SQL commands to a
database and retrieve results. They allow Java programs to interact with databases to perform operations
like SELECT, INSERT, UPDATE, and DELETE. JDBC provides three types of statements depending on
the complexity and frequency of query execution.

Types of JDBC Statements:

Type Description When to Use


Statement Used for executing simple SQL queries that do not take parameters.
When queryThe
is static
SQLand
query
used
is compiled
once. e
PreparedStatement Used for executing precompiled SQL statements with or When
withoutsame
parameters.
query runs
Improves
multiple
performanc
times wit
CallableStatement Used to execute stored procedures in the database. Supports
WhenIN,
calling
OUT,stored
and INOUT
procedures.
parameters.

Example Program:
import [Link].*; public class JDBCExample { public static void main(String[] args) throws Exception {
[Link]("[Link]"); Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb", "root", "password"); // Using Statement Statement stmt =
[Link](); ResultSet rs = [Link]("SELECT * FROM employee"); while([Link]())
[Link]([Link](1) + " " + [Link](2)); // Using PreparedStatement PreparedStatement ps =
[Link]("INSERT INTO employee VALUES(?, ?)"); [Link](1, 101); [Link](2, "John");
[Link](); [Link](); } }
Key Points to Remember:
• Statement – Executes static SQL; recompiled each time.
• PreparedStatement – Precompiled and parameterized; faster execution.
• CallableStatement – Executes stored procedures and handles parameters.
• PreparedStatement and CallableStatement are preferred for performance and security.

You might also like