0% found this document useful (0 votes)
27 views81 pages

22CS305- AJP UNIT2

zCvSvSaa

Uploaded by

jothishwar007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views81 pages

22CS305- AJP UNIT2

zCvSvSaa

Uploaded by

jothishwar007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

1

2
Please read this disclaimer before proceeding:
This document is confidential and intended solely for the
educational purpose of RMK Group of Educational Institutions. If you have
received this document through email in error, please notify the system
manager. This document contains proprietary information and is intended
only for the respective group/learning community as intended. If you
are not the addressee you should not disseminate, distribute, or copy
through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from
your system. If you are not the intended recipient you are notified that
disclosing, copying, distributing, or taking any action in reliance on
the contents of this information is strictly prohibited.

3
22CS305
Advanced Java Programming
(Lab Integrated)
Department : CSE/IT/ADS/CSD/CSBS/ECE
Batch / Year : 2023 – 2027 / II
Created by : All Subject Handling Staff Members
Date : 24.06.2024

4
Table of Contents
Page
Sl.No. Topic
No.

1 Course Objectives 6

2 Syllabus 7

3 Pre-requisites 10

4 Course Outcomes 11

5 CO- PO Mapping 12

6 Lecture Plan 13

7 Activity-based learning 14

8 Lecture Notes 16

9 Assignments I - V 58 - 63

10 Part A Questions & Answers 64

11 Part B Questions 68

12 Supportive Online Certifications 70

13 Real-Time Applications 71

14 Content Beyond the Syllabus 72

15 Assessment Schedule 73

16 Prescribed Text Books & Reference Books 74

17 Mini Projects I - V 75-80

5
1. Course Objectives

OBJECTIVES: ( To be updated )

The Course will enable learners to:

❖ Gain a comprehensive understanding of the Java Collections Framework and its various

interfaces and implementations.

❖ Learn the details of Java I/O streams and utility classes for managing dates, numbers, and

currencies.

❖ Develop a thorough understanding of the Stream API introduced in Java 8 and its various

operations.

❖ Explore advanced object serialization and string tokenizing techniques, including pattern

matching with regular expressions.

❖ Understand advanced Stream API features and gain proficiency in using regular expressions

for text processing.

6
2. Syllabus
22CS305 ADVANCED JAVA PROGRAMMING (LAB INTEGRATED) L T P C
3 0 2 4
UNIT I COLLECTIONS FRAMEWORK AND UTILITY CLASSES 9+6
Introduction to Collections Framework - Collection Interface- Methods in Collection
Interface - - Iterable and Iterator Interfaces - List Interface- ArrayList - LinkedList - Set
Interface - HashSet- LinkedHashSet - TreeSet - Map Interface - HashMap -
LinkedHashMap- TreeMap - Queue Interface -PriorityQueue - Deque Interface - Utility
Classes.
List of Exercises
1. Write a program that measures the time taken for insertion, deletion, and search
operations on ArrayList, LinkedList, HashSet, and TreeSet for varying sizes of input data.
2. Implement a custom data structure that combines features of a list and a set.
3. Write a Java program to create a HashMap where the keys are strings, and the values
are integers Add five key-value pairs to the map. Print all the keys and values in the
map. Remove an entry by key. Update the value associated with a specific key. Check
if the map contains a specific key and a specific value.
UNIT II I/O OPERATIONS, SERIALIZATION, AND DATE HANDLING 9+6
Date – Calendar – Comparable interface – Observer Interface – Streams - Types of
Streams - The Byte-stream I/O hierarchy - Character Stream Hierarchy – Random
Access File class – the java.io. Console Class – Serialization – Dates - Numbers, and
Currency - Working with Dates - Numbers and Currencies.
List of Exercises
1. Create a class representing a complex object with nested data structures.
Serialize the object to a file, then deserialize it back and verify that the object
remains intact.
2. Write a program that formats dates and currencies according to different locales.
3. Implement a java program that allows users to open a text file, navigate through
it using random access, insert, delete, and modify text at specific positions within the
file.

7
UNIT III STREAM API AND FUNCTIONAL PROGRAMMING 9+6
PARADIGMS
Overview of Stream API - Importance of Stream API in Java 8 and Beyond – Functional
Programming Concepts - Creating Streams - Stream Interface Methods - Stream
Operations- Intermediate Filtering (filter)-Mapping (map, flatMap)-Sorting (sorted)-
Distinct (distinct)- Limit and Skip (limit, skip) - Terminal Operations -Collecting Results
(collect) - Reducing and Summarizing (reduce, summaryStatistics)-Iterating (forEach) -
Matching and Finding (anyMatch, allMatch, noneMatch, findFirst, findAny) -Counting
(count).
List of Exercises
1. Write a program that performs stream operations like filtering, mapping, and reducing.
2. Create an infinite stream generator that generates prime numbers. Implement
methods to check for primality and generate the next prime number.
3. Write a program that reads a text file containing sentences. Tokenize each sentence
into words, filter out stopwords, and print the remaining words.
UNIT IV ADVANCED STRING PROCESSING, OBJECT SERIALIZATION, 9+6
AND I/O TECHNIQUES
String Tokenizer – Parsing - Tokenizing and Formatting - Locating Data via Pattern
Matching, Tokenizing - Object Serialization - Serializable Interface - Writing and Reading
Serializable Objects -Transient Keyword- SerialVersionUID - Advanced I/O - Piped
Streams (PipedInputStream and PipedOutputStream) – SequenceInputStream –
PushbackInputStream and PushbackReader.
List of Exercises
1. Write a program that reads a text file and tokenizes it into sentences using the
StringTokenizer class.
2. Create a class hierarchy representing different types of objects (e.g., Person,
Employee). Serialize instances of these classes to a file using object serialization.
3. Implement a program that uses advanced I/O techniques like PipedInputStream,
PipedOutputStream, SequenceInputStream, and PushbackInputStream.

8
UNIT V ADVANCED STREAM FEATURES AND REGULAR EXPRESSIONS 9+6
Importance and Use Cases of Advanced Stream Features - Creating Custom Streams –
Stream Generators (Stream.generate, Stream.iterate) - Infinite Streams -Using
Spliterators – Advanced Stream Operations - FlatMapping - Chaining Stream Operations
- Stream Peeking (peek) - Advanced Filtering Techniques- Introduction to Regular
Expressions - Character Classes - Quantifiers - Pattern Matching - Groups and Capturing
- Regex in Java - java.util.regex Package Pattern Class - Matcher Class - String
Manipulation with Regex - Splitting Strings - Replacing Text (replaceAll, replaceFirst) -
Replacing with Backreferences.

List of Exercises
1. Implement custom stream generators using Stream.generate and Stream.iterate
methods.
2. Write a program that demonstrates advanced stream operations like flatMapping,
chaining stream operations, and peeking.
3. Develop a program that utilizes regular expressions to perform string manipulation

tasks such as splitting strings, replacing text, and extracting specific patterns.

TOTAL: 45+30=75 PERIODS

TEXT BOOKS:
1.Cay S. Horstmann, "Core Java Volume I--Fundamentals," 12th Edition, 2019.
2.Joshua Bloch, "Effective Java," 3rd Edition, 2018.
3.Raoul-Gabriel Urma, "Java 8 in Action: Lambdas, Streams, and Functional-Style
Programming," 1st Edition, 2014.
4. Herbert Schildt, "Java: The Complete Reference," 11th Edition, 2018.
5. Alan Mycroft and Martin Odersky, "Programming in Scala," 4th Edition, 2020.

REFERENCES:
1. Bruce Eckel, "Thinking in Java," 4th Edition, 2006.
2. Herbert Schildt, "Java: A Beginner's Guide," 8th Edition, 2019.
3. Richard Warburton, "Java 8 Lambdas: Pragmatic Functional Programming”,
1st Edition, 2014.

9
3. Pre-requisites

22CS305 - Advanced Java Programming

22CS202 – Java programming

22CS101 – problem solving using C++

10
4. Course Outcomes
At the end of this course, the students will be able to:

CO# Course Outcomes KL

CO1 Utilize the Java Collections Framework to solve complex data structure problems.. K3

CO2 Demonstrate proficiency in Java I/O operations and manage data efficiently. K3

Learn to utilize the Stream API for complex data processing by applying
CO3 K3
functional programming techniques..

CO4 Understand and implement advanced object serialization techniques. K3

CO5 Effectively use regular expressions for advanced text processing tasks. K3

CO6 Build simple applications using advanced java programming concepts. K3

11
5. CO-PO Mapping

Program Status
Program Outcomes
Course Outcomes
Outcomes PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO
1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO1 3 3 3 - - - - - - - - - 3 2 2

CO2 3 2 2 - - - - - - - - - 3 3 2

CO3 3 2 2 - - - - - - - - - 3 3 2

CO4 3 2 2 - - - - - - - - - 3 3 2

CO5 3 2 2 - - - - - - - - - 3 3 2

CO6 3 2 2 - - - - - - - - - 3 3 2

12
6. LECTURE PLAN
Sl. Taxono
No. of. Proposed Actual Pertaining Mode of
No Topics my
Periods Date Date CO Delivery
. Level
As per
As per
Time
Time table
Date & table MD 1,
1,2 2 & CO2, CO6 K3
Calendar & MD 4
Academic
Academic
Calendar
Calendar
As per
As per
Time
Comparable Time table
table MD 1,
3 interface & 1 & CO2,CO6 K3
& MD 4
Observer Interface Academic
Academic
Calendar
Calendar
As per
As per
Time
Time table
Streams - Types of table MD 1,
4 1 & CO2, CO6 K3
Streams & MD 4
Academic
Academic
Calendar
Calendar
As per
As per
The Byte-stream Time
Time table
I/O hierarchy & table MD 1,
5 1 & CO2, CO6 K3
Character Stream & MD 4
Academic
Hierarchy Academic
Calendar
Calendar
As per
As per
Random Access Time
Time table
File class – the table MD 1,
6,7 2 & CO2, CO6 K3
java.io. Console & MD 4
Academic
Class Academic
Calendar
Calendar
As per
As per
Time
Serialization – Time table
table MD 1,
8 Dates - Numbers, 1 & CO2, CO6 K3
& MD 4
and Currency Academic
Academic
Calendar
Calendar
As per
As per
Time
Working with Dates Time table
table MD 1,
9 -& Numbers and 1 & CO2, CO6 K3
& MD 4
Currencies Academic
Academic
Calendar
Calendar
As per
As per
Time
10 Time table
table
- Lab Exercises 6 & CO2, CO6 K3 iamneo
&
15 Academic
Academic
Calendar
Calendar
* MD1 – Oral Presentation
13
* MD 4 – Hands on using any Java IDE
7. Activity Based Learning
Common Activities

