0% found this document useful (0 votes)
19 views

Java unit 2

Uploaded by

jothishwar007
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java unit 2

Uploaded by

jothishwar007
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

II

Unit
Topics

 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.


Java Comparable
and
Comparator
Comparable Interface:

Comparable interface is mainly used to sort the arrays (or lists)


of custom objects. Lists (and arrays) of objects that implement Comparable
interface can be sorted automatically by Collections.sort (and Arrays.sort).

 The Comparable interface is used to define the


natural ordering of objects. It allows for sorting
objects based on a single property.

 To implement the Comparable interface, a


class must override the compareTo method

 Implementing the Comparable interface


provides a natural ordering for the class. This
is useful when you want to define a default
sorting mechanism for your objects.
Comparable Interface:
Comparable Interface:

Implement the `Comparable` interface in the `Video` class so that videos can be
compared based on their number of views. The natural ordering should be from the
highest number of views to the lowest.
Comparator Interface:

Comparable interface is mainly used to sort the arrays (or lists) of custom objects. Lists
(and arrays) of objects that implement Comparable interface can be sorted automatically
by Collections.sort (and Arrays.sort).
Purpose: The Comparator interface is used to define multiple different orders for
objects of a class. It is useful when you want to sort objects in various ways.
Method: It has a single method: compare(T o1, T o2)
Signature: int compare(T o1, T o2);This method compares two specified objects and
returns
 A negative integer if the first object is less than the second object.
 Zero if the first object is equal to the second object.
 A positive integer if the first object is greater than the second object.
 Implementation:
 Implement this interface in a separate class or use lambda expressions or method references if
you’re using Java 8 or later.
Comparator Interface:
Student Marks Sorter
Comparator Interface:
Observer Interface

• The Observer design pattern is a behavioral design pattern that defines a


one-to-many dependency between objects.
• This means that when one object (the subject) changes its state, all its
dependent objects (the observers) are notified and updated
automatically. This pattern is widely used in various applications,
including GUI systems and event handling.
• In Java, the Observer pattern is implemented through the Observer
interface and the Observable class, though starting from Java 9,
Observable and Observer have been deprecated.

Observable Class: The Observable class represents the object that


maintains a list of observers.

• It has methods to add, remove, and notify observers. It also has a


mechanism to mark the state of the object as changed.
Streams
and
Hierarchy
STREAMS

 A stream is a sequence of elements from a source that


supports
aggregate operations.
 Unlike collections, streams do not store elements; instead, they
convey elements from a source (such as a collection, array, or
I/O channel) through a pipeline of computational operations.

Types of Streams:
There are two main categories of streams in Java for I/O
operations

 Byte Stream
 Character Stream
I/O OPERATIONS

 Input and Output (I/O) operations allow data


exchange between the program and external sources like
files, networks, or the console.

 Efficiently manage data flow to and from Java applications.

 Uses the concept of stream to make the I/O operations fast


STREAMS:
BYTE STREAM

 Byte streams in Java are designed to provide a convenient way for handling the input
and output of bytes (i.e., units of 8-bits data). We use them for reading or writing to
binary data I/O.
 A byte stream is suitable for any kind of file, however not quite appropriate for text files
 Byte streams in Java operate on binary data, allowing you to read and write data as
individual bytes. They are commonly used for working with non-textual data such as
images, audio files, or serialized objects.
 Types of byte streams in Java include
 FileInputStream and FileOutputStream for reading and writing bytes to files,
 BufferedInputStream and BufferedOutputStream for efficient buffered operations,
and
 DataInputStream and DataOutputStream for handling different data types.
 There are many classes related to byte streams but the most frequently used classes
are ,


BYTE STREAM
INPUT/OUTOUT STREAMS:
INPUT/OUTOUT STREAMS:
CHARACTER STREAM

 Character streams in Java are used to perform input and output


for 16-bit Unicode. A character stream will read a file character
by character.
 A Character stream are appropriate for text files
 There are many classes related to characterstreams but the
