CS20004:
Object Oriented
Programming using
Java
Lec-22
In this Discussion . . .
○ String class
■ String conversion and toString()
■ Data Conversion using valueOf()
○ StringBuffer
■ StringBuffer Constructor
■ StringBuffer Operations
○ Java I/O Stream
■ I/O Basics
■ Stream
• Byte stream
• Character stream
○ References
String conversion and toString()
● If we want to represent any object as a string, toString() is used. This
method returns the string representation of the object.
● If we print any object, java compiler internally invokes toString() method on
the object. Overriding toString() method returns the desired output.
● By overriding the toString() method of the Object class, we can return
values of the object, so we don’t need to write much code
String conversion and toString()
● By overriding the toString() method of the Object class, we can return
values of the object, so we don’t need to write much code
public String toString()
{
return "Dimensions: "+ height + ", "+ width;
}
Data Conversion using valueOf()
● It converts different types of values into string. It is a static method that is
overloaded within String for all built-in types
Example Syntaxes-
Example usage-
public static String valueOf(boolean b)
int data=30;
public static String valueOf(char c)
String str=[Link](data);
public static String valueOf(int i)
[Link](str+40);
public static String valueOf(double d)
class Tostrvalof
{
public static void main(String args[])
{
String str = null;
Integer x = 45;
[Link](str+[Link](x));
[Link]([Link]());
[Link]([Link](12));
}
}
class Tostrvalof
{
public static void main(String args[])
{
String str = null;
Integer x = 45;
[Link](str+[Link](x));
[Link]([Link]());
[Link]([Link](12));
}
}
StringBuffer
● StringBuffer is a peer class of String that provides much of the functionality
of Strings
● String is immutable. StringBuffer is mutable. It represents growable and
writable character sequence
● StringBuffer may have characters and substring inserted in the middle or
appended to the end
● It will automatically grow to make room for such additions
StringBuffer Constructor
● Creating an empty StringBuffer
StringBuffer sb = new StringBuffer();
● Creating size-defined StringBuffer
StringBuffer sb = new StringBuffer(int size);
Ex- StringBuffer sb = new StringBuffer(50);
● Creating String object - based StringBuffer
StringBuffer sb = new StringBuffer(String str);
Ex- StringBuffer sb = new StringBuffer("Hello");
StringBuffer Functions
○ length(): finds the current length
StringBuffer sb=new StringBuffer("Hello");
int len=[Link]();
○ capacity(): finds the total allocated capacity
StringBuffer sb=new StringBuffer("Hello");
int cap=[Link]();
○ ensureCapacity(): sets the size of the buffer after a StringBuffer has
been constructed
void ensureCapacity(int capacity)
Where, capacity specifies the minimum size of the buffer
StringBuffer Functions
○ setLength(): sets the length of the buffer within a StringBuffer object
void setLength(int len) len specifies the length Ex- [Link](4);
of the buffer
○ charAt(): obtains the value of a single character
pos specifies the index
char charAt(int pos)
of the character being Ex- StringBuffer sb=new StringBuffer("Hello");
obtained [Link](Character: "+[Link](2));
○ setCharAt(): sets the value of a character
pos specifies the index
void setCharAt(int pos, char ch) of the character being Ex- StringBuffer sb=new StringBuffer("Hello");
obtained [Link](2,'i');
StringBuffer Functions
○ getChars(): copies a substring of a StringBuffer into an array
void getChars (int begin, int end, char[] target, int targetbeg)
○ append(): concatenates the string representation of any type of data to
the end of the invoking StringBuffer object
StringBuffer append(Object ob) String s=null;
StringBuffer append(String str) [Link]() is called int a=100;
StringBuffer append(int num) for each parameter to StringBuffer sb=new StringBuffer (40);
obtain its string s=[Link](ä=").append(a).append("!").
representation toString();
StringBuffer Functions
○ insert(): inserts one string into another
StringBuffer insert(int index, String str) Ex-
index specifies the index
StringBuffer insert(int index, char ch) StringBuffer sb=new StringBuffer("Hello ");
at which the string will
StringBuffer insert(int index, Object ob) [Link](7,"ok");
be inserted
○ reverse(): reverses the characters in a StringBuffer object
StringBuffer reverse()
Ex-
StringBuffer sb=new StringBuffer("Hello");
[Link]();
StringBuffer Functions
○ replace(): replaces one set of characters with another set
StringBuffer replace(int start, int end, String str)
Ex-
StringBuffer sb=new StringBuffer("Bhubaneswar");
[Link](3,4,"va");
○ substring(): returns a portion of a StringBuffer
String substring(int start)
String substring(int start, int end)
○ delete(): deletes a sequence of characters
StringBuffer delete(int start, int end)
Ex- [Link](2,4);
StringBuffer Functions
○ deleteCharAt(): deletes the character at the pos index
StringBuffer deleteCharAt(int pos)
Ex- [Link](0);
○ indexOf(String str): int i = [Link](two");
○ indexOf(String str, int start): int i = [Link](two", 4);
○ lastIndexOf(String str): int i = [Link](two");
StringBuffer Functions
○ lastIndexOf(String str, int start): int i = [Link](two",4);
○ trimToSize(int size): [Link](10);
class Stringbufexp
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");
[Link](sb);
[Link](1,"Java");
[Link](sb);
[Link](1,3,"Java");
[Link](sb);
[Link](1,3);
[Link](sb);
[Link]();
[Link](sb);//prints olleH
}
}
class Stringbufexp
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");
[Link](sb);
[Link](1,"Java");
[Link](sb);
[Link](1,3,"Java");
[Link](sb);
[Link](1,3);
[Link](sb);
[Link]();
[Link](sb);
}
}
Java I/O
● Java I/O (Input and Output) is used to process the input and produce the
output based on the input.
● Java uses the concept of stream to make I/O operation fast.
● The [Link] package contains all the classes required for input and output
operations.
● File handling in Java can be performed using the Java I/O API.
● Two important methods are read() and write().
Stream
● A stream is a sequence of data. In Java, a stream is composed of bytes.
It's called a stream because it is like a stream of water that continues to
flows.
● A stream is an abstraction that either produces or consumes information. It
is linked to a physical device by the Java IO system.
● [Link] package defines a class called System, which encapsulates
several aspects of the run-time environment.
Stream
● In Java, 3 streams are created automatically for the programmers. All
these streams are attached with the console:
○ [Link]:
■ It refers to the standard output stream
○ [Link]:
■ It refers to the standard input stream
○ [Link]:
■ It refers to the standard error stream
● [Link] is an object of type InputStream. [Link] and [Link]
are objects of type PrintStream
Stream Examples
○ [Link]:
■ It refers to the standard output stream
○ [Link]:
■ It refers to the standard input stream
○ [Link]:
■ It refers to the standard error stream
● A sample code to print output and an error ● A sample code to get input from
message to the console: console.
○ [Link]("simple message"); ○ int i=[Link]();//returns
ASCII code of 1st character
○ [Link]("error message");
○ [Link]((char)i);//will
print the character
Byte stream Classes
● ByteStream classes are used to read bytes from the input stream and
write bytes to the output stream.
● In other words, we can say that ByteStream classes read/write the data of
8-bits.
● We can store video, audio, characters, etc., by using ByteStream classes.
● To use stream classes, you must import [Link] package.
Types of Byte stream Classes
Byte stream Classes
InputStream OutputStream
It is an abstract class. It is the superclass It is an abstract class. It is the superclass
of all classes representing an input of all classes representing an output
stream of bytes stream of bytes
Byte Stream Classes
InputStream Class:
● The InputStream class provides methods to read bytes from a file,
console or memory.
● It is an abstract class and can't be instantiated.
● However, various classes inherit the InputStream class and override its
methods.
● The subclasses of InputStream class are presented in the next slide.
Byte Stream Classes
InputStream Class:
● The subclasses of InputStream class are:
Byte Stream Classes
InputStream Class:
● The InputStream class contains various methods to read the data from
an input stream.
● These methods are overridden by the classes that inherit the
InputStream class. However, the methods are given in the following
table.
Byte Stream Classes
OutputStream Class:
● The OutputStream is an abstract class that is used to write 8-bit bytes
to the stream.
● It is the superclass of all the output stream classes.
● This class can't be instantiated; however, it is inherited by various
subclasses that are given in the following slide.
Byte Stream Classes
OutputStream Class:
● The subclasses of InputStream class are:
Byte Stream Classes
OutputStream Class:
● The OutputStream class provides various methods to write bytes to the
output streams.
● The methods are given in the following table.
Byte Stream Classes Example
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Bytestreamexp
{
public static void main(String[] args) throws IOException
{
byte content[] = "Welcome to the topic of Byte Streams in Java".getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
[Link](content);
File newFile = new File("/home/iitp/Desktop/Web-Technology/class/Java-IO/[Link]");
FileOutputStream outputStream = new FileOutputStream(newFile);
[Link](content);
}
}
Byte Stream Classes Example
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link]; ● The example uses the
public class Bytestreamexp
ByteArrayInputStream to
{
public static void main(String[] args) throws IOException
create an input stream from a
{
byte content[] = "Welcome to the topic of Byte
byte array "content".
Streams in Java".getBytes(); ● We use the read() method to
ByteArrayInputStream inputStream = new
ByteArrayInputStream(content); read the content from an input
[Link](content); stream.
File newFile = new ● We have also used the write()
File("/home/iitp/Desktop/Web-Technology/class/Java-IO/MyNe
[Link]");
method on a FileOutputStream
FileOutputStream outputStream = new
FileOutputStream(newFile);
object to write the byte array
}
[Link](content); content in the file.
}
Byte Stream Classes Example
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Bytestreamexp
{
public static void main(String[] args) throws IOException
{
byte content[] = "Welcome to the topic of Byte
Streams in Java".getBytes();
ByteArrayInputStream inputStream = new
ByteArrayInputStream(content);
[Link](content);
File newFile = new
File("/home/iitp/Desktop/Web-Technology/class/Java-IO/MyNe
[Link]");
FileOutputStream outputStream = new
FileOutputStream(newFile);
[Link](content);
}
}
CharacterStream Classes
● The [Link] package provides CharacterStream classes to overcome the
limitations of ByteStream classes, which can only handle the 8-bit bytes
and is not compatible to work directly with the Unicode characters.
● CharacterStream classes are used to work with 16-bit Unicode characters.
They can perform operations on characters, char arrays and Strings.
● However, the CharacterStream classes are mainly used to read characters
from the source and write them to the destination.
Types of CharacterStream Classes
CharacterStream
Classes
Reader Writer
It is the abstract class that describes It is the abstract class that describes
character stream input character stream output
CharacterStream Classes
Reader Class:
● Reader class is used to read the 16-bit characters from the input stream.
● However, it is an abstract class and can't be instantiated, but there are
various subclasses that inherit the Reader class and override the methods
of the Reader class.
● All methods of the Reader class throw an IOException.
CharacterStream Classes
Reader Class:
● The subclasses of the Reader class include:
CharacterStream Classes
Reader Class:
● Next, the Reader class methods include:
CharacterStream Classes
Writer Class:
● Writer class is used to write 16-bit Unicode characters to the output
stream.
● The methods of the Writer class generate IOException.
● Like Reader class, Writer class is also an abstract class that cannot be
instantiated; therefore, the subclasses of the Writer class are used to write
the characters onto the output stream. .
CharacterStream Classes
Writer Class:
● The subclasses of the Writer class include:
CharacterStream Classes
Writer Class:
● Next, to write the characters to the output stream, the Writer class
provides various methods including:
References
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
thod
6. [Link]
7. [Link]
8. [Link]
by%20Java%20I%2FO%20API.
9.