Learning Methods Activities

Class Exercises, Challenge Yourself,


Learn by Solving Problems
Practice At Home exercises posted in
iamneo Portal

Learn by Questioning Knowledge Check / MCQ Using iamneo


portal and RMK Nextgen App

Learn by Hands on
Practice available in iamneo Portal

Unit II Activity : Puzzle Activity: Java I/O, Date, and Currency Operations

Crossword Puzzle Sheet

Crossword Puzzle Clues:

Across

1. A stream that reads bytes from a file. (12 letters)

2. A method to format dates in Java. (15 letters)

3. An interface used to mark a class as capable of being serialized. (12 letters)

4. A class that allows for reading and writing to any location within a file. (16 letters)

Down

2. A stream that reads characters from a file. (8 letters)

3. A class used to get the current date and time. (4 letters)

4. A method to compare two dates. (10 letters)

6. A class used for formatting numbers to a currency format. (15 letters)

7. A class used for reading from and writing to the console. (7 letters)

14
7. Activity Based Learning
Crossword Puzzle Grid:

1|F|I|L|E|I|N|P|U|T|S|T|R|E|A|M

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

2| | | | | | | | | | | | | | |

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

3|D|A|T|E| | | | | | | | | | |

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

4| | | | | | | | | | | | | | |

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

5|S|I|M|P|L|E|D|A|T|E|F|O|R|M|A|T

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

6| | | | | | | | | | | | | | |

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

7| | | | | | | | | | | | | | |

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

8|S|E|R|I|A|L|I|Z|A|B|L|E| | |

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

9|R|A|N|D|O|M|A|C|C|E|S|S|F|I|L|E

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

10| | | | | | | | | | | | | | |

15
8. Lecture Notes
2.1. Date class in Java

The java.util.Date class represents a specific instant in time, with millisecond precision. The
Date class of java.util package implements Serializable, Cloneable and Comparable interface.
It provides constructors and methods to deal with date and time with java.
Constructors:

Date(): Creates a date object. Representing current date-time.


Date(long): Creates a date object. Given mills since Jan 1,1970
Date(String): Creates a date object. For specific date and time.
FORMAT: YYYY/MM/DD hh:mm:ss

Methods:

boolean after(Date date) : Tests if current date is after the given date.

boolean before(Date date) : Tests if current date is before the given date.

int compareTo(Date date) : Compares current date with given date. Returns 0 if the
argument Date is equal to the Date; a value less than 0 if the Date is before the Date
argument; and a value greater than 0 if the Date is after the Date argument.
long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
void setTime(long time) : Changes the current date and time to given time.
//Example Program1
import java.util.Date;
class DataDemo
{
public static void main(String[] a)
{
Date d1, d2, d3; d1 = new Date();
long mil = System.currentTimeMillis(); d2 = new Date(mil);
d3 = new Date("2011/3/23 12:00:10");
System.out.println(d1); System.out.println(d2); System.out.println(d3);
}}
Output

Thu Aug 10 06:26:14 GMT 2023


Thu Aug 10 06:26:14 GMT 2023
Wed Mar 23 12:00:10 GMT 2011
8. Lecture Notes
//Example Program2

import java.util.*;
public class DateDemo

public static void main(String[] args)

// Creating date

Date d1 = new Date(2000, 11, 21);

Date d2 = new Date(); // Current date

Date d3 =new Date(2010, 1, 3);

boolean a = d3.after(d1);
System.out.println("Date d3 comes after " + "date d2: " + a);
boolean b =d3.before(d2);
System.out.println("Date d3 comes before "+"date d2: " + b);
int c = d1.compareTo(d2);
System.out.println(c);

System.out.println("Miliseconds from Jan 1 "+ "1970 to date d1 is "


+ d1.getTime());
System.out.println("Before setting "+d2);
d2.setTime(204587433443L);

System.out.println("After setting "+d2);

Output
Date d3 comes after date d2: true
Date d3 comes before date d2: false
Miliseconds from Jan 1 1970 to date d1 is 60935500800000 Before setting Thu Aug 10
14:31:50 GMT 2023

After setting Fri Jun 25 21:50:33 GMT 1976


17
8. Lecture Notes
Date in Java Constructors:
Date() - Allocates a Date object and initializes it so that it represents the time at which it was
allocated, measured to the nearest millisecond.
Date(long date) - Allocates a Date object and initializes it to represent the specified
number of milliseconds since the standard base time known as "the epoch", namely
January 1, 1970, 00:00:00 GMT.

//Java program to demonstrate constuctors of Date


import java.util.*;

public class Main


{
public static void main(String[] args)
{
Date d1 = new Date();
System.out.println("Current date is " + d1);
Date d2 = new Date(2323223232L);
System.out.println("Date represented is "+ d2 );

}
}
Output
Current date is Tue Aug 15 14:27:06 GMT 2023
Date represented is Tue Jan 27 21:20:23 GMT 1970

Date in Java – Methods and Description

boolean after(Date when) - Tests if this date is after the specified date. boolean
before(Date when) - Tests if this date is before the specified date. Object clone() - Return a
copy of this object.

int compareTo(Date anotherDate) - Compares two Dates for ordering.

boolean equals(Object obj) – Compares two dates for equality.


static Date from(Instant instant) – Obtains an instance of Date from an Instant object.

18
8. Lecture Notes
The java.text.SimpleDateFormat class provides methods to format and parse date and time
in java.
The SimpleDateFormat is a concrete class for formatting and parsing date which inherits
java.text.DateFormat class.

Note- formatting means converting date to string and parsing means converting string to
date.

Formatting Dates:

Java's DateFormat class offers the format() method for formatting a given date to a Date/Time
string. This method is used to convert this date and time into an appropriate format,
i.e., mm/dd/yyyy.

Syntax:
public final String format(Date date)

//Example 1 : Java SimpleDateFormat - Date to String

import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample
{
public static void main(String[] args)
{
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formatter.format(date);
System.out.println(strDate);
}
}
Output
17/08/2023

//Example 2 : Full example to format date and time in java using java.text.SimpleDateFormat
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SimpleDateFormatExample
{
public static void main(String[] args)
{
Date date = new Date();

19
8. Lecture Notes
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println("Date Format with MM/dd/yyyy : "+strDate);
formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
strDate = formatter.format(date);
System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
strDate = formatter.format(date);

System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);

Output

Date Format with MM/dd/yyyy : 08/17/2023


Date Format with dd-M-yyyy hh:mm:ss : 17-8-2023 02:15:09
Date Format with dd MMMM yyyy : 17 August 2023
Date Format with dd MMMM yyyy zzzz : 17 August 2023
Greenwich Mean Time Date Format with E, dd MMM yyyy HH:mm:ss z : Thu, 17 Aug 2023
14:15:09 GMT

Parsing Dates
Parsing is the process of converting Strings into Java.util.Date instances.

20
8. Lecture Notes
parse() method of the SimpleDateFormat class is used to parse a string into a date instance. Strings
can be converted to dates using the SimpleDateFormat class, which takes a string pattern as input
and applies it to the class constructor.

Syntax:
public Date parse()
Note: M (capital M) represents month and m (small m) represents minute in java.
Parsing Dates - Example
import java.text.*;

import java.util.Calendar;
public class Main
{
public static void main(String[] args) throws InterruptedException
{
SimpleDateFormat d = new SimpleDateFormat("MM / dd / yy");
try
{
Calendar c = Calendar.getInstance();
// Use of .parse() method to parse Date From String 's' String str = "08 / 18 / 23";
c.setTime(d.parse(str));

System.out.println("Time parsed from String : " + c.getTime());


}
catch (ParseException except)
{
except.printStackTrace();
}
}
}
Output:
Time parsed from String : Fri Aug 18 00:00:00 GMT 2023

Simple DateFormat Format Codes

To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as
pattern letters, which are defined as the following:

21
8. Lecture Notes
Character Description Example

G Era designator AD

y Year in four digits 2001

M Month in year July or 07

d Day in month 10

h Hour in A.M./P.M. (1~12) 12

H Hour in day (0~23) 22

m Minute in hour 30

s Second in minute 55

S Millisecond 234

E Day in week Tuesday

D Day in year 360

2
F Day of week in month
(second Wed. in July)

w Week in year 40

W Week in month 1

a A.M./P.M. marker PM

k Hour in day (1~24) 24

K Hour in A.M./P.M. (0~11) 10

z Time zone Eastern Standard Time

' Escape for text Delimiter

" Single quote `

22
8. Lecture Notes
2.2. Calendar Class in Java

❑ Calendar class in Java is an abstract class that provides methods for converting date between

a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc.

❑ It inherits Object class and implements the Comparable, Serializable, Cloneable interfaces.

❑ As it is an Abstract class, we cannot use a constructor to create an instance.

❑ Instead, we will have to use the static method Calendar.getInstance() to instantiate and

implement a sub-class.

❖ Calendar.getInstance(): return a Calendar instance based on the current time in the

default time zone with the default locale.

❖ Calendar.getInstance(TimeZone zone)

❖ Calendar.getInstance(Locale aLocale)

❖ Calendar.getInstance(TimeZone zone, Locale aLocale)

//Java program to demonstrate getInstance() method:

import java.util.*;
public class Calendar1 {
public static void main(String args[])
{
Calendar c = Calendar.getInstance();
System.out.println("The Current Date is:" + c.getTime());
}
}

Output:
The Current Date is: Tue Aug 28 11:10:40 UTC 2018
8. Lecture Notes
METHOD DESCRIPTION

It is used to add or subtract the specified


abstract void add(int field, int amount) amount of time to the given calendar field,
based on the calendar’s rules.
It is used to return the value of the given
int get(int field)
calendar field.

It is used to return the maximum value for the


abstract int getMaximum(int field)
given calendar field of this Calendar instance.

It is used to return the minimum value for the


abstract int getMinimum(int field)
given calendar field of this Calendar instance.

It is used to return a Date object representing


Date getTime()
this Calendar’s time value.

//get() method

import java.util.*;
public class Calendar2 {
public static void main(String[] args)
{
// creating Calendar object
Calendar calendar = Calendar.getInstance();
// Demonstrate Calendar's get()method
System.out.println("Current Calendar's Year: " + calendar.get(Calendar.YEAR));
System.out.println("Current Calendar's Day: " + calendar.get(Calendar.DATE));
System.out.println("Current MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("Current SECOND: " + calendar.get(Calendar.SECOND));
}
}
Output:
Current Calendar's Year: 2018
Current Calendar's Day: 28
Current MINUTE: 10
Current SECOND: 45.
8. Lecture Notes
//getMaximum() method – Example Program
import java.util.*;
public class Calendar3 {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();
int max = calendar.getMaximum(Calendar.DAY_OF_WEEK);
System.out.println("Maximum number of days in a week: " + max);
max = calendar.getMaximum(Calendar.WEEK_OF_YEAR);
System.out.println("Maximum number of weeks in a year: " + max);
}
}
Output:
Maximum number of days in a week: 7
Maximum number of weeks in a year: 53
//getMinimum() method – Example Program

// Program to demonstrate getMinimum() method of Calendar class

import java.util.*;
public class Calendar4 {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();
int min = calendar.getMinimum(Calendar.DAY_OF_WEEK);
System.out.println("Minimum number of days in week: " + min);
min = calendar.getMinimum(Calendar.WEEK_OF_YEAR);
System.out.println("Minimum number of weeks in year: " + min);
}
}
Output:
Minimum number of days in week: 1
Minimum number of weeks in year: 1
8. Lecture Notes
//add() method – Example Program
// Program to demonstrate add() method
// of Calendar class
import java.util.*;
public class Calendar5 {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}
Output:
15 days ago: Mon Jul 31 15:38:32 GMT 2023
4 months later: Thu Nov 30 15:38:32 GMT 2023
2 years later: Sun Nov 30 15:38:32 GMT 2025