most frequently used classes are ,

 FileReader (Reads characters from a file


using the platform's default character encoding.)
 FileWriter (Writes characters to a
file using the platform's default
character encoding.)
CHARACTER STREAM
READER/WRITER CLASS
Character Stream program
Finding minimum element in an array
Buffered Reader

• BufferedReader is a Java class that reads text from the


input stream. It buffers the characters so that it can get the
efficient reading of characters, arrays, etc.
• It inherits the reader class and makes the code efficient
since we can read the data line-by-line with the readline()
method.
Buffered Reader
Buffered reader
Buffered reader
Buffered Writer Class:
 The BufferedWriter class in Java is used to provide efficient writing of text to a character output
stream. This is achieved by buffering the characters, which means that it reduces the number of
interactions with the underlying I/O device, resulting in improved performance, especially when
writing large amounts of data.

 BufferedWriter maintains an internal buffer to store characters before writing them to the actual
output stream. This minimizes the number of I/O operations, making the writing process faster.

 Performance: By reducing the number of I/O operations, BufferedWriter can significantly improve
performance, especially when writing large amounts of data.

 Convenience: Provides methods like newLine() to easily write platform-specific line separators.
Count the number of characters
in the file
RANDOM ACCESS FILE CLASS

 The RandomAccessFile class in Java provides functionality for reading


from and writing to files with random access.

 Unlike standard streams that offer sequential access,


RandomAccessFile allows you to move around the file and perform
operations at any specific position.

 This class allows the random movement of the file pointers. The file
pointer can
be moved back and forth.
FUNCTIONALITIES OF RANDOM ACCESS FILE CLASS

 Reading and Writing: You can read bytes of data from any position
in the file or write data at any position, overwriting existing data if
necessary.

 File Pointer: A file pointer acts like a cursor within the file, keeping
track of the current position for read/write operations. You can
manipulate the file pointer to move around the file.

 Modes: The class allows opening files in two modes:

 "r" (read-only) : Opens the file for reading only.


 "rw" (read-write): Opens the file for both reading and writing.
The java.io.Console Class

The Java.io.Console class provides methods to access the character-


based console device, if any, associated with the current Java virtual
machine.
Key Methods:
 System.console(): a reference to the Console object if
Returns otherwise null. available,
 reader(): Returns a BufferedReader object for reading
text input from the
console.
 readLine(): Reads a line of text from the console and returns it as a
String.
 password(): Reads a password from the console without echoing
characters as they are typed, enhancing security for sensitive
information.
 writer(): Returns a PrintWriter object for formatted output to the console.
Serialization
Dates , Numbers,
and
Currency
SERIALIZATI
ON

 Serialization is a process of converting an object into a sequence of


bytes which can be persisted to a disk or database or can be sent
through streams. The reverse process of creating object from
sequence of bytes is called deserialization

 The java object is serializable if its class or any of its subclasses


implements java.io.serializable or its sub interface
java.io.externalizable interface.

 The entire process is JVM independent, meaning an object can be


serialize on
platform and deserialize on an entirely different platform.

 Classes : ObjectInputStream and ObjectOutputStream or High-level


Streams that contain the methods for serializing and deserializing the
How to Serialize an
Object?

Since you now know what serialization in Java is, and all the relevant
points, let’s dwelve deep into how to serialize an object. You must use the
writeObject() method of the ObjectOutputStream class for serialization and
readObject() method of the InputObjectStream class for deserialization
purpose.
DATES ,CALENDAR, NUMBERS AND CURRENCIES IN JAVA

Date Handling: Java provides robust libraries for manipulating dates


and times through the packages

Key Classes:
 java.util.Date: Older class representing a specific point in time
(deprecated in Java 9 and later).
 java.time.LocalDate: Newer class representing a date
without time (recommended).
 java.time.LocalDateTime: Class representing a date and
time with
optional nanoseconds.
 java.time.ZonedDateTime: Class representing a date and time
with time zone information.
DATES ,CALENDAR, NUMBERS AND CURRENCIES
IN JAVA
Numbers:

Java provides robust libraries for manipulating Numbers through


the packages

Key Class of Number:


java.text.NumberFormat:

 Formats numbers, including currency values.


 Locale-sensitive and can format numbers in a way that is
appropriate for a
specific locale.
Date Class:

Java SimpleDateFormat
• 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.
• Notice that formatting means converting date to string and parsing means converting string to
date.

Constructors of the Class SimpleDateFormat


• Simpledateformat(string pattern_args): instantiates the simpledateformat class using the provided
pattern - pattern_args, default date format symbols for the default FORMAT locale.
• Simpledateformat(string pattern_args, locale locale_args): instantiates the simpledateformat class
using the provided pattern - pattern_args. For the provided FORMAT locale, the default date format
symbols are - locale_args.
• Simpledateformat(string pattern_args, dateformatsymbols formatsymbols): instantiates the
simpledateformat class and using the provided pattern - pattern_args and the date formatsymbols.
SimpleDateFormat:

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 : 01/08/2024
SimpleDateFormat(String pattern_args):
SimpleDateFormat(String pattern_args, Locale
locale_args):
Calendar Class:

Calendar methods:

• The Calendar is a built-in abstract class in java used to convert date between a specific
instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. The Calendar
class is available inside the java.util package.

• The Calendar class implements Serializable. Cloneable and Comparable interface.

 As the Calendar class is an abstract class, we cannot create an object using it.

 We will use the static method, Calendar.getInstance() to instantiate and


implement a sub-class.
Calendar Class:
Calendar Class:

You might also like