Advance Java
Java Basics: Introduction to Basic Concepts of Java
✅ 1. What is Java?
Java is a high-level, object-oriented, and platform-independent programming language
developed by Sun Microsystems (now Oracle).
🔥 Why Java is Popular?
Simple and easy to learn
Secure
Portable (Write Once, Run Anywhere – WORA)
Used in Android, Web Apps, Games, Banking Systems, etc.
✅ 2. Key Features of Java
Feature Meaning
Object-Oriented Everything is based on classes and objects
Platform Independent Run the same code on any system with JVM
Robust Strong memory management, exception handling
Secure No pointer access, runs in a sandbox
Multithreaded Can perform many tasks simultaneously
Portable Code is converted to bytecode → runs anywhere
✅ 3. Java Program Structure
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Explanation:
Part Meaning
public class Hello Class named Hello
public static void main Starting point of program
String[] args Array of command-line arguments
System.out.println() Prints to the console
Output:
Hello, Java!
✅ 4. What is Bytecode?
When you compile Java code using javac, it turns into bytecode (.class file).
Bytecode is not machine code — it runs inside the JVM.
✅ 5. JVM vs JRE vs JDK
Term Full Form Use
JVM Java Virtual Machine Runs bytecode
Term Full Form Use
JRE Java Runtime Environment JVM + libraries (needed to run Java)
JDK Java Development Kit JRE + compiler + tools (for development)
✅ 6. Constructor and Class Concept in Java
6.1 What is a Class?
A class is like a blueprint or template for creating objects.
Example:
class Student {
int rollNo; // Data members (variables)
String name;
void display() { // Method
System.out.println(rollNo + " " + name);
}
}
6.2 What is an Object?
An object is an instance of a class. Once the class is defined, we can create multiple objects of
that class.
Example:
public class Test {
public static void main(String[] args) {
Student s1 = new Student(); // s1 is an object
s1.rollNo = 101;
s1.name = "Riya";
s1.display(); // Output: 101 Riya
}
}
6.3 What is a Constructor?
A constructor is a special method that is automatically called when an object is created.
It is used to initialize objects.
✅ Important Points:
Constructor name = class name
No return type (not even void)
Automatically called during object creation
6.4 Types of Constructors
Type Description Example
Default Constructor No parameters Student()
Parameterized
Takes parameters Student(int id, String name)
Constructor
Copies one object to another (manual in Student s2 = new
Copy Constructor
Java) Student(s1);
Example: All Constructors
class Student {
int rollNo;
String name;
// Default constructor
Student() {
rollNo = 0;
name = "Unknown";
}
// Parameterized constructor
Student(int r, String n) {
rollNo = r;
name = n;
}
// Display method
void display() {
System.out.println(rollNo + " " + name);
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(); // Default constructor
Student s2 = new Student(101, "Riya"); // Parameterized constructor
s1.display(); // Output: 0 Unknown
s2.display(); // Output: 101 Riya
}
}
6.5 Constructor vs Method
Constructor Method
Same name as class Can have any name
No return type Has return type
Called automatically Called manually
✅ 7. Arrays in Java
(Concept of arrays of primitives and objects – 1D and 2D)
🔹 7.1 What is an Array?
An array is a collection of similar types of elements stored in contiguous memory locations.
🔑 Key Points:
Array size is fixed.
Arrays are indexed (starting from 0).
Arrays can hold primitive data types (like int, char, etc.) or objects.
🔹 7.2 One-Dimensional Array (1D)
✅ Syntax:
java
CopyEdit
dataType[] arrayName = new dataType[size];
📘 Example: 1D Array of Integers
java
CopyEdit
int[] marks = new int[5]; // Declaration + memory allocation
marks[0] = 90;
marks[1] = 80;// ...
💡 Shortcut Initialization:
java
CopyEdit
int[] marks = {90, 80, 85, 95, 88};
🔄 Traversing:
java
CopyEdit
for (int i = 0; i < marks.length; i++) {
System.out.println(marks[i]);
}
🔹 7.3 Two-Dimensional Array (2D)
A 2D array is like a table (rows and columns).
✅ Syntax:
java
CopyEdit
dataType[][] arrayName = new dataType[rows][columns];
📘 Example:
java
CopyEdit
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
🔄 Traversing:
java
CopyEdit
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
🔹 7.4 Array of Objects
You can also create arrays of class objects.
📘 Example:
java
CopyEdit
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
void display() {
System.out.println(id + " " + name);
}
}
java
CopyEdit
public class Test {
public static void main(String[] args) {
Student[] arr = new Student[2];
arr[0] = new Student(1, "Riya");
arr[1] = new Student(2, "Arya");
for (Student s : arr) {
s.display();
}
}
}
8. Inheritance in Java
🔹 8.1 What is Inheritance?
Inheritance is a mechanism in Java where one class (child) can acquire properties and
behaviors (fields and methods)of another class (parent).
🔁 It allows code reusability and supports the "is-a" relationship between classes.
🔹 8.2 Real-Life Example
Think of a “Car” class and a “ElectricCar” class.
Car has common properties: speed, engine, wheels.
ElectricCar inherits those properties + adds its own: battery, charge time.
java
CopyEdit
class Car {
int speed = 100;
void drive() {
System.out.println("Driving at " + speed + " km/h");
}
}
class ElectricCar extends Car {
int battery = 80;
void charge() {
System.out.println("Charging with " + battery + "% battery");
}
}
public class Test {
public static void main(String[] args) {
ElectricCar e = new ElectricCar();
e.drive(); // inherited from Car
e.charge(); // own method
}
}
🔹 8.3 Syntax of Inheritance
java
CopyEdit
class Parent {
// fields and methods
}
class Child extends Parent {
// child-specific code
}
🔹 8.4 Types of Inheritance in Java
Type Supported in Java? Diagram
Single Inheritance ✅ Yes A→B
Multilevel Inheritance ✅ Yes A→B→C
Hierarchical Inheritance ✅ Yes A → B and A → C
Multiple Inheritance (with classes) ❌ No ✘ Not allowed directly (ambiguity)
Multiple Inheritance (with interfaces) ✅ Yes ✔️Allowed with implements
🔹 8.5 Types Explained with Diagrams
✅ Single Inheritance:
java
CopyEdit
class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
void bark() { System.out.println("Dog barks"); }
}
🧠 Diagram:
nginx
CopyEdit
Animal
↓
Dog
✅ Multilevel Inheritance:
java
CopyEdit
class Animal {
void eat() { System.out.println("Eating"); }
}class Dog extends Animal {
void bark() { System.out.println("Barking"); }
}class Puppy extends Dog {
void weep() { System.out.println("Weeping"); }
}
🧠 Diagram:
nginx
CopyEdit
Animal
↓
Dog
↓
Puppy
✅ Hierarchical Inheritance:
java
CopyEdit
class Animal {
void sound() { System.out.println("Animal sound"); }
}class Dog extends Animal {}class Cat extends Animal {}
🧠 Diagram:
markdown
CopyEdit
Animal
/ \
Dog Cat
❌ Multiple Inheritance (via class – Not allowed):
java
CopyEdit
class A {}class B {}class C extends A, B {} // ❌ Error in Java
✅ Multiple Inheritance using Interfaces:
java
CopyEdit
interface A { void methodA(); }interface B { void methodB(); }
class C implements A, B {
public void methodA() { System.out.println("A"); }
public void methodB() { System.out.println("B"); }
}
🔹 8.6 Why Inheritance?
Reusability
Method Overriding (Runtime Polymorphism)
Cleaner Code (DRY Principle)
🔹 8.7 Access Modifiers & Inheritance
Modifier Accessible in child?
public ✅ Yes
protected ✅ Yes
default 🚫 (only in same package)
private ❌ No
✅ 9. Exception Handling in Java
🔹 9.1 What is an Exception?
An exception is an unexpected error that occurs during runtime (while your code is running),
which disrupts the normal flow of your program.
📌 Example: Dividing by zero, accessing an invalid array index, file not found, etc.
🔹 9.2 Real-Life Example
Imagine:
You're making a payment online.
Suddenly internet disconnects.
This "internet disconnection" is like an exception in your program that must be handled to
avoid crashing or data loss.
🔹 9.3 Why Exception Handling?
Prevents program crash
Allows us to give a user-friendly message
Helps to debug easily
🔹 9.4 Types of Exceptions
Java exceptions are broadly divided into two:
Type Description Example
Compiler checks
them. You must
✅ Checked
handle them IOException, SQLException, FileNotFoundException
Exception
using try-catch o
r throws.
Compiler doesn't
check. Happens
✅ Unchecked
due to ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException
Exception
programming
bugs.
🔹 9.5 Exception Hierarchy (Diagram)
php
CopyEdit
Object
↓Throwable
↓ ↓Exception Error (We don’t handle errors)
↓RuntimeException
🔹 9.6 Java Exception Handling Keywords
Keyword Use
try Code that might throw exception
catch Code to handle exception
finally Code that always runs (like closing files)
throw Used to manually throw an exception
throws Used in method signature to declare exception
🔹 9.7 Example: Basic try-catch
java
CopyEdit
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}
Output:
csharp
CopyEdit
Cannot divide by zero!
🔹 9.8 Example: finally block
java
CopyEdit
try {
int a[] = new int[5];
a[5] = 100; // ArrayIndexOutOfBoundsException
} catch (Exception e) {
System.out.println("Handled: " + e);
} finally {
System.out.println("This always runs!");
}
🔹 9.9 throw and throws example
👉 throw (manually throw exception):
java
CopyEdit
throw new ArithmeticException("You can't divide by zero!");
👉 throws (used in method header):
java
CopyEdit
void readFile() throws IOException {
// file reading code
}
✅ 10. Collection Framework in Java
🔸 10.1 What is Collection Framework?
Collection Framework is a unified architecture (well-structured system) in Java to store,
manipulate, and retrieve data efficiently.
🔍 Think of it like:
Just like we use shelves, boxes, or containers to organize physical items — Java
Collections provide containers to store multiple objects dynamically.
✅ Why do we need it?
Before Java 1.2, we used Arrays, Vector, or Hashtable, but:
They were fixed in size
Not consistent
No built-in sorting/searching features
➡ Java introduced Collection Framework to solve this — dynamic, flexible, powerful.
🔸 10.2 Key Interfaces in Collection Framework
yaml
CopyEdit
Iterable
|
Collection _______|________
| | |
List Set Queue
| ArrayList, LinkedList, Vector
Iterable → root interface to iterate (loop)
Collection → base interface for all collections
List → stores ordered, duplicate-allowed data
Set → stores unique data
Queue → stores in FIFO order
🔸 10.3 Key Classes
Interface Implementing Classes
List ArrayList, LinkedList, Vector
Interface Implementing Classes
Set HashSet, TreeSet, LinkedHashSet
Queue PriorityQueue, LinkedList
Map* HashMap, TreeMap
Map is not part of Collection but still used similarly.
🔸 10.4 List Interface in Detail
List allows:
Ordered data
Duplicates
Indexing (you can access using index like array)
🔹 A. ArrayList
Resizable array
Fast for searching, slow for inserting/deleting in middle
📘 Code:
java
CopyEdit
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Riya");
list.add("Arora");
list.add("Riya"); // Allows duplicate
System.out.println(list); // [Riya, Arora, Riya]
}
}
📌 Key Points:
Maintains insertion order
Access by index
Duplicates allowed
🔹 B. LinkedList
Doubly linked list
Fast for insertion/deletion
Implements both List and Queue
📘 Code:
java
CopyEdit
import java.util.LinkedList;
public class Example {
public static void main(String[] args) {
LinkedList<Integer> nums = new LinkedList<>();
nums.add(10);
nums.addFirst(5); // adds at beginning
nums.addLast(20); // adds at end
System.out.println(nums); // [5, 10, 20]
}
}
📌 Key Points:
Good for frequent add/remove
Slightly slower search than ArrayList
🔹 C. Vector
Synchronized (thread-safe)
Similar to ArrayList but slower due to synchronization
📘 Code:
java
CopyEdit
import java.util.Vector;
public class Example {
public static void main(String[] args) {
Vector<String> v = new Vector<>();
v.add("A");
v.add("B");
System.out.println(v); // [A, B]
}
}
📌 Key Points:
Rarely used now, replaced by ArrayList + manual sync if needed
🔸 10.5 Collection Framework Diagram (Hierarchy)
Iterable
|
Collection ______|________
| | |
List Set Queue
| ___________________________
| | |ArrayList LinkedList Vector
✅ 11. Collection Classes
🔸 11.1. Iterable & Collection Interface
Iterable is the top-level interface → anything that can be looped using a for-each loop.
Collection interface extends Iterable and provides methods to manipulate a group of objects.
java
CopyEdit
Collection<String> list = new ArrayList<>();
This allows use of polymorphism (you can switch implementation later).
🔸 11.2. Common Methods of Collection Interface
Method Purpose
add(E e) Adds element
remove(E e) Removes element
clear() Removes all elements
size() Returns number of elements
contains(E e) Checks if element exists
isEmpty() Checks if collection is empty
iterator() Returns an iterator for traversal
🔸 11.3. Properties of List Collection (ArrayList, LinkedList, Vector)
Property Description
Ordered Maintains insertion order
Indexing Can access using index (like array)
Duplicates Allowed
Null Values Allowed
🔸 11.4. ArrayList vs LinkedList
Feature ArrayList LinkedList
Internal storage Dynamic array Doubly linked list
Access time Fast (O(1)) for get() Slow (O(n)) for get()
Insertion/Deletion Slow in middle (O(n)) Fast (O(1) if node known)
Memory Less overhead More (because of pointers)
Use case Frequent read Frequent insert/delete
📘 Program Example for Comparison
java
CopyEdit
ArrayList<String> a = new ArrayList<>();
a.add("Riya");
System.out.println(a.get(0)); // Fast access
LinkedList<String> l = new LinkedList<>();
l.add("Riya");
System.out.println(l.get(0)); // Slower than ArrayList
🔸 11.5. Conversions Between Collections
A. ArrayList to Vector
java
CopyEdit
ArrayList<String> al = new ArrayList<>();
al.add("Java");
Vector<String> v = new Vector<>(al);
B. Vector to LinkedList
java
CopyEdit
Vector<String> v = new Vector<>();
v.add("Data");
LinkedList<String> ll = new LinkedList<>(v);
✅ These conversions are useful when using legacy code or multithreading (Vector is
synchronized).
🔸 11.6. Traversing Collections
There are 4 ways to traverse:
1. For-each loop
java
CopyEdit
for (String s : list) {
System.out.println(s);
}
2. Traditional for loop
java
CopyEdit
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
3. Iterator
java
CopyEdit
Iterator<String> it = list.iterator();while (it.hasNext()) {
System.out.println(it.next());
}
4. ListIterator (Only for Lists – forward + backward)
java
CopyEdit
ListIterator<String> lit = list.listIterator();while (lit.hasNext()) {
System.out.println(lit.next());
}
✨ Smart Tip for Exams:
Use ListIterator when backward traversal is needed — it is not available in Sets.
🔸 11.7. Stack in Java
Stack works on LIFO: Last-In, First-Out.
Java provides Stack<E> as part of Collection.
📘 Code Example
java
CopyEdit
import java.util.*;
public class StackExample {
public static void main(String[] args) {
Stack<Integer> s = new Stack<>();
s.push(10); // add
s.push(20);
s.pop(); // remove top
System.out.println(s.peek()); // view top
}
}
Method Use
push() Add element
pop() Remove top element
peek() See top element
isEmpty() Check if stack is empty
🔸 11.8. Important Specific Methods of List
Method Purpose
add(index, element) Add element at specific position
remove(index) Remove element by index
set(index, element) Update element at index
indexOf(element) Returns index of element
lastIndexOf() Returns last index
📘 Smart Example
java
CopyEdit
ArrayList<String> list = new ArrayList<>();
list.add("Riya");
list.add("Arora");
list.set(1, "AI Engineer");
System.out.println(list); // [Riya, AI Engineer]
✅ 12. Collection Classes (Part 2)
Focus: Deque Interface, HashSet & TreeSet, ListIterator
Goal: Complete theory + practical code + smart comparisons so you can write 10-mark
answers easily.
🔶 12.1 Deque Interface: Supports Both LIFO and FIFO
Deque stands for Double-Ended Queue → allows insertion/removal at both ends.
FIFO → First In First Out → like a queue
LIFO → Last In First Out → like a stack
Implemented by classes: ArrayDeque, LinkedList
📌 Methods of Deque
Method Purpose
addFirst(e) Inserts at the front (LIFO)
addLast(e) Inserts at the back (FIFO)
removeFirst() Removes from front
removeLast() Removes from back
peekFirst() Returns front without removing
peekLast() Returns last without removing
📘 Java Example:
java
CopyEdit
import java.util.*;
public class DequeExample {
public static void main(String[] args) {
Deque<String> dq = new ArrayDeque<>();
// FIFO
dq.addLast("Java");
dq.addLast("Python");
System.out.println(dq.removeFirst()); // Java
// LIFO
dq.addFirst("C++");
dq.addFirst("HTML");
System.out.println(dq.removeFirst()); // HTML
}
}
✅ Best Use: Browser history (back-forward), undo-redo systems
🔶 12.2 Set Usage: HashSet and TreeSet
Both are part of the Set interface, but they behave differently.
🔹 HashSet
Unordered, stores unique elements
Fast (uses hashing)
java
CopyEdit
Set<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("Java"); // Duplicate - ignored
System.out.println(set); // Unordered output
🔹 TreeSet
Sorted set (natural order like alphabetic or numeric)
Slower than HashSet
Cannot store null if using comparison
java
CopyEdit
Set<String> set = new TreeSet<>();
set.add("Zebra");
set.add("Apple");
System.out.println(set); // Apple, Zebra
✅ Use TreeSet when sorting is important (like leaderboard, dictionary)
🔶 12.3 ListIterator (vs Iterator)
📌 ListIterator is a bi-directional iterator → only used for List-based
collections
🛑 Cannot be used on Set or Map.
🔹 Key Features:
Feature Iterator ListIterator
Forward traversal ✅ Yes ✅ Yes
Backward traversal ❌ No ✅ Yes
Can modify during loop ❌ No ✅ Yes (with add(), remove(), set())
Index access ❌ No ✅ Yes
📘 Java Example:
java
CopyEdit
import java.util.*;
public class ListIteratorExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Riya", "Arora", "AI"));
ListIterator<String> li = names.listIterator();
System.out.println("Forward:");
while (li.hasNext()) {
System.out.println(li.next());
}
System.out.println("Backward:");
while (li.hasPrevious()) {
System.out.println(li.previous());
}
}
}
✅ Use ListIterator when you want full control of direction and editing while iterating.
✨ Smart Chart for Exams
Feature HashSet TreeSet Deque ListIterator
✅ Maintains
Order ❌ Unordered ✅ Sorted ❌ Optional
order
❌ No
Null Allowed ✅ Yes ✅ Yes ✅ Yes
(NullPointerException)
❌ Not
Duplicate ❌ Not allowed ✅ Allowed ✅ Allowed
allowed
Backward ❌ No ❌ No ✅ removeLast() ✅ hasPrevious()
Feature HashSet TreeSet Deque ListIterator
Move
Index Access ❌ No ❌ No ❌ No ✅ Yes
✅ 13. AWT Components & Layout Manager
🔶 13.1 AWT Basics
AWT (Abstract Window Toolkit) is a part of Java for creating Graphical User Interfaces
(GUI).
Belongs to: java.awt package
Platform-dependent (uses OS components – called heavyweight)
Used to build windows, buttons, text fields, labels, etc.
🧩 Common AWT Classes:
Class Use
Frame Main window
Button Clickable button
Label Displays static text
TextField Input box for a single line
TextArea Multiline input
Checkbox Box for yes/no option
🔶 13.2 AWT Hierarchy (Diagram)
mathematica
CopyEdit
java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ java.awt.Panel
↳ java.awt.Window
↳ java.awt.Frame
↳ java.awt.Dialog
Component: Base class for all UI elements
Container: Can hold multiple components
Frame: Main top-level window
Panel: A blank space to hold components
🔶 13.3 Component Class
All GUI elements like Button, Label, etc., inherit from Component class.
Key Methods of Component class:
Method Description
setSize() Set width and height
setLayout() Set layout manager
setVisible() Show/hide the component
setBackground() Set background color
13.4 Layout Managers
Used to arrange components automatically inside a container (like Frame or Panel).
1. BorderLayout (Default for Frame)
Divides container into 5 areas:
North, South, East, West, Center
setLayout(new BorderLayout());
add(new Button("North"), BorderLayout.NORTH);
2. FlowLayout (Default for Panel)
Places components in a row, left to right.
Wraps to next line if space ends.
setLayout(new FlowLayout());
add(new Button("A"));
add(new Button("B"));
3. GridLayout
Makes a grid of equal-sized cells.
You specify rows and columns.
setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns
Mini Sample Code
import java.awt.*;
public class LayoutDemo {
public static void main(String[] args) {
Frame f = new Frame("AWT Layout Example");
f.setLayout(new BorderLayout());
f.add(new Button("North"), BorderLayout.NORTH);
f.add(new Button("South"), BorderLayout.SOUTH);
f.add(new Button("East"), BorderLayout.EAST);
f.add(new Button("West"), BorderLayout.WEST);
f.add(new Button("Center"), BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
}
}
✅ 14. Swing in Java
🔶 14.1 What is Swing?
🔹 Swing is a part of Java used to create GUI (Graphical User Interface) apps.
Comes from javax.swing package
Lightweight: Doesn't depend on OS components
More powerful and flexible than AWT
Built on top of AWT but with pluggable look and feel
📌 AWT vs Swing
Feature AWT Swing
Platform OS dependent Pure Java (cross-platform)
Weight Heavyweight Lightweight
Package java.awt javax.swing
Look & Feel Native Customizable
🔶 14.2 Swing Class Hierarchy
markdown
CopyEdit
java.lang.Object
↳ java.awt.Component ↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.JFrame
↳ javax.swing.JPanel
↳ javax.swing.JButton
↳ javax.swing.JLabel
↳ javax.swing.JTextField
JComponent: Base class for all Swing components (buttons, labels, etc.)
JFrame: Top-level window
JButton, JLabel, JTextField → Visual components added to frame
🔶 14.3 Common Swing Components
Component Description
JFrame Window to hold components
JLabel Text display (read-only)
JButton Clickable button
JTextField Single-line text input
JTextArea Multi-line text input
JCheckBox Box for multiple options
JRadioButton One selection from many
JComboBox Drop-down menu
JList List of selectable items
🔶 14.4 JComponent Class – Important Methods
JComponent provides common behavior to all Swing components.
Useful methods:
Method Use
setBackground(Color c) Set background color
setForeground(Color c) Set text color
setToolTipText(String) Help popup on hover
setFont(Font f) Change text font
setVisible(true/false) Show or hide
setEnabled(true/false) Enable/disable
🔶 14.5 How to Create a Frame in Swing
✅ Basic steps:
Create a class extending JFrame
Create components (JButton, JLabel, etc.)
Add components to frame
Set layout
Set size, visibility
🧾 Example Code:
java
CopyEdit
import javax.swing.*;
public class MySwingFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Swing App");
JLabel label = new JLabel("Hello, Swing!");
JButton button = new JButton("Click Me");
frame.setLayout(null); // No layout manager
label.setBounds(50, 50, 100, 30);
button.setBounds(50, 100, 100, 30);
frame.add(label);
frame.add(button);
frame.setSize(300, 250);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
✅ 15. JComponent & Swing Components
🔶 15.1 What is JComponent?
JComponent is the base class for all Swing UI components like buttons, labels, etc.
It extends Container and adds features like:
Tooltips
Borders
Double-buffering
Custom painting
All Swing widgets like JButton, JLabel, etc. inherit from JComponent.
🔶 15.2 Important Swing Components from JComponent
Let’s learn one-by-one with example code.
🔹 1. JButton – Button component
Used to perform an action when clicked.
java
CopyEdit
JButton button = new JButton("Click Me");
🧠 Methods:
setText("...")
setEnabled(true/false)
addActionListener(...) → For handling clicks
🔹 2. JLabel – Displays text
java
CopyEdit
JLabel label = new JLabel("Welcome!");
🧠 Use: Display non-editable text, messages, or output.
🔹 3. JTextField – Single-line text input
java
CopyEdit
JTextField textField = new JTextField(20); // 20 columns width
🧠 Use: Input from user
🧠 Methods:
getText() → Get input
setText(...) → Set value
🔹 4. JCheckBox – Multiple selections possible
java
CopyEdit
JCheckBox box1 = new JCheckBox("C++");JCheckBox box2 = new JCheckBox("Java");
🧠 Use: Choose multiple options (like "interests")
🧠 Method: isSelected() → returns true if selected
🔹 5. JRadioButton – Only one selected in a group
java
CopyEdit
JRadioButton male = new JRadioButton("Male");JRadioButton female = new
JRadioButton("Female");ButtonGroup bg = new ButtonGroup();
bg.add(male);
bg.add(female);
🧠 Use: Choose one among many (like Gender)
🔹 6. JComboBox – Drop-down list
java
CopyEdit
String[] languages = {"C++", "Java", "Python"};
JComboBox<String> combo = new JComboBox<>(languages);
🧠 Use: Select one from dropdown
🧠 Method: getSelectedItem()
🔹 7. JList – Scrollable list of items
java
CopyEdit
String[] cities = {"Delhi", "Mumbai", "Pune"};
JList<String> list = new JList<>(cities);
🧠 Use: List multiple options
🧠 Method: getSelectedValue()
🔸 GUI Example with All Components
java
CopyEdit
import javax.swing.*;
public class AllComponentsExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Components");
frame.setLayout(null);
JLabel label = new JLabel("Enter Name:");
label.setBounds(20, 20, 100, 30);
JTextField tf = new JTextField();
tf.setBounds(120, 20, 150, 30);
JCheckBox cb1 = new JCheckBox("C++");
cb1.setBounds(20, 60, 100, 30);
JCheckBox cb2 = new JCheckBox("Java");
cb2.setBounds(120, 60, 100, 30);
JRadioButton rb1 = new JRadioButton("Male");
rb1.setBounds(20, 100, 80, 30);
JRadioButton rb2 = new JRadioButton("Female");
rb2.setBounds(120, 100, 80, 30);
ButtonGroup gender = new ButtonGroup();
gender.add(rb1);
gender.add(rb2);
JButton btn = new JButton("Submit");
btn.setBounds(20, 140, 100, 30);
frame.add(label); frame.add(tf);
frame.add(cb1); frame.add(cb2);
frame.add(rb1); frame.add(rb2);
frame.add(btn);
frame.setSize(300, 250);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
🔶 15.3 AWT vs Swing (Must Write Table)
Feature AWT Swing
Package java.awt javax.swing
Platform Dependence Dependent on OS GUI Fully written in Java (cross-platform)
Components Heavyweight (native) Lightweight (non-native)
Look and Feel Native OS Pluggable look and feel
Thread Safety Not guaranteed Mostly thread safe
Features Basic UI Advanced features (tooltips, borders)
✅ 16. Event Handling in Java
🔶 16.1 What is Event Handling?
In GUI apps, when the user clicks a button, moves the mouse, or types something, Java
detects and handles it — this is event handling.
🔶 16.2 Event Delegation Model (EDM)
This is Java’s mechanism to handle events.
🧠 Delegation means passing responsibility to another object.
🔁 In EDM:
Source: Component that generates event (e.g., JButton)
Listener: Object that listens and reacts (e.g., class implementing ActionListener)
🧩 Think of it like:
User clicks → Button creates event → Listener handles event
📌 Example:
java
CopyEdit
JButton b = new JButton("Click");
b.addActionListener(new MyListener());
🔶 16.3 Event Classes
Event objects carry info about what happened (who clicked, what key pressed, etc.)
Event Class Description
ActionEvent Button clicks, menu selection
MouseEvent Mouse click, move, press, release
KeyEvent Key press, release
ItemEvent Checkbox, ComboBox selection change
WindowEvent Window opened, closed
🔶 16.4 Event Source
A source is any UI component that can generate events.
Examples:
JButton → generates ActionEvent
JTextField → generates ActionEvent
JCheckBox → generates ItemEvent
🔶 16.5 Event Listener Interfaces
Listeners are interfaces with methods that handle events.
Listener Interface Method(s) Used For
ActionListener actionPerformed(ActionEvent e) Button click
MouseListener mouseClicked, mousePressed, etc. Mouse events
KeyListener keyPressed, keyReleased Keyboard events
ItemListener itemStateChanged Checkbox, combo box
WindowListener windowClosing, windowOpened Window actions
🧠 All these are functional interfaces → you implement them or use lambda.
🔶 16.6 Code Example – ActionListener with JButton
java
CopyEdit
import javax.swing.*;import java.awt.event.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Demo");
JButton button = new JButton("Click Me");
button.setBounds(100, 100, 100, 40);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
🔶 16.7 Adapter Classes
If you implement MouseListener, you have to override all 5 methods even if you need just
one.
To solve this, Java provides Adapter classes (like MouseAdapter, KeyAdapter).
🧠 Adapter = Partial listener (you override only needed methods)
🔁 Example with MouseAdapter:
java
CopyEdit
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at " + e.getX() + "," + e.getY());
}
});
✅ Saves time and code
✅ 18. JDBC Connectivity: Application
🔶 18.1 Recap: Basic Flow of JDBC
Load driver
Connect to DB
Write and execute SQL
Get results
Close everything
Now let’s go deeper into:
🔹 18.2 SQL Statements in JDBC
There are two main ways to execute SQL:
Type Use For Secure?
Statement Simple, fixed queries ❌ Not secure (SQL injection risk)
PreparedStatement Dynamic queries with input ✅ Secure and fast
🔸 A. Using Statement
java
CopyEdit
Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery("SELECT * FROM
users");
Best for static/fixed queries
Risk of SQL injection if user input is added directly
🔸 B. Using PreparedStatement (Recommended ✅)
java
CopyEdit
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 101); // Set value for '?'ResultSet rs = pstmt.executeQuery();
✅ Why better?
Avoids SQL injection
Automatically escapes user inputs
Used for INSERT, UPDATE, DELETE, SELECT
🔶 18.3 Inserting Data – Example
java
CopyEdit
PreparedStatement pstmt = con.prepareStatement("INSERT INTO users VALUES (?, ?)");
pstmt.setInt(1, 102);
pstmt.setString(2, "Riya");int i = pstmt.executeUpdate();
System.out.println(i + " record inserted.");
executeUpdate() is used for insert/update/delete
It returns the number of rows affected
🔶 18.4 Retrieving Data – Full Example
java
CopyEdit
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM users");ResultSet rs =
pstmt.executeQuery();
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " - " + name);
}
rs.next() → moves the pointer to next row
rs.getInt("column_name") → get column value
🔖 Key Points to Write in Exams (10 marks answer)
Brief JDBC intro
Mention of Statement vs PreparedStatement
Code of:
INSERT
SELECT
Clear explanation of ResultSet
Proper closing of resources:
java
CopyEdit
rs.close();
pstmt.close();
con.close();