Date object using the Calendar class


import java.util.*;
public class DateObjectWithClass
{
public static void main(String[] args)
{
int year = 2016;
int month = 0; // January int date = 1;
Calendar cal = Calendar.getInstance();
// Sets the given calendar field value and the time value
// (millisecond offset from the Epoch) of this Calendar undefined.
cal.clear();
System.out.println();
cal.set(Calendar.YEAR, year);
8. Lecture Notes
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DATE, date);
System.out.println(cal.getTime());
System.out.println();
}
}
Output
Fri Jan 01 00:00:00 GMT 2016

//Java program to convert a string to a date


import java.time.*;
import java.util.*;
import java.time.format.DateTimeFormatter;
class Main
{
public static void main(String[] args)
{
String string = "August 15, 2023"; DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH); LocalDate date =
LocalDate.parse(string, formatter); System.out.println();
System.out.println(date); System.out.println();
}
}
Output
Aug 15,2023

//Java program to display dates in the following formats.


import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
8. Lecture Notes
public class DateParseFormatDemo

public static void main(String[] args)

//Format examples

LocalDate date = LocalDate.now();

//default format

System.out.println("\nDefault format of LocalDate="+date); //specific format

System.out.println(date.format(DateTimeFormatter.ofPattern ("d::MMM::uuuu")));

LocalDateTime dateTime = LocalDateTime.now();

//default format

System.out.println("Default format of LocalDateTime="+dateTime);

//specific format

System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));

Instant timestamp = Instant.now();

//default format

System.out.println("Default format of Instant="+timestamp); //Parse examples

LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",

DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));

System.out.println("Default format after parsing = "+dt+"\n");

Output
Default format of LocalDate = 2023-08-15 15::Aug::2023
Default format of LocalDateTime = 2023-08-15T16:21:01.491605 15::Aug::2023 16::21::01
Default format of Instant = 2023-08-15T16:21:01.492268Z
Default format after parsing = 2014-04-27T21:39:48
8. Lecture Notes
2.3. Java Comparable interface

❑ Java Comparable interface is used to order the objects of the user-defined class.

❑ This interface is found in java.lang package and contains only one method named
compareTo(Object).

❑ It provides a single sorting sequence only, i.e., we can sort the elements on the basis of single data
member only. For example, it may be rollno, name, age or anything else.

❖ compareTo(Object obj) method


public int compareTo(Object obj): It is used to compare the current object with the specified
object.

It returns

➢ positive integer, if the current object is greater than the specified object.

➢ negative integer, if the current object is less than the specified object.

➢ zero, if the current object is equal to the specified object. Able to sort the elements of:
1. String objects Wrapper class objects
2. Class Objects
3. User-defined class objects
❖ Recap:
Method of Collections class for sorting List elements
public void sort(List list);
➢ It is used to sort the elements of List.
➢ List elements must be of the Comparable type.
Note: String class and Wrapper classes implement the Comparable interface by default. So if we store
the objects of string or wrapper classes in a list, set or map, it will be Comparable by default.
//Example Program
import java.util.*;
public class TestSort1
{
public static void main(String args[])
{
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(4026,"Hema Sree R",19));
al.add(new Student(4052,"Jammuladinne Ajay",20));
al.add(new Student(4067,"Kaviya P",18));
Collections.sort(al);
for(Student st:al)
{
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
} 29

}
8. Lecture Notes
//Java Comparable Example
class Student implements Comparable<Student>
{
int rollno;
String name;
int age;

Student(int rollno, String name,int age)


{
this.rollno=rollno;
this.name=name;
this.age=age;

}
public int compareTo(Student st)
{
if(age==st.age) return 0;
else if(age>st.age) return 1;

else return -1;


}
}

Output
4067 Kaviya P 18
4026 HemaSree R 19
4052 Jammuladinne Ajay 20

//Java Comparable Example: reverse order


class Student implements Comparable<Student>
{
int rollno;
String name;
int age;
Student(int rollno,String name,int age)
{
this.rollno=rollno;
this.name=name;
this.age=age; 30
}
8. Lecture Notes
public int compareTo(Student st)
{
if(age==st.age)
return 0;
else if(age<st.age)
return 1;
else
return -1;
}
}

import java.util.*;
public class TestSort2{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:

106 Ajay 27
101 Vijay 23
105Jai 21

2.4. Observer Interface:

The Observer interface is used to notify “Observers” of the changes made to the
Observable. It is mainly used to implement the Observer Pattern in Java. It has been
around since Java 1.
The Observer interface has only one method, void update(Observable o, Object arg).
The Observable o is the observable object from java.util.Observable class. The arg object
is any optional object that can be passed as argument by the notifying Observable
class. A class that implements the Observer interface, declares itself eligible to listen to the
changes made to the observables.
The Observer pattern establishes a one-to-many relationship between objects, ensuring
that when one object updates its state, all dependent observers are notified and updated
automatically.

31
8. Lecture Notes
Usage:
➢ When the change of a state in one object must be reflected in another object without keeping the
objects tight coupled.
➢ When the framework we writes and needs to be enhanced in future with new observers with
minimal changes.
It also provides method to the Observer instances to hook on with itself, or unhook. Few methods in
the java.util.Observable class are:

➢ public void addObserver(Observer o) -- Add an Observer.

➢ public void deleteObserver(Observer o) --- Delete an Observer.

➢ public void notifyObservers() --- notify observers of changes.

❖ Observer Pattern

UML for Observer Pattern


❖ Implementation of Observer Pattern
Step 1:
Create a ResponseHandler1 class the will implement the java.util.Observer interface.
//This is a class.
import java.util.Observable;
import java.util.Observer;
public class ResponseHandler1 implements Observer {
private String resp;
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
resp = (String) arg;
System.out.println("\nReceived Response: " + resp );
}
}
}// End of the ResponseHandler1 interface

32
8. Lecture Notes
Step 2:
Create a ResponseHandler2 class the will implement the java.util.Observer
interface.
//This is a class.
import java.util.Observable;
import java.util.Observer;
public class ResponseHandler2 implements Observer {
private String resp;
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
resp = (String) arg;
System.out.println("\nReceived Response: " + resp );
}
}
}// End of the ResponseHandler2 interface.
Output:

