Object Oriented Programming Through Java (R22) Unit - III
UNIT - III
Files
Introduction to I/O Streams in Java
I/O (Input/Output) in Java refers to the process of reading from and writing to different sources like
files, keyboard, network, or memory. Java provides a rich set of classes in the java.io package to
handle I/O operations.
Understanding Streams
A stream is a continuous flow of data. Java handles input and output operations through streams.
Types of Streams:
1. Input Stream – Used to read data from a source.
2. Output Stream – Used to write data to a destination.
Java categorizes streams into:
Byte Streams (for binary data like images, audio, video)
Character Streams (for text-based data)
Byte Streams
Byte streams are used to handle raw binary data. They operate on bytes (8-bit data).
Key Classes:
InputStream (Abstract Class) - InputStream is an abstract class in Java that represents
the base class for all input byte streams. It provides methods for reading bytes from a data
source (e.g., file, keyboard, network).
FileInputStream - FileInputStream is a subclass of InputStream used to read bytes
from a file. It is useful for reading binary data (e.g., images, audio, video).
BufferedInputStream - BufferedInputStream is a subclass of InputStream that
improves efficiency by buffering data before reading it. It reduces the number of
disk reads, making file reading faster.
DataInputStream - DataInputStream is a subclass of InputStream that allows reading
primitive data types (int, float, double, boolean) from an input stream.
OutputStream (Abstract Class) - OutputStream is an abstract class in Java that represents
the base class for all output byte streams. It provides methods to write bytes to an output
destination (e.g., file, network).
B ESWAR BABU DEPT OF IT 1
Object Oriented Programming Through Java (R22) Unit - III
FileOutputStream - FileOutputStream is a subclass of OutputStream used to write
raw binary data into a file.
BufferedOutputStream - BufferedOutputStream is a subclass of OutputStream that
buffers data before writing it to the output stream. This improves performance by
reducing the number of direct writes.
DataOutputStream - DataOutputStream is a subclass of OutputStream that allows
writing primitive data types (int, float, double, boolean) in a binary format.
Example: Reading a File using Byte Stream
import java.io.FileInputStream;
import java.io.IOException;
public class ByteStreamExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("input.txt");
int data;
while ((data = fis.read()) != -1) { // Read one byte at a time
System.out.print((char) data); // Convert byte to character
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note:
The string is converted into a byte array using getBytes().
Each byte is written into the file.
Example: Writing to a File using Byte Stream
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamWrite {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("output.txt");
String text = "Hello, Byte Stream!";
fos.write(text.getBytes()); // Convert String to byte array
fos.close();
System.out.println("Data written successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note:
The string is converted into a byte array using getBytes().
Each byte is written into the file.
B ESWAR BABU DEPT OF IT 2
Object Oriented Programming Through Java (R22) Unit - III
Character Streams
Character streams are used to handle text-based data. They operate on 16-bit Unicode characters.
Key Classes:
Reader (Abstract Class)
FileReader
BufferedReader
Writer (Abstract Class)
FileWriter
BufferedWriter
Example: Reading a File using Character Stream
import java.io.FileReader;
import java.io.IOException;
public class CharacterStreamExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("input.txt");
int data;
while ((data = fr.read()) != -1) { // Read character by character
System.out.print((char) data);
}
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note:
Uses FileReader to read characters from a file.
Reads character by character instead of byte by byte.
Example: Writing to a File using Character Stream
import java.io.FileWriter;
import java.io.IOException;
public class CharacterStreamWrite {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("output.txt");
fw.write("Hello, Character Stream!");
fw.close();
System.out.println("Data written successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note:
Writes characters directly to the file instead of converting them into bytes.
B ESWAR BABU DEPT OF IT 3
Object Oriented Programming Through Java (R22) Unit - III
File I/O Operations in Java
Java provides the File class in java.io package to work with files and directories.
Example: Creating a File
import java.io.File;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
try {
File file = new File("newfile.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: Uses createNewFile() to check if the file exists, and if not, creates a new file.
Example: Reading a File using BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = br.readLine()) != null) { // Read line by line
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: Uses BufferedReader for efficient reading of text files line by line.
Example: Writing to a File using BufferedWriter
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample {
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new
FileWriter("output.txt"));
bw.write("Hello, BufferedWriter!");
bw.newLine(); // Write a new line
bw.write("Java File Handling Example.");
bw.close();
System.out.println("Data written successfully.");
} catch (IOException e) {
B ESWAR BABU DEPT OF IT 4
Object Oriented Programming Through Java (R22) Unit - III
e.printStackTrace();
}
}
}
Note:
Uses BufferedWriter to write text data efficiently.
newLine() is used to insert a line break.
Byte vs. Character Streams
Byte Streams Character Streams
Feature
(InputStream/OutputStream) (Reader/Writer)
Data Type Binary (bytes) Text (characters)
Classes FileInputStream, FileOutputStream FileReader, FileWriter
Use Case Images, videos, PDF files Text files, XML, JSON
Performance Faster for binary files Better for text processing
B ESWAR BABU DEPT OF IT 5
Object Oriented Programming Through Java (R22) Unit - III
Multithreading vs. Multitasking
Both multithreading and multitasking involve executing multiple operations concurrently, but
they differ in scope and implementation.
Feature Multithreading Multitasking
Running multiple threads within a Running multiple processes
Definition
single process. simultaneously.
Works within a single Manages multiple
Scope
application/process. applications/processes.
Resource Threads share the same memory Each process has its own memory
Sharing space within a process. space.
Easier as threads share memory and More complex as processes use
Communication
resources. Inter-Process Communication (IPC).
All threads belong to the same
Execution Each process runs independently
process and share code, data, and OS
Context with its own memory and resources.
resources.
Lower overhead as threads share Higher overhead due to separate
Overhead
resources. memory allocation for each process.
Running multiple applications like a
A web browser running multiple tabs
Example browser, media player, and word
as separate threads.
processor simultaneously.
More efficient for lightweight tasks Better for running independent
Efficiency
like concurrent I/O operations. programs without interference.
Handled by the process itself using
OS Support Managed by the OS scheduler.
threading libraries.
Multithreading is useful for concurrent tasks within the same application (e.g., handling multiple
user requests in a web server).
Multitasking is broader and enables running multiple independent applications at the same time.
Multithreading
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU.
Each part of such program is called a thread. So, threads are light-weight processes within a
process.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
There can be multiple processes inside the OS and one process can have multiple threads.
B ESWAR BABU DEPT OF IT 6
Object Oriented Programming Through Java (R22) Unit - III
What is a Thread?
• A thread is a lightweight process that allows parallel execution.
• In Java, threads can be created using Thread class or Runnable interface.
• The JVM manages the execution of threads.
Thread Life Cycle in Java
A thread in Java goes through several stages from its creation to termination. The Thread Life
Cycle consists of the following states:
1. New (Created)
2. Runnable
3. Blocked (Optional)
4. Waiting (Optional)
5. Timed Waiting (Optional)
6. Terminated (Dead)
1. New (Created) State
When a thread object is created using the Thread class but has not started yet.
The thread remains in this state until the start() method is called.
B ESWAR BABU DEPT OF IT 7
Object Oriented Programming Through Java (R22) Unit - III
Example:
Thread t = new Thread(); // Thread created but not started
2. Runnable State
When the start() method is called, the thread moves to the Runnable state.
The thread is ready to run but may not execute immediately (depends on the CPU
scheduler).
Example:
t.start(); // Thread is now runnable
It may still be waiting for CPU time if other threads have higher priority.
3. Blocked State (Optional)
A thread enters this state when it tries to access a synchronized resource that is locked by
another thread.
It moves back to the Runnable state once the resource is available.
Example:
synchronized(obj) {
// Thread enters the blocked state if another thread is already
using this block
}
4. Waiting State (Optional)
A thread enters this state when it waits indefinitely for another thread to notify it.
This happens when using wait(), join(), or similar methods.
The thread moves back to Runnable when it receives a notification.
Example:
synchronized(obj) {
obj.wait(); // Thread waits indefinitely until notified
}
5. Timed Waiting State (Optional)
A thread enters this state when it waits for a specific time using methods like sleep(),
wait(timeout), or join(timeout).
It automatically moves back to Runnable after the timeout expires.
Example:
Thread.sleep(5000); // Thread waits for 5 seconds
B ESWAR BABU DEPT OF IT 8
Object Oriented Programming Through Java (R22) Unit - III
6. Terminated (Dead) State
A thread reaches this state after completing execution or when it is forcefully stopped
using stop() (deprecated).
Once a thread is terminated, it cannot be restarted.
Example:
public void run() {
System.out.println("Thread is running...");
}
// After run() method finishes, the thread enters the Terminated state.
State Trigger
New Thread is created but not started.
Runnable start() is called. Thread is waiting for CPU.
Blocked Waiting for a synchronized resource.
Waiting Waiting indefinitely for another thread (e.g., wait()).
Timed Waiting Waiting for a fixed time (sleep(), wait(time), join(time)).
Terminated Thread execution is complete or forcefully stopped.
Example:
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(500); // Sleep for 500ms
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread(); // Thread 1
MyThread t2 = new MyThread(); // Thread 2
t1.start(); // Start first thread
t2.start(); // Start second thread
System.out.println("Main thread running...");
}
}
B ESWAR BABU DEPT OF IT 9
Object Oriented Programming Through Java (R22) Unit - III
Output (Example Output, Order May Vary)
Main thread running...
Thread-0 - 1
Thread-1 - 1
Thread-0 - 2
Thread-1 - 2
Thread-0 - 3
Thread-1 - 3
Thread-0 - 4
Thread-1 - 4
Thread-0 - 5
Thread-1 – 5
Note: The output order may differ each time because thread scheduling is handled by the JVM
and OS.
Why is "Main thread running..." Printed First?
In the given multithreading example, the output "Main thread running..." is printed first
because of how Java schedules and executes threads.
Step-by-Step Execution
1. The main thread starts execution.
2. The start() method is called on t1 and t2.
o Important: Calling start() does not immediately execute run(). It only schedules the
thread for execution.
3. The statement System.out.println("Main thread running..."); is executed immediately by the
main thread.
4. The JVM then assigns CPU time to t1 and t2 whenever available, meaning their execution
starts after the main thread prints its message.
Threads in java
Thread can be created by using two mechanisms:
1. Extending the Thread class
2. Implementing the Runnable Interface
1. Creating a Thread by extending the Thread class
Create a class that extends java.lang.Thread class.
This class overrides the run() method available in the Thread class. A thread begins its life
inside run() method.
Create an object of our new class and call start() method to start the execution of a thread.
Start() invokes the run() method on the Thread object.
B ESWAR BABU DEPT OF IT 10
Object Oriented Programming Through Java (R22) Unit - III
Example:
import java.lang.Thread;
class Thread1 extends Thread {
public void run() {
System.out.println("Thread1 is running...");
System.out.println("Current running thread name is " +
Thread.currentThread().getName());
System.out.println("Current running thread id is " +
Thread.currentThread().getId());
}
}
public class MultiThread1 {
public static void main(String args[]) {
Thread1 t1 = new Thread1();
t1.start();
Thread1 t2 = new Thread1();
t2.setName("Java Thread");
t2.start();
}
}
2. Creating a Thread by implementing Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run()
method.
Create an instance of the Thread class and pass your Runnable object to its constructor as a
parameter.
o A Thread object is created that can run your Runnable class.
Call the Thread object’s start() method.
Example:
import java.lang.Thread;
class Thread2 implements Runnable {
public void run() {
System.out.println("Thread is Running...");
System.out.println("Current running thread name is " +
Thread.currentThread().getName());
System.out.println("Current running thread id is " + +
Thread.currentThread().getId());
}
}
public class Multithread2 {
public static void main(String args[]) {
Thread t1=new Thread( new Thread2());
t1.start();
}
}
Thread Methods: getName(), setName(), and getId()
In Java, threads have names and unique IDs assigned to them. The Thread class provides methods
to retrieve and modify these attributes.
1. getName() Method
Returns the name of the thread.
Default thread names are "Thread-0", "Thread-1", etc., assigned by the JVM.
B ESWAR BABU DEPT OF IT 11
Object Oriented Programming Through Java (R22) Unit - III
2. setName(String name) Method
Used to rename a thread.
Helps in identifying specific threads in debugging.
3. getId() Method
Returns a unique identifier for the thread.
The ID is a long value assigned by the JVM when the thread is created.
4. Sleep() Method
The sleep() method in Java is used to pause the execution of a thread for a specified period.
It belongs to the Thread class and is commonly used for timing control in multi-threaded
applications.
Syntax:
sleep(long milliseconds)throws InterruptedException
milliseconds → Time in milliseconds for which the thread should sleep.
Example:
class AlphabetThread extends Thread {
public void run() {
for (char ch = 'A'; ch <= 'Z'; ch++) {
System.out.print(ch + " ");
try {
Thread.sleep(2000); // Sleep to simulate concurrency
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class NumberThread extends Thread {
public void run() {
for (int i = 1; i <= 26; i++) {
System.out.print(i + " ");
try {
Thread.sleep(200); // Sleep to simulate concurrency
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MultiThreadDemo {
public static void main(String[] args) {
AlphabetThread at = new AlphabetThread();
NumberThread nt = new NumberThread();
at.start(); // Start alphabet thread
nt.start(); // Start number thread
}
}
B ESWAR BABU DEPT OF IT 12
Object Oriented Programming Through Java (R22) Unit - III
Thread Priorities in Java
Java allows setting priorities for threads, which influence the order in which threads are scheduled
for execution. However, thread priority does not guarantee execution order, as it depends on the
OS thread scheduler.
1. Understanding Thread Priorities
Each thread has a priority, represented as an integer between 1 (MIN_PRIORITY) and 10
(MAX_PRIORITY).
Default Priorities
Thread.MIN_PRIORITY (1) → Lowest priority
Thread.NORM_PRIORITY (5) → Default priority
Thread.MAX_PRIORITY (10) → Highest priority
2. Setting and Getting Thread Priority
Methods
setPriority(int priority) → Sets the priority of a thread.
getPriority() → Returns the priority of a thread.
Example:
import java.lang.Thread;
class TestPriority1 extends Thread {
public void run(){
System.out.println("running thread name
is:"+Thread.currentThread().getName());
System.out.println("running thread priority
is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]) {
TestPriority1 t1=new TestPriority1();
TestPriority1 t2=new TestPriority1();
TestPriority1 t3=new TestPriority1();
//setting thread Priorities
t1.setPriority(8);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(2);
// t3.setPriority(15); //will throw IllegalArgumentException
//setting the names of threads
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
t1.start();
t2.start();
t3.start();
}
}
B ESWAR BABU DEPT OF IT 13
Object Oriented Programming Through Java (R22) Unit - III
Thread Synchronization in Java
Thread synchronization is a mechanism that ensures multiple threads do not interfere with each
other while accessing shared resources. It prevents race conditions and ensures data consistency.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
When we start two or more threads within a program, there may be a situation when multiple
threads try to access the same resource and finally they can produce unforeseen result due to
concurrency issues.
So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time. This is implemented using a concept
called monitors/Lock. Each object in Java is associated with a monitor, which a thread can
lock or unlock. Only one thread at a time may hold a lock on a monitor.
Types of thread Synchronization
1. Mutual Exclusive
– Synchronized method.
– Synchronized block.
– Static synchronization.
2. Inter-thread communication
Mutual Exclusive - It keep threads from interfering with one another while sharing data.
a) Synchronized Method
If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
A synchronized method ensures that only one thread can execute it at a time for the
same object
Example:
class Table{
synchronized void printTable(int n) {
for(int i=1;i<=5;i++){
System.out.println(n+"*"+i+"="+n*i);
try{
Thread.sleep(200);
}
catch(Exception e){
System.out.println(e);
}
}
B ESWAR BABU DEPT OF IT 14
Object Oriented Programming Through Java (R22) Unit - III
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t1) {
this.t=t1;
}
public void run() {
t.printTable(5);
}
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(10);
}
}
class TestSynchronization{
public static void main(String args[]) {
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Note: printTable() is a shared resource and synchronized method
b) Synchronized Block
Instead of locking an entire method, a synchronized block locks only a specific part of the code.
• Synchronized block is used to lock an object for any shared resource.
• Scope of synchronized block is smaller than the method.
• A Java synchronized block doesn't allow more than one JVM, to provide access control to a
shared resource.
• The system performance may degrade because of the slower working of synchronized
keyword.
• Java synchronized block is more efficient than Java synchronized method.
Syntax:
synchronized (object reference expression) {
//code block
}
Example:
class SharedResource {
void printNumbers(int n) {
synchronized (this) { // Synchronization block
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
B ESWAR BABU DEPT OF IT 15
Object Oriented Programming Through Java (R22) Unit - III
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
c) Static Synchronization
When multiple threads access static methods, we use static synchronization.
• If you make any static method as synchronized, the lock will be on the class not on object.
Example:
class SharedResource {
synchronized static void printNumbers(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
class MyThread extends Thread {
public void run() {
SharedResource.printNumbers(2);
}
}
public class StaticSyncExample {
public static void main(String args[]) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
Problem without static synchronization
Suppose there are two objects of a shared class (e.g. Table) named object1 and object2. In
case of synchronized method and synchronized block there cannot be interference between
B ESWAR BABU DEPT OF IT 16
Object Oriented Programming Through Java (R22) Unit - III
t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single
lock.
But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock
and t3 acquires another lock. We don't want interference between t1 and t3 or t2 and t4.
Static synchronization solves this problem.
Inter-Thread Communication in Java
Inter-thread communication allows threads to cooperate with each other using wait(), notify(), and
notifyAll() methods. This is essential when multiple threads need to share resources efficiently.
Methods for Inter-Thread Communication
wait(): It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify().
notify(): It wakes up one single thread called wait() on the same object. It should be noted
that calling notify() does not give up a lock on a resource.
notifyAll(): It wakes up all the threads called wait() on the same object.
Inter-thread communication in Java is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.
• The process of testing a condition repeatedly till it becomes true is known as polling.
• Polling is usually implemented with the help of loops to check whether a particular
condition is true or not. If it is true, a certain action is taken. This wastes many CPU cycles
and makes the implementation inefficient.
• To avoid polling, Java uses three methods, namely, wait(), notify(), and notifyAll(). All
these methods belong to object class as final so that all classes have them. They must be
used within a synchronized block only.
Example1: Producer-Consumer Problem Using wait() and notify()
class SharedResource {
private int data;
private boolean available = false;
synchronized void produce(int value) {
while (available) {
try {
wait(); // Wait if data is already produced
} catch (InterruptedException e) {
System.out.println(e);
}
}
data = value;
B ESWAR BABU DEPT OF IT 17
Object Oriented Programming Through Java (R22) Unit - III
System.out.println("Produced: " + data);
available = true;
notify(); // Notify consumer to consume
}
synchronized void consume() {
while (!available) {
try {
wait(); // Wait until data is produced
} catch (InterruptedException e) {
System.out.println(e);
}
}
System.out.println("Consumed: " + data);
available = false;
notify(); // Notify producer to produce more
}
}
class Producer extends Thread {
SharedResource resource;
Producer(SharedResource resource) {
this.resource = resource;
}
public void run() {
for (int i = 1; i <= 5; i++) {
resource.produce(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
class Consumer extends Thread {
SharedResource resource;
Consumer(SharedResource resource) {
this.resource = resource;
}
public void run() {
for (int i = 1; i <= 5; i++) {
resource.consume();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class InterThreadExample {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Producer producer = new Producer(resource);
Consumer consumer = new Consumer(resource);
producer.start();
consumer.start();
B ESWAR BABU DEPT OF IT 18
Object Oriented Programming Through Java (R22) Unit - III
}
}
Output:
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
Note:
The Producer thread produces an item and notifies the Consumer.
The Consumer thread waits until an item is produced and then consumes it.
This prevents race conditions and busy-waiting.
Example2:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the
object.
B ESWAR BABU DEPT OF IT 19
Object Oriented Programming Through Java (R22) Unit - III
java.util Package
The java.util package in Java contains utility classes for data structures, date/time manipulation,
random number generation, and string processing.
Collection Framework -Key components include:
Collection interfaces – List, Set, Queue, Map
Collection classes: LinkedList, HashMap, TreeSet
Utility Classes – StringTokenizer, Date, Random, Scanner.
Interface Description Example Implementations
Ordered collection, allows
List ArrayList, LinkedList, Vector
duplicates
Unordered collection,
Set HashSet, TreeSet, LinkedHashSet
unique elements
Key-value pairs, unique HashMap, TreeMap,
Map
keys LinkedHashMap
B ESWAR BABU DEPT OF IT 20
Object Oriented Programming Through Java (R22) Unit - III
Collection Interfaces and Implementations
1. List Interface
Maintains insertion order
Allows duplicate elements
Implemented by: ArrayList, LinkedList, Vector
a) ArrayList
ArrayList is a resizable array implementation of the List interface in Java. Unlike arrays,
ArrayList can dynamically grow and shrink in size. It is part of the java.util package.
Features of ArrayList:
Dynamic Size – Unlike arrays, ArrayList automatically resizes when elements are added or
removed.
Indexed Access – Elements can be accessed using an index, like arrays.
Allows Duplicates – ArrayList can store duplicate values.
Maintains Insertion Order – Elements remain in the order they were added.
Non-Synchronized – Not thread-safe; requires manual synchronization for multi-threaded
applications.
Syntax :
ArrayList<DataType> VariableName = new ArrayList<DataTYpe>()
Common ArrayList Methods:
Method Description
get(object o) It prints the value at a specific index.
It updates the value. In that, we need to provide an
set(index, object o)
index.
add(index, object o) It adds an element at a specific index.
remove(Object o) It removes elements at specific indexes.
sort() It sorts an array depending upon the data type.
addAll(Collection c) It is used to add another collection.
removeAll(Collection c) It is used to remove another collection.
Example:
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListMethodsDemo {
public static void main(String[] args) {
// 1. Create an ArrayList
ArrayList<String> list = new ArrayList<>();
// 2. Adding elements
list.add("Apple");
B ESWAR BABU DEPT OF IT 21
Object Oriented Programming Through Java (R22) Unit - III
list.add("Banana");
list.add("Cherry");
list.add("Mango");
System.out.println("Initial ArrayList: " + list);
// 3. Adding an element at a specific index
list.add(2, "Orange");
System.out.println("After adding 'Orange' at index 2: " + list);
// 4. Accessing elements using get()
System.out.println("Element at index 1: " + list.get(1));
// 5. Updating an element using set()
list.set(3, "Grapes");
System.out.println("After updating index 3 with 'Grapes': " + list);
// 6. Removing elements
list.remove("Banana"); // Remove by value
System.out.println("After removing 'Banana': " + list);
list.remove(2); // Remove by index
System.out.println("After removing element at index 2: " + list);
// 7. Checking if an element exists
System.out.println("Contains 'Mango'? " + list.contains("Mango"));
// 8. Finding the size of ArrayList
System.out.println("Size of ArrayList: " + list.size());
// 9. Sorting the ArrayList
Collections.sort(list);
System.out.println("After Sorting: " + list);
// 10. Iterating over ArrayList using for-each loop
System.out.println("Iterating over elements:");
for (String fruit : list) {
System.out.println(fruit);
}
// 11. Converting ArrayList to Array
String[] array = list.toArray(new String[0]);
System.out.println("Converted Array:");
for (String item : array) {
System.out.println(item);
}
// 12. Clearing the ArrayList
list.clear();
System.out.println("After clearing ArrayList: " + list);
// 13. Checking if the ArrayList is empty
System.out.println("Is the ArrayList empty? " + list.isEmpty());
}
}
b) LinkedList
LinkedList is a doubly linked list implementation of the List interface in Java. Unlike ArrayList,
which is backed by a dynamic array, LinkedList uses nodes where each node contains:
Data (value stored)
Reference to the next node (next pointer)
Reference to the previous node (previous pointer)
It is part of the java.util package.
B ESWAR BABU DEPT OF IT 22
Object Oriented Programming Through Java (R22) Unit - III
Features of LinkedList:
Doubly Linked List – Each node has pointers to the next and previous nodes.
Efficient Insertions & Deletions – Insertion and deletion are faster than ArrayList,
especially in the middle of the list (O(1)).
Slower Access Time – Random access takes O(n) time, compared to O(1) in ArrayList.
Allows Duplicates & Null Values – Can store duplicate elements and null values.
Implements List, Queue, and Deque – Can be used as a List, Queue, or Stack.
Syntax:
LinkedList<DataType> VariableName = new LinkedList < DataType>();
Common LinkedList Methods:
Method Description
add(E e) Adds an element at the end of the list.
add(int index, E e) Inserts an element at a specified index.
get(int index) Retrieves an element from a given index.
set(int index, E e) Updates an element at a specific index.
remove(int index) Removes an element at the specified index.
remove(E e) Removes the first occurrence of an element.
size() Returns the number of elements in the list.
contains(E e) Checks if an element exists in the list.
clear() Removes all elements from the list.
addFirst(E e) Adds an element at the beginning of the list.
addLast(E e) Adds an element at the end of the list.
removeFirst() Removes the first element from the list.
Example:
import java.util.LinkedList;
import java.util.Collections;
public class LinkedListMethods {
public static void main(String[] args) {
// 1. Create a LinkedList
LinkedList<String> list = new LinkedList<>();
// 2. Adding elements
list.add("Apple");
list.add("Banana");
list.add("Cherry");
list.add(1, "Orange"); // Add at a specific index
list.addFirst("Mango"); // Add at the beginning
list.addLast("Grapes"); // Add at the end
System.out.println("Initial LinkedList: " + list);
// 3. Accessing elements
System.out.println("First Element: " + list.getFirst());
System.out.println("Last Element: " + list.getLast());
B ESWAR BABU DEPT OF IT 23
Object Oriented Programming Through Java (R22) Unit - III
System.out.println("Element at index 2: " + list.get(2));
// 4. Updating elements
list.set(2, "Pineapple");
System.out.println("After updating index 2: " + list);
// 5. Removing elements
list.remove("Banana"); // Remove by value
list.remove(2); // Remove by index
list.removeFirst(); // Remove first element
list.removeLast(); // Remove last element
System.out.println("After Removals: " + list);
// 6. Checking for an element
System.out.println("Contains 'Mango'? " + list.contains("Mango"));
// 7. Getting the size
System.out.println("Size of LinkedList: " + list.size());
// 8. Sorting the LinkedList
Collections.sort(list);
System.out.println("Sorted LinkedList: " + list);
// 9. Iterating over elements
System.out.println("Iterating using for-each loop:");
for (String fruit : list) {
System.out.println(fruit);
}
// 10. Converting to Array
String[] array = list.toArray(new String[0]);
System.out.println("Converted Array:");
for (String item : array) {
System.out.println(item);
}
// 11. Clearing the LinkedList
list.clear();
System.out.println("After clearing LinkedList: " + list);
// 12. Checking if it's empty
System.out.println("Is the LinkedList empty? " + list.isEmpty());
}
}
c) Vector
Vector is a resizable-array implementation of the List interface, similar to ArrayList. However, it
is synchronized, making it thread-safe for concurrent access.
Features of Vector:
Implements List Interface – Works like an array but grows dynamically.
Thread-Safe (Synchronized) – Multiple threads can access it safely.
Allows Duplicates & Null Values – Just like ArrayList.
Slower than ArrayList – Because of synchronization overhead.
B ESWAR BABU DEPT OF IT 24
Object Oriented Programming Through Java (R22) Unit - III
Syntax:
Vector < DataType> VariableName = new Vector<DataType> ();
Common Vector Methods:
Method Description
add(E e) Adds an element at the end.
add(int index, E e) Inserts an element at a specified index.
get(int index) Retrieves an element at the given index.
set(int index, E e) Updates an element at the given index.
remove(int index) Removes an element at a specified index.
remove(E e) Removes the first occurrence of an element.
size() Returns the number of elements in the vector.
contains(E e) Checks if an element exists in the vector.
clear() Removes all elements.
firstElement() Retrieves the first element.
lastElement() Retrieves the last element.
capacity() Returns the current capacity of the vector.
isEmpty() Checks if the vector is empty.
Example:
public class VectorMethods import java.util.Vector;
import java.util.Collections;
public class VectorAllMethods {
public static void main(String[] args) {
// 1. Creating a Vector
Vector<String> vector = new Vector<>();
// 2. Adding elements
vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");
vector.add(1, "Orange"); // Insert at index 1
vector.addElement("Mango"); // Alternative way to add
vector.add("Grapes");
System.out.println("Initial Vector: " + vector);
// 3. Accessing elements
System.out.println("First Element: " + vector.firstElement());
System.out.println("Last Element: " + vector.lastElement());
System.out.println("Element at index 2: " + vector.get(2));
// 4. Updating elements
vector.set(2, "Pineapple");
System.out.println("After updating index 2: " + vector);
// 5. Removing elements
vector.remove("Banana"); // Remove by value
vector.remove(2); // Remove by index
vector.removeElement("Mango"); // Remove by value (alternative)
vector.removeElementAt(1); // Remove at index
vector.removeAllElements(); // Clear all elements
B ESWAR BABU DEPT OF IT 25
Object Oriented Programming Through Java (R22) Unit - III
System.out.println("After Removals: " + vector);
// 6. Checking if empty
System.out.println("Is Vector empty? " + vector.isEmpty());
// 7. Re-adding elements for further operations
vector.add("Strawberry");
vector.add("Blueberry");
vector.add("Raspberry");
// 8. Checking size and capacity
System.out.println("Size: " + vector.size());
System.out.println("Capacity: " + vector.capacity());
// 9. Sorting the Vector
Collections.sort(vector);
System.out.println("Sorted Vector: " + vector);
// 10. Iterating using a for-each loop
System.out.println("Iterating over Vector:");
for (String fruit : vector) {
System.out.println(fruit);
}
// 11. Converting to
{
}
2. Queue – interface
The Queue interface is a part of the Java Collections Framework and is used to hold multiple
elements prior to processing. It follows the FIFO (First-In-First-Out) principle.
Note: import java.util.Queue;
Key Features
Elements are added at the rear (tail) and removed from the front (head).
Offers methods for insertion, deletion, and inspection.
Sub-interfaces:
o Deque (double-ended queue)
Commonly Used Implementing Classes:
Class Name Description
LinkedList Most commonly used class for Queue implementation.
Elements are ordered based on priority (natural order or
PriorityQueue
custom Comparator).
Resizable-array implementation of Deque, faster than Stack
ArrayDeque
and LinkedList.
B ESWAR BABU DEPT OF IT 26
Object Oriented Programming Through Java (R22) Unit - III
Common Methods in Queue Interface
Method Description
add(E e) Inserts the specified element. Throws exception if fails.
offer(E e) Inserts the specified element. Returns false if fails.
remove() Retrieves and removes the head. Throws exception if empty.
poll() Retrieves and removes the head. Returns null if empty.
element() Retrieves but does not remove the head. Throws exception if empty.
peek() Retrieves but does not remove the head. Returns null if empty.
Example:
import java.util.*;
public class QueueExample {
public static void main(String[] args) {
Queue<String> q = new LinkedList<>();
// Adding elements
q.add("Apple");
q.offer("Banana");
q.offer("Cherry");
System.out.println("Queue: " + q);
// Retrieving head
System.out.println("Head using peek(): " + q.peek());
// Removing elements
System.out.println("Removed using remove(): " + q.remove());
System.out.println("Removed using poll(): " + q.poll());
System.out.println("Queue after removals: " + q);
}
}
Example:
import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
Queue<Integer> pq = new PriorityQueue<>();
pq.offer(30);
pq.offer(10);
pq.offer(20);
System.out.println("Priority Queue (natural order): " + pq);
while (!pq.isEmpty()) {
System.out.println("Polling: " + pq.poll());
}
}
}
B ESWAR BABU DEPT OF IT 27
Object Oriented Programming Through Java (R22) Unit - III
3. Set interface
a) HashSet
Backed by: Hash table
Order: No guaranteed order
Duplicates: Not allowed
Null: Allowed (only one null element)
b) LinkedHashSet
Backed by: Hash table + linked list
Order: Maintains insertion order
Duplicates: Not allowed
Null: Allowed
c) Sub Interfaces of Set (SortedSet)
SortedSet interface- Maintains elements in ascending order. Implemented by TreeSet class.
TreeSet
Backed by: Red-Black tree
Order: Sorted (natural or custom)
Duplicates: Not allowed
Null: ❌ Not allowed (throws NullPointerException)
Implements: SortedSet
Common Methods of Set interface
Method Signature Description
Adds the element to the set if it's not already
boolean add(E e)
present. Returns true if added.
boolean addAll(Collection<? extends E> Adds all elements from another collection to
c) this set, ignoring duplicates.
void clear() Removes all elements from the set.
Checks if the specified element is present in the
boolean contains(Object o)
set.
Checks if the set contains all elements of the
boolean containsAll(Collection<?> c)
specified collection.
Compares the specified object with this set for
boolean equals(Object o)
equality.
int hashCode() Returns the hash code value for the set.
boolean isEmpty() Checks if the set is empty.
Iterator<E> iterator() Returns an iterator over the elements in the set.
Removes the specified element from the set if
boolean remove(Object o)
present.
B ESWAR BABU DEPT OF IT 28
Object Oriented Programming Through Java (R22) Unit - III
Removes all elements from the set that are
boolean removeAll(Collection<?> c)
contained in the specified collection.
Retains only the elements in the set that are also
boolean retainAll(Collection<?> c)
in the specified collection.
int size() Returns the number of elements in the set.
Returns an array containing all the elements in
Object[] toArray()
the set.
Notes:
All these methods are available in all implementations of Set (like HashSet, TreeSet,
LinkedHashSet).
Some methods like retainAll() and removeAll() are useful when performing set operations
like intersection or difference.
The iterator() method is commonly used for looping through elements.
Feature HashSet LinkedHashSet TreeSet
Maintains Order? ❌ No ✅ Yes (Insertion) ✅ Yes (Sorted)
Allows Null? ✅ Yes (1) ✅ Yes (1) ❌ No
Duplicate
❌ No ❌ No ❌ No
Allowed?
Example:
import java.util.*;
public class SetMethodsExample {
public static void main(String[] args) {
// ===== HashSet Example =====
System.out.println("🔹 HashSet Example");
Set<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Cherry");
hashSet.add("Apple"); // Duplicate
hashSet.add(null); // One null allowed
System.out.println("HashSet Elements: " + hashSet);
System.out.println("Contains 'Banana'? " + hashSet.contains("Banana"));
System.out.println("Size: " + hashSet.size());
hashSet.remove("Banana");
System.out.println("After removing 'Banana': " + hashSet);
System.out.println("Is Empty? " + hashSet.isEmpty());
Set hashSet2 = new HashSet();
hashSet2.add("Eswar");
hashSet2.add(20);
B ESWAR BABU DEPT OF IT 29
Object Oriented Programming Through Java (R22) Unit - III
hashSet2.add(true);
hashSet2.add(20.5);
System.out.println("Hashset2 contents are: "+ hashSet2);
// Iteration
System.out.print("Iterating HashSet: ");
for (String s : hashSet) {
System.out.print(s + " ");
}
System.out.println();
// Convert to array
Object[] hashArray = hashSet.toArray();
System.out.println("Array from HashSet: " + Arrays.toString(hashArray));
hashSet.clear();
System.out.println("After clear(): " + hashSet);
System.out.println("\n--------------------------\n");
// ===== LinkedHashSet Example =====
System.out.println("🔹 LinkedHashSet Example");
Set<String> linkedSet = new LinkedHashSet<>();
linkedSet.add("Dog");
linkedSet.add("Cat");
linkedSet.add("Elephant");
linkedSet.add("Dog"); // Duplicate
linkedSet.add(null); // One null allowed
System.out.println("LinkedHashSet Elements: " + linkedSet);
System.out.println("Size: " + linkedSet.size());
System.out.println("Contains 'Cat'? " + linkedSet.contains("Cat"));
linkedSet.remove("Cat");
System.out.println("After removing 'Cat': " + linkedSet);
Set<String> otherAnimals = new LinkedHashSet<>(Arrays.asList("Horse",
"Lion"));
linkedSet.addAll(otherAnimals); // Add all
System.out.println("After addAll(): " + linkedSet);
linkedSet.retainAll(Arrays.asList("Elephant", "Horse")); // Intersection
System.out.println("After retainAll(): " + linkedSet);
linkedSet.removeAll(Arrays.asList("Elephant")); // Difference
System.out.println("After removeAll(): " + linkedSet);
linkedSet.clear();
System.out.println("After clear(): " + linkedSet);
System.out.println("\n--------------------------\n");
// ===== TreeSet Example =====
System.out.println("🔹 TreeSet Example");
Set<String> treeSet = new TreeSet<>();
treeSet.add("Zebra");
treeSet.add("Lion");
treeSet.add("Tiger");
treeSet.add("Lion"); // Duplicate
// treeSet.add(null); // Uncommenting this will throw
NullPointerException
System.out.println("TreeSet (Sorted): " + treeSet);
System.out.println("Size: " + treeSet.size());
System.out.println("Contains 'Tiger'? " + treeSet.contains("Tiger"));
B ESWAR BABU DEPT OF IT 30
Object Oriented Programming Through Java (R22) Unit - III
treeSet.remove("Zebra");
System.out.println("After removing 'Zebra': " + treeSet);
System.out.print("Iterating TreeSet: ");
Iterator<String> itr = treeSet.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
// Convert to typed array
String[] treeArray = treeSet.toArray(new String[0]);
System.out.println("Array from TreeSet: " + Arrays.toString(treeArray));
treeSet.clear();
System.out.println("After clear(): " + treeSet);
}
}
Map Interface in Java
Package: java.util
Purpose: A Map is an object that maps keys to values. It cannot contain duplicate keys, and
each key maps to at most one value.
Unlike Set and List, Map is not a subtype of the Collection interface.
Characteristics of a Map:
No duplicate keys allowed.
One key → one value (but values can be duplicated).
Null keys and values:
o HashMap: allows one null key and multiple null values.
o TreeMap: does not allow null keys.
o LinkedHashMap: allows one null key and null values.
Common Implementations:
Order
Implementation Null Allowed Sorted Thread-safe
Maintained
HashMap ❌ No ✅ Yes ❌ No ❌ No
✅ Insertion
LinkedHashMap ✅ Yes ❌ No ❌ No
order
TreeMap ✅ Sorted by key ❌ No key ✅ Yes ❌ No
Hashtable ❌ No ❌ No ❌ No ✅ Yes
B ESWAR BABU DEPT OF IT 31
Object Oriented Programming Through Java (R22) Unit - III
Commonly Used Methods in Map<K, V>:
Method Signature Description
V put(K key, V value) Adds or updates a key-value pair.
V get(Object key) Returns the value for the specified key.
V remove(Object key) Removes the mapping for the key.
boolean containsKey(Object key) Checks if the key exists.
boolean containsValue(Object value) Checks if the value exists.
Set<K> keySet() Returns a Set view of keys.
Collection<V> values() Returns a Collection view of values.
Set<Map.Entry<K,V>> entrySet() Returns a set of key-value mappings.
void putAll(Map<? extends K, ? extends V> m) Copies all mappings from another map.
void clear() Removes all entries.
boolean isEmpty() Checks if the map is empty.
int size() Returns the number of entries.
Example Program Using HashMap, LinkedHashMap, and TreeMap:
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeMap;
public class MapExample {
public static void main(String[] args) {
// ===== HashMap =====
System.out.println("🔹 HashMap");
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(101, "Alice");
hashMap.put(102, "Bob");
hashMap.put(103, "Charlie");
hashMap.put(101, "David"); // Overwrites key 101
hashMap.put(null, "NullKey"); // One null key allowed
System.out.println("HashMap: " + hashMap);
System.out.println("Get key 102: " + hashMap.get(102));
System.out.println("Contains key 103? " + hashMap.containsKey(103));
System.out.println("Contains value 'Alice'? " +
hashMap.containsValue("Alice"));
System.out.println("Keys: " + hashMap.keySet());
System.out.println("Values: " + hashMap.values());
System.out.println("Entries: " + hashMap.entrySet());
// Iterating using for-each
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " +
entry.getValue());
}
System.out.println("\n-------------------------\n");
// ===== LinkedHashMap =====
System.out.println("🔹 LinkedHashMap");
Map<String, String> linkedMap = new LinkedHashMap<>();
B ESWAR BABU DEPT OF IT 32
Object Oriented Programming Through Java (R22) Unit - III
linkedMap.put("one", "First");
linkedMap.put("two", "Second");
linkedMap.put("three", "Third");
linkedMap.put(null, "NullKey"); // One null key allowed
System.out.println("LinkedHashMap (insertion order): " + linkedMap);
System.out.println("\n-------------------------\n");
// ===== TreeMap =====
System.out.println("🔹 TreeMap");
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Zebra", 5);
treeMap.put("Apple", 10);
treeMap.put("Lemon", 3);
// treeMap.put(null, 7); // ❌ Null key not allowed
System.out.println("TreeMap (sorted by key): " + treeMap);
System.out.println("First key: " + ((TreeMap<String, Integer>)
treeMap).firstKey());
System.out.println("Last key: " + ((TreeMap<String, Integer>)
treeMap).lastKey());
System.out.println("\n-------------------------\n");
// ===== Map Operations Summary =====
System.out.println("HashMap size: " + hashMap.size());
hashMap.remove(102);
System.out.println("After removing key 102: " + hashMap);
hashMap.clear();
System.out.println("After clear(): " + hashMap);
System.out.println("Is Empty? " + hashMap.isEmpty());
}
}
StringTokenizer in Java
StringTokenizer class in Java is used to break a string into tokens. A StringTokenizer object
internally maintains a current position within the string to be tokenized.
• The String Tokenizer class allows an application to break strings into tokens.
• To use String Tokenizer class we have to specify an input string and a string that contains
delimiters. Delimiters are the characters that separate tokens.
Constructors
• StringTokenizer(String str): default delimiters like newline, space, tab, carriage return,
and form feed.
• StringTokenizer(String str, String delim): delim is a set of delimiters that are used to
tokenize the given string.
• StringTokenizer(String str, String delim, boolean flag): The first two parameters have
the same meaning wherein . If the flag is false, delimiter characters serve to separate tokens
B ESWAR BABU DEPT OF IT 33
Object Oriented Programming Through Java (R22) Unit - III
Methods of StringTokenizer:
Method Action Performed
countTokens() Returns the total number of tokens present
Tests if tokens are present for the StringTokenizer’s
hasMoreToken()
string
nextElement() Returns an Object rather than String
hasMoreElements() Returns the same value as hasMoreToken
nextToken() Returns the next token from the given StringTokenizer.
Example:
import java.util.StringTokenizer;
public class StringTokenizerDemo {
public static void main(String[] args) {
System.out.println("1st type constructor");
StringTokenizer s1 = new StringTokenizer("A+B","+",true);
System.out.println("s1 tokens- ");
while(s1.hasMoreTokens()) {
System.out.println(s1.nextToken());
}
String s = "I am a B.Tech Student:VJIT";
System.out.println("2nd type constructor");
StringTokenizer s2 = new StringTokenizer(s,":");
System.out.println("s2 tokens- ");
while(s2.hasMoreTokens()) {
System.out.println(s2.nextToken());
}
System.out.println("3rd type constructor");
StringTokenizer s3 = new StringTokenizer(s,":", true);
System.out.println("s3 tokens- ");
while(s3.hasMoreTokens()) {
System.out.println(s3.nextToken());
}
}
}
Date class in Java
The class Date represents a specific instant in time, with millisecond precision.
Constructors:
• Date() : Creates date object representing current date and time.
• Date(long milliseconds) : Creates a date object for the given milliseconds since January 1,
1970, 00:00:00 GMT.
• Date(int year, int month, int date)
• Date(int year, int month, int date, int hrs, int min)
B ESWAR BABU DEPT OF IT 34
Object Oriented Programming Through Java (R22) Unit - III
• Date(int year, int month, int date, int hrs, int min, int sec)
• Date(String s)
Note: After Calendar class, the above last 4 constructors methods of java.util.Date class has been
deprecated.
Methods:
• boolean after(Date date) - Returns true if the invoking Date object contains a date that is
later than the one specified by date, otherwise, it returns false.
• boolean before(Date date) - Returns true if the invoking Date object contains a date that is
earlier than the one specified by date, otherwise, it returns false.
• boolean equals(Object date) - Returns true if the invoking Date object contains the same
time and date as the one specified by date, otherwise, it returns false.
Date Formatting Using SimpleDateFormat
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.
SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time
formatting.
Example:
import java.text.SimpleDateFormat;
import java.util.*;
public class DateDemo {
public static void main(String[] args) throws Exception {
// Current date
Date todayDate = new Date();
System.out.println("Current date is " + todayDate); // prints current
system date and time
// Parsing date from String using dd/MM/yyyy format
String lastDate = "31/04/2025";
System.out.println("last Date : " + lastDate);
SimpleDateFormat formatter1 = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = formatter1.parse(lastDate);
System.out.println("Date format1 = " + date1);
// Parsing date from String using dd-MMM-yyyy format
SimpleDateFormat formatter2 = new SimpleDateFormat("dd-MMM-yyyy");
lastDate = "30-May-2025";
Date date2 = formatter2.parse(lastDate);
System.out.println("Date format2 = " + date2);
}
}
B ESWAR BABU DEPT OF IT 35
Object Oriented Programming Through Java (R22) Unit - III
Scanner Class in Java
The Scanner class in Java is part of the java.util package. It is used to read input from various
input sources, such as:
Keyboard input (System.in)
Files
Strings
Note: Scanner is a class in java.util package
To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream.
Commonly used methods:
Method Description Example
nextInt() Reads an int value int x = sc.nextInt();
nextFloat() Reads a float value float f = sc.nextFloat();
nextDouble() Reads a double value double d = sc.nextDouble();
nextLine() Reads an entire line of text String s = sc.nextLine();
next() Reads the next word/token String s = sc.next();
nextBoolean() Reads a boolean value boolean b = sc.nextBoolean();
hasNext() Checks if there is another token if(sc.hasNext())
close() Closes the Scanner sc.close();
Example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Reading integer
System.out.print("Enter an integer: ");
int num = sc.nextInt();
// Reading float
System.out.print("Enter a float: ");
float f = sc.nextFloat();
// Reading a single word
System.out.print("Enter a word: ");
String word = sc.next();
// Consuming the newline before nextLine
sc.nextLine();
// Reading a full line
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();
System.out.println("\n--- Output ---");
B ESWAR BABU DEPT OF IT 36
Object Oriented Programming Through Java (R22) Unit - III
System.out.println("Integer: " + num);
System.out.println("Float: " + f);
System.out.println("Word: " + word);
System.out.println("Sentence: " + sentence);
sc.close(); // Always close the scanner
}
}
B ESWAR BABU DEPT OF IT 37