Java Note
Java Note
Notes
1. Collection Interface (Root Interface)
The Collection interface is the root of the Java Collection Framework. It represents a
group of objects and provides basic methods to work with collections.
• Key Methods:
o add(E e): Adds an element to the collection.
o remove(Object o): Removes an element.
o size(): Returns the size of the collection.
o isEmpty(): Checks if the collection is empty.
o iterator(): Returns an iterator for the collection.
Implementations of List:
Implementations of Set:
Implementations of Queue:
Implementations of Deque:
Summary
1. List: Ordered, allows duplicates. (ArrayList, LinkedList, Vector, Stack)
2. Set: Unordered, no duplicates. (HashSet, LinkedHashSet, TreeSet)
3. Queue: FIFO, process elements in order. (LinkedList, PriorityQueue)
4. Deque: Allows adding/removing from both ends. (ArrayDeque, LinkedList)
5. Map: Key-value pairs, unique keys. (HashMap, LinkedHashMap, TreeMap,
Hashtable)
Allows Key
Collecti Maintain Access
Duplica Use Case Implementatio
on Type s Order Method
tes ns
Ordered collection
with possible
duplicates.
ArrayList,
Index- Suitable when
List Yes Yes LinkedList,
based precise control
Vector, Stack
over element
positions is
required.
Collection of
unique elements.
No HashSet,
Element- Ideal when
Set No (unordere LinkedHashSet,
based uniqueness is a
d) TreeSet
priority, and order
is not a concern.
First-In-First-Out
collection. Used
LinkedList,
Element- for scheduling
Queue Yes Yes (FIFO) PriorityQueue,
based tasks or handling
ArrayDeque
data in the order it
was received.
Double-Ended
Queue allowing
insertion and
Yes (both Element- removal from both ArrayDeque,
Deque Yes
ends) based ends. Useful for LinkedList
implementing
stacks and
queues.
Collection of key-
HashMap,
No value pairs. Each
No LinkedHashMa
Map (unordere Key-based key maps to a
(keys) p, TreeMap,
d) single value,
Hashtable
suitable for
associative arrays
or dictionaries.
• ArrayList:
o Allows duplicates
o Maintains insertion order
o Provides fast random access (O(1))
o Slower insertion and deletion at middle (O(n))
• LinkedList:
o Allows duplicates
o Maintains insertion order
o Faster insertion and deletion at both ends (O(1))
o Can act as both a List and a Queue or Deque
• Vector:
o Allows duplicates
o Maintains insertion order
o Synchronized (thread-safe)
o Slower performance due to synchronization overhead
• Stack:
o Extends Vector
o Follows LIFO (Last-In-First-Out) order
o Provides stack operations like push(), pop(), and peek()
• HashSet:
o Does not allow duplicates
o Does not maintain insertion order
o Offers fast lookups, insertions, and deletions (O(1))
• LinkedHashSet:
o Does not allow duplicates
o Maintains insertion order
o More efficient than TreeSet for ordered sets
• TreeSet:
o Does not allow duplicates
o Elements are sorted (natural or by comparator)
o Slower (O(log n)) due to tree-based structure
• PriorityQueue:
o Allows duplicates
o Does not maintain insertion order (elements sorted by priority)
o Often used for priority scheduling
• ArrayDeque:
o Allows duplicates
o Maintains insertion order
o Can act as both a Queue and a Deque
o More efficient than Stack
• HashMap:
o Does not allow duplicate keys (but values can be duplicated)
o Does not maintain insertion order
o Offers fast lookups, insertions, and deletions (O(1))
• LinkedHashMap:
o Does not allow duplicate keys (but values can be duplicated)
o Maintains insertion order
o Slightly slower than HashMap due to maintaining order
• TreeMap:
o Does not allow duplicate keys (but values can be duplicated)
o Keys are sorted (natural or by comparator)
o Slower (O(log n)) due to tree-based structure
• Hashtable:
o Does not allow duplicate keys (but values can be duplicated)
o Synchronized (thread-safe)
o Slower performance due to synchronization overhead
Definition: An exception is an event that disrupts the normal flow of the program's
execution. It is an object that wraps an error or unusual condition that occurs during
program execution.
Types of Exceptions
1. Checked Exceptions:
Exceptions that must either be caught using a try-catch block or declared in the
method signature using throws. Example: IOException, SQLException. Cause:
Typically occurs due to external factors (e.g., file operations, network issues).
public void readFile(String file) throws IOException {
// Code that might throw IOException
}
3. Errors:
Serious problems that usually cannot be handled by the program (e.g., JVM or
system failures). Example: OutOfMemoryError, StackOverflowError. Cause:
System-level failures beyond the program's control.
1. try-catch
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
2. finally
try {
FileReader fr = new FileReader("file.txt");
} catch (IOException e) {
System.out.println("File not found!");
} finally {
fr.close(); // Always executed
}
3. throw
4. throws
Summary Table:
File handling refers to the ability to manipulate files: create, delete, read, write, and
modify them. Java provides the File class to perform these tasks.
• File Class:
o The File class represents a file or directory path.
o It provides methods like createNewFile(), delete(), exists(), renameTo(),
and more to work with files and directories.
1. Create a File:
a. createNewFile() method is used to create a new empty file.
b. If the file already exists, this method returns false.
import java.io.File;
import java.io.IOException;
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
}
}
2. Delete a File:
a. delete() method is used to delete a file or directory.
if (file.exists()) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
What is a Stream?
Types of Streams
1. Byte Streams:
a. Byte streams handle I/O of raw binary data (8 bits).
b. They are used for all kinds of I/O, such as image, video, and audio files,
and work with binary files.
c. Classes in Byte Streams:
i. FileInputStream (for reading binary data)
ii. FileOutputStream (for writing binary data)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
int data;
while ((data = input.read()) != -1) {
output.write(data);
}
input.close();
output.close();
}
}
2. Character Streams:
a. Character streams handle I/O of character data (16 bits). They are
specifically designed for handling text data.
b. Classes in Character Streams:
i. FileReader (for reading character data)
ii. FileWriter (for writing character data)
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
int character;
while ((character = reader.read()) != -1) {
writer.write(character);
}
reader.close();
writer.close();
}
}
Buffered Streams
Buffered streams improve I/O performance by reading or writing data in larger chunks,
minimizing the number of I/O operations.
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine(); // To add new line after each line
}
reader.close();
writer.close();
}
}
• Explanation: This example reads a file line by line using BufferedReader and
writes each line to a new file using BufferedWriter.
Example:
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
// Deserialize
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("person.ser"));
Person deserializedPerson = (Person) in.readObject();
System.out.println(deserializedPerson.name + " " + deserializedPerson.age);
in.close();
}
}
• Explanation: The Person object is serialized to a file and then deserialized back
into an object.
File Handling in Detail:
File handling is essential in any programming language, and Java provides easy-to-use
classes for managing files. These operations include reading, writing, creating, deleting,
renaming, and modifying files.
Example:
import java.io.File;
Summary:
These I/O mechanisms make Java a powerful tool for working with files, networks, and
other forms of input/output.
Java Beans:
Java Beans are classes in Java that follow a specific convention. They are used to
encapsulate multiple objects into a single object (a bean). The main purpose of Java
Beans is to represent data in a consistent way and allow easy manipulation of that data.
Java Beans are typically used in Enterprise Applications, GUI Development, and for
Data Transfer Objects (DTOs) in applications. They simplify the management of
complex data in Java applications.
import java.io.Serializable;
Explanation:
• Data Transfer: When you need to transfer data between layers in a software
application, like from a database to a web page.
• Encapsulation: To ensure that data is accessed and modified in a controlled
manner using getters and setters.
• Framework Integration: Many Java frameworks, like Spring, rely on Java Beans
for configuration and data binding.
Summary:
• Java Beans are reusable software components that follow certain conventions
(e.g., private fields, public no-argument constructor, getter and setter methods).
• Used for: Encapsulating data, transferring data between layers, or simplifying
data manipulation.
• Example: A class representing a Person with properties like name and age,
which can be accessed and modified through getter and setter methods.
Before diving into Java multithreading, let's understand some fundamental concepts:
Term Description
Processo The hardware that executes instructions. Modern CPUs have multiple
r (CPU) cores.
Process An executing instance of a program. Each process runs independently
with its own memory.
Thread A lightweight process that runs inside a program (process). Multiple
threads share the same memory.
Multipro Running multiple processes simultaneously. Each process has its own
cessing memory space.
Multithre Running multiple threads within a single process, sharing the same
ading memory but executing tasks independently.
1. What is Multitasking?
Multitasking is the ability of an operating system to run multiple tasks (processes or
threads) simultaneously to improve efficiency.
Types of Multitasking
Type Description
Process-Based Running multiple processes simultaneously. Each process has
Multitasking separate memory.
Thread-Based Running multiple threads within a single process. Threads
Multitasking share the same memory space.
Process-Based Multitasking
Thread-Based Multitasking
2. What is a Thread?
A thread is the smallest unit of execution in a program. Multiple threads can run in
parallel to perform tasks more efficiently.
Types of Threads
Type Description
User Created and controlled by the programmer.
Thread
Daemon Background threads (e.g., Garbage Collector). Automatically stops when
Thread all user threads finish execution.
Main Thread in Java
Every Java program has a main thread, which runs the main() method.
Example:
class MainThreadExample {
public static void main(String[] args) {
Thread t = Thread.currentThread(); // Getting main thread
System.out.println("Current Thread: " + t.getName());
}
}
Output:
4. Thread Lifecycle
State Description
New Thread is created but not started.
Runnable Thread is ready and waiting for CPU time.
Running Thread is executing.
Blocked Waiting for a resource to be free.
Waiting Waiting indefinitely for another thread's
signal.
Timed Waiting Waiting for a specific time (e.g., sleep()).
Terminated Thread has finished execution.
5. Thread Synchronization
When multiple threads access shared resources, race conditions may occur. Java
provides synchronized to prevent this.
class Counter {
private int count = 0;
6. Deadlock in Java
A deadlock occurs when two threads wait for each other's resources, causing a cycle.
Example of Deadlock
class Deadlock {
static final Object lock1 = new Object();
static final Object lock2 = new Object();
t1.start();
t2.start();
}
}
7. Inter-Thread Communication
Java provides wait(), notify(), and notifyAll() to coordinate threads.
class SharedResource {
private int value;
private boolean available = false;
Producer(SharedResource res) {
this.resource = res;
}
Consumer(SharedResource res) {
this.resource = res;
}
8. Summary Table
Concept Description
Multitasking Running multiple tasks simultaneously.
Process-Based Multiple independent processes executing.
Multitasking
Thread-Based Multiple threads running within the same process.
Multitasking
Main Thread Default thread that runs main().
Creating Threads Extend Thread class or implement Runnable.
Thread Lifecycle New → Runnable → Running → Waiting/Blocked →
Terminated.
Synchronization Prevents race conditions using synchronized.
Deadlock Two or more threads waiting indefinitely for each other’s
resources.
Inter-Thread Uses wait(), notify(), and notifyAll().
Communication
Summary
• Multithreading improves performance but must be managed carefully.
• Synchronization prevents data corruption, but excessive locking can reduce
performance.
• Deadlocks should be avoided using proper resource management.
An Example:
class NumberPrinter extends Thread {
private int start, end;
this.start = start;
this.end = end;
try {
} catch (InterruptedException e) {
System.out.println(e.getMessage());
t1.start();
t2.start();
}
What is GUI?
A Graphical User Interface (GUI) allows users to interact with programs using
graphical components such as buttons, text fields, menus, and dialogs instead of
command-line interfaces.
Why Swing?
Framework Description
AWT (Abstract Window Uses native OS components (Heavyweight, limited
Toolkit) features).
Swing Fully Java-based, lightweight, flexible, and rich in UI
components.
Advantages of Swing:
Cross-platform compatibility
Lightweight components
Containers hold other components and define the structure of the UI.
Container Description
JFrame The main application window.
JPanel A sub-container that groups components.
JDialog A popup dialog box.
JApplet A container for embedding applets in web
pages.
JWindow A borderless, undecorated window.
import javax.swing.*;
Component Description
JLabel Displays static text or images.
JTextField Single-line text input.
JButton Clickable button.
JTextArea Multi-line text input.
JCheckBox Checkbox (on/off selection).
JRadioButton Used in groups for mutually exclusive
choices.
JComboBox Dropdown selection menu.
JList List of selectable items.
JMenuBar, JMenu, JMenuItem Menus and menu items.
Example: Adding Components to JFrame
import javax.swing.*;
panel.add(label);
panel.add(textField);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
}
3. Layout Managers
Swing provides Layout Managers to arrange components in a container.
Here’s a detailed explanation of each Layout Manager in Swing, along with examples:
1. FlowLayout
Description:
Example:
import javax.swing.*;
import java.awt.*;
frame.add(panel);
frame.setVisible(true);
}
}
2. BorderLayout
Description:
Example:
import javax.swing.*;
import java.awt.*;
frame.setVisible(true);
}
}
3. GridLayout
Description:
Example:
import javax.swing.*;
import java.awt.*;
frame.add(new JButton("1"));
frame.add(new JButton("2"));
frame.add(new JButton("3"));
frame.add(new JButton("4"));
frame.add(new JButton("5"));
frame.add(new JButton("6"));
frame.setVisible(true);
}
}
4. BoxLayout
Description:
import javax.swing.*;
import java.awt.*;
frame.add(panel);
frame.setVisible(true);
}
}
5. CardLayout
Description:
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
cardPanel.add(panel1, "Card1");
cardPanel.add(panel2, "Card2");
frame.add(cardPanel, BorderLayout.CENTER);
frame.add(nextButton, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
Summary
Layout Description
Manager
FlowLayout Arranges components in a row, wraps if space runs out.
BorderLayou Divides the container into 5 regions (NORTH, SOUTH, EAST, WEST,
t CENTER).
GridLayout Arranges components in a grid of equal-sized cells.
BoxLayout Arranges components in a single row or column.
CardLayout Allows flipping between different panels (useful for wizards).
4. Event Handling in Swing
Swing uses Event Listeners to handle user actions.
Listener Description
Interface
ActionListener Handles button clicks.
MouseListener Detects mouse clicks and movements.
KeyListener Captures keyboard input.
WindowListener Handles window events (open, close, minimize,
etc.).
import javax.swing.*;
import java.awt.event.*;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button Clicked!");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
5. Dialogs in Swing
Swing provides JOptionPane and JDialog for pop-up messages.
panel.add(nameLabel);
panel.add(nameField);
panel.add(ageLabel);
panel.add(ageField);
panel.add(genderLabel);
panel.add(genderBox);
panel.add(submitButton);
frame.add(panel);
frame.setVisible(true);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String age = ageField.getText();
String gender = (String) genderBox.getSelectedItem();
JOptionPane.showMessageDialog(frame, "Student Info:\nName: " + name +
"\nAge: " + age + "\nGender: " + gender);
}
});
}
}
Conclusion
Method Description
drawLine(x1, y1, x2, y2) Draws a straight line from (x1, y1) to
(x2, y2).
drawRect(x, y, width, height) Draws a rectangle outline.
fillRect(x, y, width, height) Draws a filled rectangle.
drawOval(x, y, width, height) Draws an oval inside the given
rectangle.
fillOval(x, y, width, height) Draws a filled oval.
drawArc(x, y, width, height, startAngle, Draws an arc within an oval.
arcAngle)
fillArc(x, y, width, height, startAngle, arcAngle) Draws a filled arc.
drawPolygon(int[] xPoints, int[] yPoints, int n) Draws a polygon using an array of x
and y points.
fillPolygon(int[] xPoints, int[] yPoints, int n) Draws a filled polygon.
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawLine(20, 50, 200, 50);
g.drawRect(50, 80, 150, 100);
g.fillRect(220, 80, 150, 100);
g.drawOval(50, 200, 150, 100);
g.fillOval(220, 200, 150, 100);
g.drawArc(50, 320, 150, 100, 0, 180);
g.fillArc(220, 320, 150, 100, 0, 180);
import javax.swing.*;
import java.awt.*;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.setColor(Color.BLUE);
g.drawString("Hello, Java Graphics!", 50, 50);
}
import javax.swing.*;
import java.awt.*;
public ImageGraphics() {
image = new ImageIcon("image.jpg").getImage();
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 50, 50, this);
}
public static void main(String[] args) {
new ImageGraphics();
}
}
Example:
g.setColor(Color.GREEN);
g.fillRect(50, 50, 100, 50);
Summary
• Graphics in Java allow custom drawing of shapes, text, and images.
• Graphics is used inside paintComponent(Graphics g).
• Swing components (JPanel, JFrame) provide the drawing surface.