The Observer and Observable are used to implement the Observer Pattern in Java. This
pattern is used when a multiple number of instances called Observers are listening to changes
to a particular class called Observable. For example, if the underlying data- source changes, all
the views using that data-source should reflect the changes. Here is a simple weather reporting
system, which tries to implement the Observer Pattern using the Observer interface and
Observable class,
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;
import java.util.Observer;
class ResponseHandler1 implements Observer {
private String resp;
public void update(Observable obj, Object arg)
{
if (arginstanceof String) {
resp = (String) arg;
System.out.println("\nReceived Response: " + resp ); }
} 33
}
8. Lecture Notes
class ResponseHandler2 implements Observer {

private String resp;

public void update(Observable obj, Object arg) {

if (arginstanceof String) {

resp = (String) arg;

System.out.println("\nReceived Response: " + resp ); }

❖ Observable
❑ The java.util.Observable class is used along with Observer instance to implement the Observer
pattern.
❑ A class whose changes are to be tracked by the observers, extends the java.util.Observable
class.
❑ This class has implemented methods for updating/notifying the Observers about the changes
made to the Observable.
class EventSource extends Observable implements Runnable
{
@Override public void run()
{
try {
finalInputStreamReaderisr = new InputStreamReader(System.in);
finalBufferedReaderbr = new BufferedReader(isr);
while (true) {
String response = br.readLine();
setChanged();

notifyObservers(response); }
}
catch (IOException e) {
e.printStackTrace(); }
}
}
public class ObserverPatternDemo
{
public static void main(String[] args)
{
System.out.println("Enter Text >");
// create an event source - reads from stdin
final EventSourceeventSource = new34 EventSource();
8. Lecture Notes
// create first observer
final ResponseHandler1 responseHandler1 = new ResponseHandler1();
// subscribe the observer to the event source
eventSource.addObserver(responseHandler1);
// create second observer
final ResponseHandler2 responseHandler2 = new ResponseHandler2();
// subscribe the observer to the event source
eventSource.addObserver(responseHandler2);

// starts the event thread


Thread thread = new Thread(eventSource); thread.start();
}
}
Output
Enter Text >
I am Observer
Received Response: I am Observer
Received Response: I am Observer
2.6. Streams in Java

❖A simple java program takes an input, process the input and produces the output.
❖Input can be taken from the keyboard, from a file, from main memory or from elsewhere.

❖Now if the input is defined inside the program itself, then running it anytime would present us
the same output.
❖In Order for an effective use of the program the input has to be received from outside of the
program. Hence Input / Output functions are defined.

❖Streams are used to handle input/output operations fast.

❖Stream is like a pipe which carries data from one end to the other. The end points are nothing
but the source and destination of the data to be read/written. Getting input from console and
writing in a file.
❖The java.io package contains all the classes required for input and output operations.

❖A stream in Java is a sequence of objects that supports various methods which can be pipelined
to produce the desired result.

Streams
35
8. Lecture Notes
Use of Stream in Java
There uses of Stream in Java are mentioned below:
1.Stream API is a way to express and process collections of objects.
2.Enable us to perform operations like filtering, mapping, reducing and sorting.
Steps to create Stream:
Java Stream Creation is one of the most basic steps before considering the functionalities of the Java
Stream. Below is the syntax given on how to declare Java Stream.
Syntax
Stream<T> stream;
Here T is either a class, object, or data type depending upon the declaration.
Java Stream Features:
The features of Java stream are mentioned below:
•A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
•Streams don’t change the original data structure, they only provide the result as per the pipelined
methods.
•Each intermediate operation is lazily executed and returns a stream as a result, hence various
intermediate operations can be pipelined. Terminal operations mark the end of the stream and
return the result.
Different Operations On Streams
There are two types of Operations in Streams:
1. Intermediate Operations
2. Terminate Operations
❖ Intermediate Operations

36
8. Lecture Notes
Intermediate Operations are the types of operations in which multiple methods are chained in a row.
Characteristics of Intermediate Operations
1. Methods are chained together.
2. Intermediate operations transform a stream into another stream.
3. It enables the concept of filtering where one method filters data and passes it to another
method after processing.
❖ Benefit of Java Stream
There are some benefits because of which we use Stream in Java as mentioned below:
•No Storage
•Pipeline of Functions
•Laziness
•Can be infinite
•Can be parallelized
•Can be created from collections, arrays, Files Lines, Methods in Stream, IntStream etc.

❖ Important Intermediate Operations


There are a few Intermediate Operations mentioned below:
1. map()
The map method is used to return a stream consisting of the results of applying the given function to
the elements of this stream.
List number = Arrays.asList(2,3,4,5);
List square = number.stream().map(x->x*x).collect(Collectors.toList());
2. filter()
The filter method is used to select elements as per the Predicate passed as an argument.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());
3. sorted()
The sorted method is used to sort the stream.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().sorted().collect(Collectors.toList());

❖ Terminal Operations
Terminal Operations are the type of Operations that return the result. These Operations are not
processed further just return a final result value.

37
8. Lecture Notes
Important Terminal Operations
There are a few Terminal Operations mentioned below:
1. collect()
The collect method is used to return the result of the intermediate operations performed on the
stream.
List number = Arrays.asList(2,3,4,5,3);
Set square = number.stream().map(x->x*x).collect(Collectors.toSet());
2. forEach()
The forEach method is used to iterate through every element of the stream.
List number = Arrays.asList(2,3,4,5);
number.stream().map(x->x*x).forEach(y->System.out.println(y));
3. reduce()
The reduce method is used to reduce the elements of a stream to a single value. The reduce
method takes a BinaryOperator as a parameter.
List number = Arrays.asList(2,3,4,5);
int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
Here ans variable is assigned 0 as the initial value and i is added to it.

Note: Intermediate Operations are running based on the concept of Lazy Evaluation, which
ensures that every method returns a fixed value(Terminal operation) before moving to the next
method.
// Java program to demonstrate
// the use of stream in java
import java.util.*;
import java.util.stream.*;
class Demo {
public static void main(String args[])
{
// create a list of integers
List<Integer> number = Arrays.asList(2, 3, 4, 5);
// demonstration of map method
List<Integer> square
= number.stream()
.map(x -> x * x)
.collect(Collectors.toList());
38
8. Lecture Notes
// create a list of String
List<String> names = Arrays.asList("Reflection", "Collection", "Stream");
// demonstration of filter method
List<String> result = names.stream()
.filter(s -> s.startsWith("S"))
.collect(Collectors.toList());
System.out.println(result);
// demonstration of sorted method
List<String> show
= names.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(show);
// create a list of integers
List<Integer> numbers
= Arrays.asList(2, 3, 4, 5, 2);
// collect method returns a set
Set<Integer> squareSet
= numbers.stream()
.map(x -> x * x)
.collect(Collectors.toSet());
System.out.println(squareSet);
// demonstration of forEach method
number.stream().map(x -> x * x)
.forEach(y -> System.out.println(y));

// demonstration of reduce method


int even = number.stream()
.filter(x -> x % 2 == 0)
.reduce(0, (ans, i) -> ans + i);
System.out.println(even);
}
}
Output
[4, 9, 16, 25]
[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6
2.6. Types of Streams :

The Streams in Java IO are of the following types:


2.7. Byte Streams – Java byte streams are the ones that are used to implement the input
and output of 8-bit bytes. Several classes are affiliated with byte streams. In Java. However,
the most generally practiced classes are FileInputStream and FileOutputStream.

39
8. Lecture Notes

Types of Streams
Different classes of Byte Streams

S. No. Stream Class Description

1 InputStream This is an abstract class that defines stream input.

2 FileInputStream This is used to reads from a file.

It contains a method for reading java standard


3 DataInputStream
datatypes.

4 BufferedInputStream It is used for Buffered Input Stream.

This class comprises the commonly used print() and


5 PrintStream
println() methods.

6 OutputStream This is an abstract class that describes stream output.

7 FileOutputStream This class is used to write to a file.

This contains a method for writing java standard data


8 DataOutputStream
types.

9 BufferedOutputStream This is used for Buffered Output Stream.

40
8. Lecture Notes
2.8. Character Streams :

Java Character streams are the ones that are used to implement the input and output for 16-bit
Unicode. Several classes are associated with character streams in Java, but the most commonly
used classes are FileReader and FileWriter. Internally, the FileReader class uses
FileInputStream and the FileWriter class uses FileOutputStream. Nevertheless, the significant
contrast is that FileReader and FileWriter read and write two bytes, respectively.

Different classes of Character Streams:

S. No. Stream Classes Description

1 Reader This is an abstract class that defines character stream input.

2 Writer This is an abstract class that defines character stream output.

3 FileReader This is an input stream that reads from the file.

4 FileWriter This is used to the output stream that writes to the file.

5 BufferedReader It is used to handle buffered input streams.

6 BufferedWriter This is used to handle buffered output streams.

7 InputStreamReader This input stream is used to translate the byte to the character.

8 OutputStreamReader This output stream is used to translate characters to bytes.

9 PrintWriter This contains the most used print() and println() methods.

❖ Standard Streams
All the programming languages assist standard I/O, where the user’s program can take input
from a keyboard and then produce an output on the computer screen. Just like C and C++ have
three standard streams, STDIN, STDOUT, and STDERR, Java also provides the following three
standard streams:

41
8. Lecture Notes
Input / Output Streams
❖Java supports various Streams with its I/O package that helps the user to perform all the
input-output operations.
❖These streams support all the types of objects, data-types, characters, files etc to fully execute
the I/O operations.

❖ InputStream - The InputStream is used to read data from a source. Java application uses an input
stream to read data from a source It may be a file, an array, peripheral device or socket.
❖ OutputStream - The OutputStream is used for writing data to a destination. Java application uses
an output stream to write data to a destination It may be a file, an array, peripheral device or
socket.
❖ Before exploring various input and output streams we discuss 3 Standard or Default Streams that
Java has to provide which are also most common in use:
❖ System.in:
This is the standard input stream that is used to read characters from the keyboard or any other
standard input device.
❖ System.out:
This is the standard output stream that is used to produce the result of a program on an output
device like the computer screen.
Here is a list of the various print functions that we use to output statements:
❖ print(): This method in Java is used to display a text on the console and the cursor remains
at the end of the text at the console.
Syntax : System.out.print(parameter);
❖ println(): This method in Java is also used to display a text on the console and the cursor moves
to the start of the next line at the console.
Syntax : System.out.println(parameter);
❖ printf(): This is the easiest of all methods similar to printf in C.

Note: System.out.print() and System.out.println() take a single argument, but printf() may take
multiple arguments. This is used to format the output in Java.
❖ System.err:

This is the standard error stream that is used to output all the error data that a program might throw,
on a computer screen or any standard output device. This stream also uses all the 3 above-mentioned
functions to output the error data: print(), println() & printf()

42
8. Lecture Notes
❖ InputStream Class

InputStream class is an abstract class. It is the superclass of all classes representing an input stream of
bytes.

❖ InputStream Hierarchy

❖ OutputStream Class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some destination.
❖ OutputStream Hierarchy

43
8. Lecture Notes
ByteStream and CharacterStream
❖ Depending on the types of file, Streams can be divided into two primary classes
1. ByteStream
2. CharacterStream

❖ Byte Streams
❖Java byte streams are used to perform input and output of 8-bit bytes.
❖Though there are many classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream.

Example which makes use of these two classes to copy an input file into an output file
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); }
}
finally {
if (in != null) {
in.close(); }
if (out != null) {
out.close(); }
}
} 44

}
8. Lecture Notes
Now let's have a file input.txt with the following content: This is test for copy file. As a next
step, compile the above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt.

So let's put the above code in CopyFile.java file and do the following:

$javac CopyFile.java

$java CopyFile

Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character
streams are used to perform input and output for 16-bit unicode. Though there are many
classes related to character streams, most frequently used classes are, FileReader and
FileWriter.

Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here the major difference is that FileReader reads two bytes at a time and FileWriter writes two
bytes at a time.
import java.io.*;
public class CopyFile

{
public static void main(String args[]) throws IOException
{
FileReader in = null; FileWriter out = null;
try

{
in = new FileReader("input.txt"); out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}
finally
{
if (in != null) {
in.close(); }
if (out != null) {
out.close(); }
} 45
}
}
8. Lecture Notes
Now let's have a file input.txt with the following content: This is test for copy file. As a next
step, compile the above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt.

So let's put the above code in CopyFile.java file and do the following:
$javac CopyFile.java
$java CopyFile
2.9. Random Access File class
➢ This class is used for reading and writing to random access file.
➢ A random access file behaves like a large array of bytes.
➢ There is a cursor implied to the array called file pointer, by moving the cursor
read/write operations are done.
❖ If end-of-file is reached before the desired number of byte has been read than EOFException
is thrown.
❖ It is a type of IOException Declaration :
public class RandomAccessFile extends Object implements DataOutput,
DataInput, Closeable
While creating the instance of RandomAccessFile in java, it is necessary to provide the mode to
open the file.
for example,
▪ to open the file for read only mode we have to use “r”
▪ for read-write operations we have to use “rw”
▪ Using file pointer, read or write data from random access file at any position can
be done.
❖ Constructors and its Description

RandomAccessFile(File file, String mode) - Creates a random access file stream to read from,
and optionally to write to, the file specified by the File argument.

RandomAccessFile(String name, String mode) - Creates a random access file stream to read
from, and optionally to write to, a file with the specified name.

❖ Methods and its Description:


int read() - It reads byte of data from a file. The byte is returned as an integer in the range 0-
255.
int read(byte[] b) – It reads byte of data from file upto b.length, -1 if end of file is reached.
int read(byte[] b, int offset, int len) - It reads bytes initialising from offset position
upto b.length from the buffer.
readBoolean() - It reads a boolean value from the file.
byte readByte() - It reads signed eight-bit value from file.
46
8. Lecture Notes
char readChar() - It reads a character value from file.

double readDouble() - It reads a double value from file.

float readFloat() - It reads a float value from file.

int readInt() - It reads a integer value from file.

void readFully(byte[] b) - It reads bytes initialising from offset position upto b.length from the
buffer.
void readFully(byte[] b, int offset, int len) - It reads bytes initialising from offset position upto
b.length from the buffer.

String readUTF() - It reads in a string from the file.

void seek(long pos) - It sets the file-pointer(cursor) measured from the beginning of the file, at
which the next read or write occurs.

long length() - It returns the length of the file.

void write(int b) - It writes the specified byte to the file from the current cursor position.

void writeFloat(float v) - It converts the float argument to an int using the floatToIntBits
method in class Float, and then writes that int value to the file as a four- byte quantity, high byte
first.
void writeDouble(double v) - It converts the double argument to a long using the
doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte
quantity, high byte first.
Example
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileExample


{
static final String FILEPATH ="inputfile.txt";
public static void main(String[] args)
{
try
{
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);

}
47
catch (IOException e)
8. Lecture Notes
{
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size) throws IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size]; file.read(bytes); file.close();

return bytes;
}
private static void writeToFile(String filePath, String data, int position) throws
IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position); file.write(data.getBytes()); file.close();

}
}
Output – in a File
I love my country and my people
2.10 the java.io. Console Class
❖ 3 Ways To Read Java Input:
1.Java Bufferedreader Class to read input
➢ This is the Java traditional technique, introduced in JDK1.0.
➢ This strategy is utilized by wrapping the System.in in an InputStreamReader
which is wrapped in a Java BufferedReader
➢ Can read result include from the user in the order line Example of Java Bufferedreader
Class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println(name); } }

Output:

Java Programming
48
Java Programming
8. Lecture Notes
2. Java Scanner Class to read input
➢ This is probably the most preferred method to take input.
➢ The main purpose of the Scanner class is to parse primitive types and strings using regular
expressions.
➢ However it is also can be used to read input from the user in the command line Example of
Java Bufferedreader Class
import java.util.Scanner;
class Main // GetInputFromUser
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in); String s
= in.nextLine(); System.out.println("You entered String "+s); int a = in.nextInt();
System.out.println("You entered Integer "+a); float b = in.nextFloat();
System.out.println("You entered Float "+b); }
}
Output:
Java Programming
You entered String Java Programming 99
You entered Integer 99 99999.99 You entered Float 99999.99
3. Java Console Class to read input
➢ It has been becoming a way for reading user’s input from the preferred command line.
➢ In addition, it can be used for reading password-like input without echoing the characters
entered by the user.
➢ The format string syntax can also be used (like System.out.printf()).

//Example - Java Console Class


public class Main // ConsoleSample
{
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();
System.out.println(name);

} }
Output:
49
Java Programming
Java Programming
8. Lecture Notes
Java Console Class to read Password input
import java.io.Console;
class Main //ReadPasswordTest
{
public static void main(String args[])
{
System.out.println("Enter password: ");
char[] ch=System.console().readPassword();
String pass=String.valueOf(ch);
//converting char array into string
System.out.println("Password is: "+pass);
}
}
Output:
Enter password:
Password is: Testpassword123

//line on the console


import java.io.*;
public class Main // FileTest
{
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
// This will reference one line at a time String line = null;
try
{
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + fileName + "'");
} catch(IOException ex)
{
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
ex.printStackTrace(); }
} // main()
} // Class Main

50
8. Lecture Notes
2.11. Serialization in Java
❖ Serialization in Java is a mechanism of writing the state of an object into a byte-stream.

❖ Java provides a mechanism, called object serialization where an object can be represented
as a sequence of bytes that includes the object's data as well as information about the
object's type and the types of data stored in the object.

❖ It can then saved to a database or transfer over a network.

❖ The reverse operation of serialization is called deserialization where byte-stream is converted


into an object.

❖ The serialization and deserialization process is platform-independent, it means you can


serialize an object on one platform and deserialize it on a different platform.

❖ Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain


the methods for serializing and deserializing an object.

❖ For serializing the object, we call the writeObject() method of ObjectOutputStream class.
For deserialization, we call the readObject() method of ObjectInputStream class. We
must have to implement the Serializable interface. for serializing the object .

❖ Serializable is a marker interface (has no data member and method).


❖ It is used to "mark" Java classes so that the objects of these classes may get a
certain capability.
❖ The Serializable interface must be implemented by the class whose object needs to be
persisted.
❖ The String class and all the wrapper classes implement the java.io.Serializable
interface by default.

51
8. Lecture Notes
❖ Serializable Interface: Classes must implement java.io.Serializable to be serialized.

❖ ObjectOutputStream and ObjectInputStream: Used for writing and reading serialized objects.

❖ Example:
import java.io.*;
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
Employee(String name, int age) {
this.name = name;
this.age = age;
}
}
public class SerializationExample {
public static void main(String[] args) {
Employee emp = new Employee("John", 30);
// Serialization
try (FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(emp);
}
catch (IOException i) {
i.printStackTrace();
}
// Deserialization
Employee deserializedEmp = null;
try (FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {
deserializedEmp = (Employee) in.readObject();
}
catch (IOException | ClassNotFoundException i) {
i.printStackTrace();
}
System.out.println("Deserialized Employee: " + deserializedEmp.name + ", " +
deserializedEmp.age);
}
}
52
8. Lecture Notes
Explanation of the above code:
Importing Necessary Classes:
java.io.Serializable: An interface that classes must implement to be serializable.
java.io.FileOutputStream and java.io.FileInputStream: Used for writing to and reading from a
file.
java.io.ObjectOutputStream and java.io.ObjectInputStream: Used for writing and reading
objects to and from streams.
Employee Class Definition:
implements Serializable: Marks the Employee class as serializable.
serialVersionUID: A unique identifier for the class, used during deserialization to ensure that a
loaded class corresponds exactly to a serialized object.
Fields: name and age to store employee details.
Constructor: Initializes the name and age fields.
SerializationExample Class Definition:
Initializes an Employee object with name "John" and age 30.
FileOutputStream: Creates a file output stream to write to employee.
ser.ObjectOutputStream: Wraps the file output stream to write objects.
writeObject(emp): Serializes the emp object and writes it to the file.
try-with-resources: Ensures that the streams are closed automatically.
IOException: Catches and handles any I/O exceptions that occur during serialization.
Deserialization:
FileInputStream: Creates a file input stream to read from employee.
ser.ObjectInputStream: Wraps the file input stream to read objects.
readObject(): Reads the serialized Employee object from the file and casts it to Employee.
IOException | ClassNotFoundException: Catches and handles any I/O or class not found
exceptions that occur during deserialization.
Prints the details of the deserialized Employee object.
❖ Serialization – Dates
//Example Program
import java.io.*;
import java.util.Date;
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
String name;
53
int age;
Date hireDate;
8. Lecture Notes
Employee(String name, int age, Date hireDate) {
this.name = name;
this.age = age;
this.hireDate = hireDate;
}
}
public class SerializationWithDateExample {
public static void main(String[] args) {
Employee emp = new Employee("John", 30, new Date());
// Serialization
try (FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(emp);
System.out.println("Employee object serialized: " + emp.name + ", " + emp.age + ", "
+ emp.hireDate);
} catch (IOException i) {
i.printStackTrace();
}
// Deserialization
Employee deserializedEmp = null;
try (FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {
deserializedEmp = (Employee) in.readObject();
System.out.println("Employee object deserialized: " + deserializedEmp.name + ", " +
deserializedEmp.age + ", " + deserializedEmp.hireDate);
} catch (IOException | ClassNotFoundException i) {
i.printStackTrace();
}
}
}
Explanation of the above Code:
Employee Class Definition:
implements Serializable: Marks the Employee class as serializable.
Fields: name, age, and hireDate (of type Date).
Constructor: Initializes name, age, and hireDate.
54
8. Lecture Notes
Serialization:
Creating an Employee Object: Initializes an Employee object with name, age, and the current
date (hireDate).
Writing the Object to a File: Uses ObjectOutputStream to serialize the Employee object and
write it to employee.
ser.Output: Prints a confirmation message showing the serialized object's details.
Deserialization:
Reading the Object from a File: Uses ObjectInputStream to deserialize the Employee object
from employee.ser.Output: Prints a confirmation message showing the deserialized object's
details.
❖ Serialization - Working with Number and Currency Formatting
Java provides classes such as NumberFormat and Currency for formatting numbers and
currencies in a locale-sensitive manner.

//Example Program
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Currency;
public class NumberCurrencyExample {
public static void main(String[] args) {
double number = 1234567.89;
// Formatting numbers
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
String formattedNumber = numberFormat.format(number);
System.out.println(formattedNumber); // Output: 1,234,567.89
// Formatting currency
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
String formattedCurrency = currencyFormat.format(number);
System.out.println(formattedCurrency); // Output: $1,234,567.89
// Working with Currency
Currency usd = Currency.getInstance("USD");
System.out.println(usd.getSymbol()); // Output: $
}
}
55
8. Lecture Notes
Explanation of the above code:
Importing Necessary Classes
NumberFormat: This class provides methods for formatting and parsing numbers.
Locale: Represents a specific geographical, political, or cultural region. It affects how
numbers, dates, and currencies are formatted.
Currency: Represents a currency. Provides information like currency code, symbol, and the
default fraction digits.
Formatting Numbers
Creating a Number Format Instance: NumberFormat.getNumberInstance(Locale.US)
creates a number formatter for the US locale, which uses commas as thousand separators
and a period as a decimal separator.
Formatting the Number: numberFormat.format(number) formats the number variable
according to the locale-specific rules.Output: The formatted number is printed as
‘1,234,567.89’.
Formatting Currency
Creating a Currency Format Instance: NumberFormat.getCurrencyInstance (Locale.US)
creates a currency formatter for the US locale.
Formatting the Currency: currencyFormat.format(number) formats the number variable as
currency according to the locale-specific rules.
Output: The formatted currency is printed as ‘$1,234,567.89’.
Working with Currency
Getting Currency Instance: Currency.getInstance("USD") gets a Currency instance
representing the US Dollar.
Getting the Symbol: usd.getSymbol() returns the symbol of the currency, which is $ for the
US Dollar.
Output: The currency symbol is printed as $.

❖ NumberFormat: Used to format numbers in a locale-sensitive way. It can be configured for


different locales to handle various number formatting conventions.
❖ NumberFormat for Currency: Specialization of NumberFormat for formatting monetary
values. It automatically applies the correct currency symbol and formatting rules based on
the locale.
❖ Currency: Provides information about a specific currency, such as its symbol and code.

56
8. Lecture Notes
class SerializeDemo
{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Jackr";
e.address = "Chennai";
e.aadhar = 555577779999;
e.number = 0229; try

{
FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);

out.writeObject(e);

out.close();

fileOut.close();

System.out.printf("Serialized data is saved in /tmp/employee.ser");


}
catch (IOException i)
{
i.printStackTrace();
}
} // class Main
} //class SerializeDemo

Output
Serialized data is saved in /tmp/employee.ser

57
9. Assignment - I
1. Create a Book class that represents a book with attributes title, author, and price.
Implement the Comparable interface in the Book class to compare books based on their prices.

Test Cases:
❑ Create a Book class with private attributes title, author, and price.
❑ Implement the Comparable interface in the Book class.
❑ Override the compareTo() method to compare two Book objects based on their prices.
❑ Write a main() method to test the compareTo() method.

2. Create a WeatherStation class that represents a weather station with attributes temperature,
humidity, and pressure. Implement the Observer interface to enable WeatherDisplay objects to
observe and react to changes in the weather station‘s.
Test Cases:
❑ Create a WeatherStation class that extends the Observable class.
❑ Create a WeatherDisplay class that implements the Observer interface.
❑ In the WeatherStation class, implement the addObserver(), removeObserver(),
and notifyObservers() methods to manage the list of observers.
❑ In the WeatherDisplay class, implement the update() method to react to changes in the
weather station's attributes.
❑ Write a main() method to test the observer pattern.

58
9. Assignment - II
1. Create a FileCopier class that copies a file from a source location to a destination location
using the Byte-stream I/O hierarchy.
Test Cases:
❑ Create a FileCopier class with a copyFile() method that takes two File objects as
parameters: sourceFile and destinationFile.
❑ Use the FileInputStream and FileOutputStream classes to read from the source file
and write
to the destination file, respectively.
❑ Implement the copyFile() method to read bytes from the source file and write them
to the
destination file using a buffer.
❑ Handle any IOException exceptions that may occur during the file copy operation.
❑ Write a main() method to test the FileCopier class.

2. Create a TextFileProcessor class that reads a text file, processes its contents, and writes
the processed text to a new file using the Character Stream Hierarchy.

Test Cases:

❑ Create a TextFileProcessor class with a processFile() method that takes two File objects as
parameters: inputFile and outputFile.

❑ Use the FileReader and FileWriter classes to read from the input file and write to the
output file, respectively.

❑ Implement the processFile() method to read characters from the input file, convert all
uppercase letters to lowercase, and write the processed text to the output file.

❑ Handle any IOException exceptions that may occur during the file processing operation.

❑ Write a main() method to test the TextFileProcessor class.

59
9. Assignment - III
1. Create a StudentRecordManager class that uses a Random Access File to store and retrieve
student records. Each student record consists of a unique ID, name, and grade.

Test Cases:
❑Create a StudentRecord class to represent a student record, with fields for ID, name, and
grade.
❑Create a StudentRecordManager class with the following methods:
❑createFile(): Creates a new Random Access File with a specified filename.
❑addRecord(StudentRecord record): Adds a new student record to the file.
❑getRecord(int id): Retrieves a student record by ID from the file.
❑updateRecord(StudentRecord record): Updates an existing student record in the file.
❑deleteRecord(int id): Deletes a student record by ID from the file.
❑Implement the StudentRecordManager class using the Random Access File class.
❑Handle any IOException exceptions that may occur during file operations.
❑Write a main() method to test the StudentRecordManager class.

2.Create a Banking System class that uses the Console class to provide a console-based interface for
users to perform basic banking operations.

Test Cases:

❑ The BankingSystem class should use the Console class to read user input and display output.

❑ The login() method should use the Console class to read password input securely.

❑ The displayMenu() method should display a menu of available banking operations.

❑ The performOperation() method should perform the selected banking operation based on user
input.

60
9. Assignment - IV
1.Create a Student class that implements the Serializable interface, and a StudentManager class
that uses serialization to store and retrieve student objects.

Test Cases:
❑ The Student class must implement the Serializable interface.

❑ The StudentManager class must use an ObjectOutputStream to serialize the Student object
and write it to a file.

❑ The StudentManager class must use an ObjectInputStream to deserialize a Student object


from a file and return it.

❑ The main() method must test the StudentManager class by creating a Student object, saving
it to a file, and then loading it back from the file.

2. Create a Transaction class that represents a financial transaction, and a TransactionManager


class that uses serialization to store and retrieve Transaction objects.

Test Cases:

❑ The Transaction class must implement the Serializable interface.

❑ The TransactionManager class must use an ObjectOutputStream to serialize the Transaction


object and write it to a file.

❑ The TransactionManager class must use an ObjectInputStream to deserialize a Transaction


object from a file and return it.

❑ The main() method must test the TransactionManager class by creating a Transaction object,
saving it to a file, and then loading it back from the file.

61
9. Assignment - V
1. Create a DateRecord class that represents a date record, and a DateRecordManager class that
uses serialization to store and retrieve DateRecord objects.
Test Cases:

❑ The Student class must implement the Serializable interface.

❑ Create a DateRecord class with the following fields:

❑ date (java.util.Date)

❑ dateFormat (java.lang.String) - the format of the date (e.g. "yyyy-MM-dd", "MM/dd/yyyy", etc.)

❑ timeZone (java.util.TimeZone) - the time zone of the date (e.g. "America/New_York",


"Europe/London", etc.)

❑ Implement the Serializable interface in the DateRecord class.

❑ Create a DateRecordManager class with the following methods:

❑ saveDateRecord(DateRecord dateRecord, String filename): Serializes the DateRecord object and


saves it to a file with the specified filename.

❑ loadDateRecord(String filename): Deserializes a DateRecord object from a file with the specified
filename and returns it.

❑ Implement the saveDateRecord() method using an ObjectOutputStream to serialize the


DateRecord object and write it to a file.

❑ Implement the loadDateRecord() method using an ObjectInputStream to deserialize a DateRecord


object from a file and return it.

❑ Write a main() method to test the DateRecordManager class by creating a DateRecord object,
saving it to a file, and then loading it back from the file.

2. Create a FinancialApplication class that represents a financial application, and a FinancialRecord


class that represents a financial record.
Test Cases:
❑ The Student class must implement the Serializable interface.

❑ Create a FinancialRecord class with the following fields:

❑ date (java.time.LocalDate) - the date of the financial record

❑ amount (java.math.BigDecimal) - the amount of the financial record

❑ currency (java.util.Currency) - the currency of the financial record

❑ description (java.lang.String) - a brief description of the financial record


62
9. Assignment - V
❑ Implement the toString() method to format the date, amount, currency, and description fields
in a human-readable format (e.g. "2022-01-01, USD 100.50, Payment for services").
❑ Create a FinancialApplication class with the following methods:
❑ addRecord(FinancialRecord record): Adds a new FinancialRecord to the application.
❑ getTotalAmount(): Returns the total amount of all FinancialRecord objects in the
application.
❑ getAverageAmount(): Returns the average amount of all FinancialRecord objects in the
application.
❑ getRecordsByCurrency(Currency currency): Returns a list of FinancialRecord objects that
match the specified currency.
❑ getRecordsByDateRange(LocalDate startDate, LocalDate endDate): Returns a list of
FinancialRecord objects that fall within the specified date range.
❑ Implement the addRecord() method to add a new FinancialRecord to a list of records.
❑ Implement the getTotalAmount() method to calculate the total amount of all FinancialRecord
objects using the BigDecimal class.
❑ Implement the getAverageAmount() method to calculate the average amount of all
FinancialRecord objects using the BigDecimal class.
❑ Implement the getRecordsByCurrency() method to filter the list of FinancialRecord objects by
currency.
❑ Implement the getRecordsByDateRange() method to filter the list of FinancialRecord objects by
date range.
❑ Write a main() method to test the FinancialApplication class by creating FinancialRecord
objects, adding them to the application, and displaying the results of the various methods.

63
10. Part A Questions & Answers
1. What are the two main classes in Java's byte-stream I/O hierarchy?
(K2,CO2)
The two main classes in Java's byte-stream I/O hierarchy are InputStream and
OutputStream
2. Which class reads bytes from a file in the byte-stream I/O hierarchy?
(K2,CO2)
The FileInputStream class reads bytes from a file in the byte-stream I/O hierarchy.
3. How does DataOutputStream enhance OutputStream? (K2,CO2)
DataOutputStream enhances OutputStream by allowing the writing of primitive data
types to the output stream.
4. What is the purpose of BufferedInputStream? (K2,CO2)
The purpose of BufferedInputStream is to improve the efficiency of input operations by
buffering the input.
5. What is the function of FilterInputStream? (K2,CO2)
FilterInputStream is a superclass that provides a framework for creating input stream
filters.
6. What class in the byte-stream I/O hierarchy provides functionality for
reading and writing objects? (K2,CO2)
ObjectInputStream and ObjectOutputStream provide functionality for reading and
writing objects.
7. What are the two main classes in Java's character stream I/O hierarchy?
(K2,CO2)
The two main classes in Java's character stream I/O hierarchy are Reader and Writer.
8. How does PrintWriter differ from other writers? (K2,CO2)
PrintWriter provides methods for printing formatted representations of objects to a text-
output stream.
9. Which class reads text from a character-input stream, buffering characters
for efficient reading? (K2,CO2)
BufferedReader class reads text from a character-input stream, buffering characters for
efficient reading.
10. What is the primary use of the RandomAccessFile class? (K2,CO2)
The primary use of the RandomAccessFile class is to allow reading from and writing to a
file at any position. 64
10. Part A Questions & Answers
11. How do you open a RandomAccessFile in read-write mode? (K2,CO2)
Open a RandomAccessFile in read-write mode by using the mode "rw".
12. Which method moves the file pointer to a specific location in
RandomAccessFile? (K2,CO2)
The seek(long pos) method moves the file pointer to a specific location in RandomAccessFile.
13. How can you determine the current position of the file pointer in
RandomAccessFile? (K2,CO2)
The current position of the file pointer is determined using the getFilePointer() method.
14. How do you ensure data written to a RandomAccessFile is flushed to the
storage device? (K2,CO2)
RandomAccessFile does not have an explicit flush method; data is written directly, but
closing the file ensures it is properly saved.
15. What is the primary purpose of the java.io.Console class? (K2,CO2)
The primary purpose of the java.io.Console class is to provide methods to access the console
device, if available.
16. How do you read a line of text from the console using Console? (K2,CO2)
line of text is read from the console using the readLine() method.
17. What method in Console is used to format a string and write it to the console?
(K2,CO2)
The format(String format, Object... args) method is used to format a string and write it to
the console.
18. How do you use Comparable to sort a list of objects? (K2,CO2)
The compareTo method is implemented and then use Collections.sort(list).
19. Which method must be implemented when a class implements the
Comparable interface? (K2,CO2)
The compareTo(T o) method must be implemented.
20. What is the purpose of the Comparable interface? (K2,CO2)
The Comparable interface is used to define the natural ordering of objects.
21. What does the compareTo method return if the current object is less than,
equal to, or greater than the specified object? (K2,CO2)
The compareTo method returns a negative integer, zero, or a positive integer, respectively.

65
10. Part A Questions & Answers
22. Which class in java.util package represents a specific instant in time, with
millisecond precision? (K2,CO2)
The Date class represents a specific instant in time, with millisecond precision.
23. How do you format a Date object to a readable string in Java? (K2,CO2)
You format a Date object to a readable string using SimpleDateFormat.
24. What is the default format of the Date class’s toString() method? (K2,CO2)
The default format of the Date class’s toString() method is typically "EEE MMM dd
HH:mmzzz yyyy".
25. Which class is recommended for more modern date and time handling
instead of Date? (K2,CO1)
The java.time.LocalDateTime class is recommended for more modern date and time
handling.
26. Which class in the java.text package is used to format numbers? (K2,CO2)
The NumberFormat class is used to format numbers.
27. How do you get a month and year from a Date object in Java? (K2,CO2)
int day = calendar.get(Calendar.DATE); // returns the day

int month = calendar.get(Calendar.MONTH) + 1; // month starts from 0

int year = calendar.get(Calendar.YEAR) + 1900; // year starts from 1900

28. What is the difference between Comparable and Comparator interface?


(K2,CO2)

A comparable object is capable of comparing itself with another object. The class itself
must implement the java.lang.Comparable interface to compare its instances. A
comparator object is capable of comparing two different objects. The class is not
comparing its instances, but some other class’s instances. This comparator class
must implement the java.util.Comparator interface.

29. How do you convert a Calendar to Date and vice-versa? (K2,CO2)


Calendar.setTime() and Calendar.getTime() method to convert the Calendar to Date and
vice-versa.

30. How do you copy a Date in Java? (K2,CO2)


It's a simple question to answer. The Date class implements the clone() method, so just call
the date.clone() to create a copy of the Date object in Java.

66
10. Part A Questions & Answers
31. What is serialization? (K2,CO2)

Serialization is a mechanism by which you can save the state of an object by converting it
to a byte stream.

32 Can you customize the serialization process? If yes, then how can one have
control over the serialization process? (K2,CO2)

Yes, it is possible to have control over the serialization process. For this, the class should
implement the Externalizable interface. This interface contains two methods, namely,
readExternal and writeExternal. You should implement these methods and write the logic
for customizing the serialization process.

33. What is the common usage of serialization? (K2,CO2)

Whenever an object is to be sent over the network, objects need to be serialized. Moreover,
if the state of an object is to be saved, objects need to be serialized.

67
11. Part B Questions
1. Explain how the Date and Calendar classes are used to manipulate dates and times in Java.
Provide examples of how to create, modify, and format dates. (K3, CO2)
2. Compare and contrast the Date class with the LocalDateTime class from the java.time package.
Discuss the advantages of using LocalDateTime over Date with examples. (K3, CO2)
3. Describe the Comparable interface and how it is used in Java. Provide an example of a custom
class that implements Comparable and demonstrate how objects of this class can be sorted using
Collections.sort. (K3, CO2)
4. Discuss the differences between the Comparable and Comparator interfaces. Provide examples
to illustrate how each interface can be used to sort a collection of objects. (K3, CO2)
5. Discuss the differences between byte streams and character streams in Java. Provide examples
of classes used for each type of stream and explain scenarios where each type would be
appropriate. (K3, CO2)
6. Explain how the BufferedInputStream and BufferedOutputStream classes work. Provide a Java
example that demonstrates reading from and writing to a file using buffered streams. (K3, CO2)
7. Outline the byte-stream I/O hierarchy in Java, detailing the purpose of key classes such as
InputStream, OutputStream, FileInputStream, and FileOutputStream. Provide examples of their
usage. (K3, CO2)
8. Describe how the DataInputStream and DataOutputStream classes extend the capabilities of
basic byte streams. Provide an example that demonstrates reading and writing primitive data
types using these classes. (K3, CO2)
9. Describe the classes and methods available in Java for working with dates, numbers, and
currency. Provide examples of formatting dates using SimpleDateFormat, formatting numbers
using NumberFormat, and handling currency values. (K3, CO2)
10. Discuss the java.time package introduced in Java 8 for date and time handling. Provide
examples of using LocalDate, LocalTime, LocalDateTime, DateTimeFormatter, and Period to
manipulate and format date and time values. (K3, CO2)
11. Discuss the limitations of the Calendar class and explain how the java.time package
addresses these limitations. Provide examples comparing date manipulation using Calendar and
LocalDate. (K3, CO2)

68
11. Part B Questions
12. Explain the importance of the NumberFormat and Currency classes in Java. How can
they be used to format numbers and currencies in a locale-sensitive way? (K3, CO2)
13. Describe the process of object serialization in Java. What are the key interfaces and
methods involved? Explain when and why serialization is useful. (K3, CO2)
14. Provide a detailed explanation of dates in Java and discuss about date class methods
and constructors(K3, CO2)
15. Compare and contrast the byte-stream and character-stream I/O hierarchies in Java
with suitable examples? (K3, CO2)
16. Explain between the different types of streams in Java (K3, CO2)
17. Define the Comparable interface and explain how it can be used to impose a natural
ordering on objects. Provide a code to illustrate this concept. (K3, CO2)
18. Explain the role of the Comparator interface in Java and provide an example of how it
can be used to sort objects in a custom order. (K3, CO2)

69
12. Supportive Online Certifications

1. Java Programming: Complete Beginner to Advanced https://www.udemy.com/course/java-


programming-complete-beginner-to- advanced/(Paid)

2. Java DeveloperCertification (Infosys Springboard):


https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_01319338454
0020736264_shared/overview

3. Java Programming Masterclass updated to Java 17: https://www.udemy.com/course/java-


the-complete-java-developer-course/ (Paid)

4. Programming in Java: https://nptel.ac.in/courses/106/105/106105191/ (Paid)

5. Java Learning Subscription: https://education.oracle.com/java-se-8-


fundamentals/courP_3348 (Paid)

70
13. Real Time Applications

❖ Desktop GUI Programs

❖ Mobile Applications

❖ Artificial intelligence

❖ Web based Applications

❖ Big data technology

❖ Gaming Applications

❖ Business Applications

❖ Embedded Systems

❖ Cloud based Applications

❖ Scientific Applications

❖ Distributed Applications

❖ Web servers and Application servers

❖ Software Tools

71
14. Contents Beyond the Syllabus
❖ java.util.Random class
The java.util.Random class instance is used to generate a stream of pseudorandom
numbers.
Following are the important points about Random:
❑ The class uses a 48-bit seed, which is modified using a linear congruential formula.
❑ The algorithms implemented by class Random use a protected utility method that on each
invocation can supply up to 32 pseudorandomly generated bits
Constructors:
Random(): Creates a Random object. Random(long): This creates a new random number.
Here generator use a single long seed.
Class Methods & Description:
protected int next(int bits): This method generates the next pseudorandom
number.
booleannextBoolean(): This method returns the next pseudorandom, uniformly
distributed boolean value from this random number generator's sequence.
void nextBytes(byte[] bytes): This method generates random bytes and places them
into a user-supplied byte array.
double nextDouble():This method returns the next pseudorandom, uniformly
distributed double value between 0.0 and 1.0 from this random number generator's
sequence.
float nextFloat():This method returns the next pseudorandom, uniformly distributed float
value between 0.0 and 1.0 from this random number generator's sequence.
double nextGaussian():This method returns the next pseudorandom, Gaussian
("normally") distributed double value with mean 0.0 and standard deviation 1.0 from
this random number generator's sequence.
int nextInt():This method returns the next pseudorandom, uniformly distributed int value
from this random number generator's sequence.
int nextInt(int n):This method returns a pseudorandom, uniformly distributed int value
between 0 (inclusive) and the specified value (exclusive), drawn from this random number
generator's sequence.
long nextLong():This method returns the next pseudorandom, uniformly distributed long
value from this random number generator's sequence.
void setSeed(long seed):This method sets the seed of this random
number generator using a single long seed. 72
15. Assessment Schedule
Tentative schedule for the Assessment During 2024-2025 Odd Semester

S. Name of the
Start Date End Date Portion
No. Assessment

As Per Academic As Per Academic


1 Unit Test 1 Unit 1
Schedule Schedule

As Per Academic As Per Academic


2 FIAT Unit 1 & 2
Schedule Schedule
As Per Academic As Per Academic
3 Unit Test 2 Unit 3
Schedule Schedule
As Per Academic As Per Academic
4 SIAT Unit 3 & 4
Schedule Schedule
As Per Academic As Per Academic
5 Revision 1 Unit 5, 1 & 2
Schedule Schedule
As Per Academic As Per Academic
6 Revision 2 Unit 3 & 4
Schedule Schedule
As Per Academic As Per Academic
7 Model All 5 Units
Schedule Schedule

73
16. Prescribed Text Books
&
Reference Books
TEXT BOOK:
1. Cay S. Horstmann, "Core Java Volume I--Fundamentals,"
12th Edition, 2019.
2. Joshua Bloch, "Effective Java," 3rd Edition, 2018.
3. Raoul-Gabriel Urma, "Java 8 in Action: Lambdas, Streams,
and Functional-Style Programming," 1st Edition, 2014.
4. Herbert Schildt, "Java: The Complete Reference," 11th
Edition, 2018.
5. Alan Mycroft and Martin Odersky, "Programming in Scala,"
4th Edition, 2020.
REFERENCES:
1. Bruce Eckel, "Thinking in Java," 4th Edition, 2006.
2. Herbert Schildt, "Java: A Beginner's Guide," 8th Edition,
2019.
3. Richard Warburton, "Java 8 Lambdas: Pragmatic Functional
Programming," 1st Edition, 2014.

74
17. Mini Project – I
Calendar Event Manager
Create a Java program that allows users to manage a list of events with dates. The program
should enable users to add events, remove events, and list all events in chronological order.
The events should be stored in a file, and the program should be able to read from and write to
this file.
Requirements:
Add Event: Allow the user to add an event with a date.
Remove Event: Allow the user to remove an event by specifying the date.
List Events: List all events in chronological order.
File Persistence: Store events in a file and read from it when the program starts.
Date Validation: Validate the date format (e.g., YYYY-MM-DD).
Steps:
Create a class Event to store the event details (date and description).
Create methods to add, remove, and list events.
Store the events in a file named events.txt.
Ensure that events are listed in chronological order.
Test Case:
Create a text file events.txt with the following content:
Add an event: 2024-07-04|Independence Day Celebration
Remove an event: 2024-06-15
List events
Choose an option: (1) Add Event (2) Remove Event (3) List Events (4) Exit
1
Enter the event date (YYYY-MM-DD):
2024-07-04
Enter the event description:
Independence Day Celebration
Event added successfully.
Choose an option: (1) Add Event (2) Remove Event (3) List Events (4) Exit
2
Enter the event date to remove (YYYY-MM-DD):
2024-06-15
Event removed successfully.
Choose an option: (1) Add Event (2) Remove Event (3) List Events (4) Exit
3
Events:
2024-06-01: Conference at City Hall
2024-07-04: Independence Day Celebration
Choose an option: (1) Add Event (2) Remove Event (3) List Events (4) Exit
Check events.txt after exiting the program:
2024-06-01|Conference at City Hall
2024-07-04|Independence Day Celebration
17. Mini Project – II
Stream-Based File Processor

Create a Java program that processes a text file using Java Streams. The program should read a text
file, filter out specific words, convert the remaining words to uppercase, sort them alphabetically, and
write the result to a new output file.

Requirements

Input File: The program should read from an input file specified as a command-line argument.

Output File: The program should write the processed words to an output file named
processed_output.txt.

Word Filtering: Filter out common English stopwords (e.g., "the", "is", "in", etc.).

Case Conversion: Convert all remaining words to uppercase.

Sorting: Sort the words alphabetically before writing to the output file.

Steps:

1. Read the input file specified as a command-line argument.

2. Filter out common stopwords.

3. Convert remaining words to uppercase.

4. Sort the words alphabetically.

5. Write the result to processed_output.txt.

Test Case:

1. Create a text file input.txt with the following content:

The quick brown fox jumps over the lazy dog.

This is a test of the emergency broadcast system.

Expected processed_output.txt content:


• A
• BROADCAST
• BROWN
• DOG
• EMERGENCY
• FOX
• JUMPS
• LAZY
• OVER
• QUICK
• SYSTEM
• TEST
• THIS
17. Mini Project – III
Contact Manager with Serialization

Create a Java program to manage a list of contacts. Each contact has a name, phone number,
and email address. The program should allow users to add, remove, list, and save contacts.
Contacts should be serialized to a file and deserialized when the program starts.
Requirements:
1.Contact Class: A class to represent a contact with name, phone number, and email address.
2.Serialization: Use Java's serialization mechanism to save and load the list of contacts from a
file.
3.Add Contact: Allow the user to add a new contact.
4.Remove Contact: Allow the user to remove a contact by name.
5.List Contacts: List all contacts.
6.File Persistence: Save the contacts to a file named contacts.ser.
Steps:
1.Create a class Contact that implements Serializable.
2.Create methods to add, remove, and list contacts.
3.Use serialization to save and load contacts from a file.

Test Case:
•Add a contact: John Doe, 123-456-7890, [email protected]
•Add another contact: Jane Smith, 234-567-8901, [email protected]
•List contacts.

Expected Console Output after adding and listing contacts:


Choose an option: (1) Add Contact (2) Remove Contact (3) List Contacts (4) Exit
1
Enter name:
John Doe
Enter phone number:
123-456-7890
Enter email:
[email protected]
Contact added successfully.
Choose an option: (1) Add Contact (2) Remove Contact (3) List Contacts (4) Exit
1
Enter name:
Jane Smith
Enter phone number:
234-567-8901
Enter email:
[email protected]
Contact added successfully.
Choose an option: (1) Add Contact (2) Remove Contact (3) List Contacts (4) Exit
3
Contacts:
Name: John Doe, Phone: 123-456-7890, Email: [email protected]
Name: Jane Smith, Phone: 234-567-8901, Email: [email protected]
Remove a contact: John Doe and list contacts:
17. Mini Project – IV
Internationalized Expense Tracker

Create a Java program to manage expenses with support for date, number, and currency
formatting based on locale. The program should allow users to add expenses, display
expenses with appropriate formatting, and save/load expenses to/from a file.
Requirements:
1.Expense Class: A class to represent an expense with date, description, and amount.
2.Date Formatting: Display dates in a locale-specific format.
3.Number Formatting: Display amounts in a locale-specific format.
4.Currency Formatting: Display amounts with appropriate currency symbols.
5.File Persistence: Save and load expenses to/from a file named expenses.ser.
6.Locale Selection: Allow the user to select a locale for formatting.

Steps:
1.Create a class Expense that implements Serializable.
2.Create methods to add, remove, and list expenses.
3.Use locale-specific date, number, and currency formatting.
4.Allow users to select a locale for displaying expenses.
5.Save and load expenses from a file.

Test Case:

Perform the following operations:


•Add an expense: 2024-06-21, Groceries, 120.50
•Add another expense: 2024-06-22, Rent, 1500.00
•List expenses.
Expected Console Output after adding and listing expenses:
Choose an option: (1) Add Expense (2) Remove Expense (3) List Expenses (4) Set Locale
(5) Exit
1
Enter date (YYYY-MM-DD):
2024-06-21
Enter description:
Groceries
Enter amount:
120.50
Expense added successfully.
Choose an option: (1) Add Expense (2) Remove Expense (3) List Expenses (4) Set Locale
(5) Exit
1
Enter date (YYYY-MM-DD):
2024-06-22
Enter description:
Rent
Enter amount:
1500.00
Expense added successfully.
Choose an option: (1) Add Expense (2) Remove Expense (3) List Expenses (4) Set Locale
(5) Exit
3
Expenses:
Date: 2024-06-21, Description: Groceries, Amount: $120.50
Date: 2024-06-22, Description: Rent, Amount:
78 $1,500.00
17. Mini Project – IV
Change locale to French (France):
Set locale: fr_FR
List expenses.

Choose an option: (1) Add Expense (2) Remove Expense (3) List Expenses (4) Set
Locale (5) Exit
4
Enter locale (e.g., en_US, fr_FR):
fr_FR
Locale set to French (France)
Choose an option: (1) Add Expense (2) Remove Expense (3) List Expenses (4) Set
Locale (5) Exit
3
Expenses:
Date: 2024-06-21, Description: Groceries, Amount: 120,50 €
Date: 2024-06-22, Description: Rent, Amount: 1 500,00 €
17. Mini Project – V
Student Grade Manager using Comparable Interface

Create a Java program to manage a list of students with their grades. The program should
allow users to add, remove, list, and sort students based on their grades using the
Comparable interface.
Requirements:
Student Class: A class to represent a student with name and grade, implementing the
Comparable interface.
Add Student: Allow the user to add a new student.
Remove Student: Allow the user to remove a student by name.
List Students: List all students sorted by their grades.
File Persistence: Save and load students to/from a file named students.ser.
Steps:
1.Create a class Student that implements Serializable and Comparable<Student>.
2.Create methods to add, remove, and list students.
3.Use the Comparable interface to sort students by their grades.
4.Save and load students from a file.
Test Case:
Perform the following operations:
•Add a student: Alice, 85.5
•Add another student: Bob, 92.0
•List students.
Expected Console Output after adding and listing students:
Choose an option: (1) Add Student (2) Remove Student (3) List Students (4) Exit
1
Enter name:
Alice
Enter grade:
85.5
Student added successfully.
Choose an option: (1) Add Student (2) Remove Student (3) List Students (4) Exit
1
Enter name:
Bob
Enter grade:
92.0
Student added successfully.
Choose an option: (1) Add Student (2) Remove Student (3) List Students (4) Exit
3
Students:
Name: Bob, Grade: 92.0
Name: Alice, Grade: 85.5

Remove a student: Alice and list students:


Choose an option: (1) Add Student (2) Remove Student (3) List Students (4) Exit
2
Enter the name of the student to remove:
Alice
Student removed successfully.
Choose an option: (1) Add Student (2) Remove Student (3) List Students (4) Exit
3 80
Students:
Name: Bob, Grade: 92.0
Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document through
email in error, please notify the system manager. This document contains
proprietary information and is intended only to the respective group / learning
community as intended. If you are not the addressee you should not disseminate,
distribute, or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system.
If you are not the intended recipient you are notified that disclosing, copying,
distributing, or taking any action in reliance on the contents of this information is strictly
prohibited.

75

You might also like