[go: up one dir, main page]

0% found this document useful (0 votes)
3 views39 pages

2 - IO - File Handling-STRING HANDLING (Unit-2)

The document provides an overview of I/O and file handling in Java, detailing the concepts of streams, including byte and character streams, and their associated classes for input and output operations. It also covers Java serialization and deserialization, explaining the use of the Serializable interface and the transient keyword. Additionally, it discusses string handling in Java, including string creation, immutability, and various string methods for manipulation and comparison.

Uploaded by

rajatmaurya7906
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)
3 views39 pages

2 - IO - File Handling-STRING HANDLING (Unit-2)

The document provides an overview of I/O and file handling in Java, detailing the concepts of streams, including byte and character streams, and their associated classes for input and output operations. It also covers Java serialization and deserialization, explaining the use of the Serializable interface and the transient keyword. Additionally, it discusses string handling in Java, including string creation, immutability, and various string methods for manipulation and comparison.

Uploaded by

rajatmaurya7906
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/ 39

Contents

 I/O and File Handling


I/O (Input and Output)

• It is used to process the input and produce the output.


• It uses the concept of a stream to make I/O operation fast.
• Stream is encapsulated under java.io package that contains all the classes
required for input and output operations.
Stream

• It's called a stream because it is like a stream of water that continues to flow.
• Streams are sequence of data(composed of bytes) that are read from source &
written to destination.
• An input stream is used to read data from source & an output stream is write
data to the destination.

• There are 3 streams created for us automatically that are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Code to print output and an error message to the console :

System.out.println("simple message"); class HelloWorld {


System.err.println("error message"); public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
For example, in our first Hello World example, we have
used System.out to print a string. Here, the System.out is
a type of output stream.

code to get input from console :

int i=System.in.read(); //returns ASCII code of 1st


character
System.out.println((char)i); //will print the character
Java defines two types of streams. They are,
1.Byte Stream : a convenient means for handling input and output of byte.
2.Character Stream : a convenient means for handling input and output of
characters.

(1) Byte Stream Classes :

• defined by using two abstract class at the top of hierarchy, they are InputStream and
OutputStream.

• byte stream classification

• These two abstract classes have several concrete classes that handle various devices
such as disk files, network connection etc.
Some important Byte stream classes

Stream class Description


BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file


FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are :
read() : reads byte of data.
write() : Writes byte of data.
(2) Character Stream Classes
• It is also defined by using two abstract class at the top of hierarchy, they are
Reader & Writer.
• Character stream classification:

• These two abstract classes have several concrete classes that handle unicode character.
Stream class Description
BufferedReader Handles buffered input stream.
Some important Character BufferedWriter Handles buffered output stream.
stream classes FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output


Reading Console Input
We use the object of BufferedReader class to take inputs from the keyboard :

Reading Characters :
• read() method is used with BufferedReader object to read characters.
• As this function returns integer type value, we need to use typecasting to convert it into char type.
• int read() throws IOException class CharRead {
public static void main( String args[]) {
BufferedReader br = new Bufferedreader(new
InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
} }
Reading Strings :
• To read string we have to use readLine() function with BufferedReader class's object.
• String readLine() throws IOException

Program to take String input from Keyboard :

import java.io.*;
class MyInput {
public static void main(String[] args) {
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
} }
Program to read from a file using BufferedReader class :

import java. Io *;
class ReadTest {
public static void main(String[] args) {
try {
File fl = new File("d:\myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null) {
System.out.println(str); }
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
} } }
Program to write to a File using FileWriter class :

import java. Io *;
class WriteTest {
public static void main(String[] args) {
try {
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
} }
Java Serialization and Deserialization

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

• A class must implement Serializable interface present in java.io package in


order to serialize its object successfully. Serializable is a marker interface that
adds serializable behaviour to the class implementing it.

• Java provides Serializable API encapsulated under java.io package for serializing
and deserializing objects
Marker interface
• It is a special interface without any field and method.
• It is used to inform compiler that the class implementing it has some special
behaviour or meaning.
• Some example of Marker interface are :
• java.io.serializable
• java.lang.Cloneable
• java.rmi.Remote
• java.util.RandomAccess

• However marker interfaces have been deprecated since Java 5, they were
replaced by Annotations.
• Annotations play the exact same role as marker interfaces did before.
transient Keyword
• While serializing an object, if we don't want certain data member of the object to be serialized
we can mention it transient.
• transient keyword will prevent that data member from being serialized.

class studentinfo implements Serializable


{
String name;
transient int rid;
static String contact;
}
• Making a data member transient will prevent its serialization.
In this example :
rid will not be serialized because it is transient, and
contact will also remain unserialized because it is static.
STRING HANDLING
String
• In Java, String is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

char[] ch={'j','a','v','a','t','p',’r',’o',’g',’r’,’a’,’m’};
String s=new String(ch);
is same as: String s="javatprogram";

• String class methods: Used to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

• In many other languages, a string is treated as a character array.


• But in Java, a string is treated as an object.
• After creating a string object we can not change it. So that is why it is said that a string is
immutable.
Note: Strings in Java are not primitive types (like int, char, etc). Instead, all strings are objects of a predefined class -> String.
And, all string variables are instances of the String class.
String Classes
• Java provides three string classes named: String, StringBuffer & StringBuilder.

• Both are mutable.

• The StringBuffer and StringBuilder classes have the same methods with one

difference and that's synchronization.

• A StringBuffer is synchronized (which means it is thread-safe and hence can

be used it when we implement threads for our methods) whereas

StringBuilder is not synchronized (which implies it isn't thread-safe).


String class
 String is represented by String class which is located into java.lang package.
 In java, every string that we create is actually an object of type String.
 String objects are immutable.i.e. once created, it can’t be changed.
 The Java String class implements Serializable, Comparable and CharSequence
interface that we have represented using the below image.

What is an Immutable object?


It is an object whose state cannot be changed after it is created.
String, Integer, Byte, Short, Float, Double and all other wrapper
classes objects are immutable.
Creating a String object

String is immutable. Whenever we change any string, a new instance is created.


There are two ways to create String object: 1. By string literal 2. By new keyword

1) Using a String literal public class Demo{


String literal is a simple string enclosed in double quotes " ". public static void main(String[] args)
A string literal is treated as a String object. { OP:
String s1 = "Hello Java"; Hello
System.out.println(s1); Java
} }

2) Using new Keyword public class Demo{


We can create a new string object by using new operator. public static void main(String[] args) {
It allocates memory for the object. String s1 = new String("Hello
Java");
System.out.println(s1);
}
}
OP:
Hello Java
Each time we create a String literal, the JVM checks the string pool first. If the string literal already exists in the pool, a
reference to the pool instance is returned. If string does not exist in the pool, a new string object is created, and is placed in
the pool. String objects are stored in a special memory area known as string constant pool inside the heap memory.
String object and How they are stored
(1) When we create a new string object using string literal,
that string literal is added to the string pool, if it is not present there
already.
String str= "Hello";
Creating String in heap :
(3) But if we change the new string, its reference gets
modified.
str2=str2.concat("world");

(2) And, when we create another object with same string,


then a reference of the string literal already present in string pool is
returned.
String str2 = str;
String class methods

• The java.lang.String class provides a lot of methods to work on string.

• By the help of these methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.

Important methods of String class =>>


String Methods
(A) Concatenating String
There are 2 methods to concatenate two or more string.
(1) concat() method (2) Using + operator
Example:

1) Using concat() method public class Demo{


used to add two or more string into a single string public static void main(String[] args) { OP:
object. String s1 = "Hello"; HelloJava
String s2 = "Java";
2) Using + operator String s3 = s1.concat(s2);
"+" operator concatenate two string objects into single one. System.out.println(s3); } }
It can also concatenate numeric value with string object.
public class Demo{
public static void main(String[] args) {
Example: String s1= "Hello";
String s2 = "Java";
String s3 = s1+s2; OP:
String s4= "Java"+11; HelloJava
System.out.println(s3); Java11
System.out.println(s4); }
}
(B) String Comparison

3 ways:

1. Using equals() method


2. Using == operator
3. By CompareTo() method

(B-1) Using equals() method


compares two strings for equality. It compares the original content of the string.
String class provides two methods:

• public boolean equals(Object another) compares this string to the specified object.

• public boolean equalsIgnoreCase(String another) compares this String to another string,


ignoring case.
Example:
It compares the content of the strings. It will return true if string matches, else returns false.(But match the case)
class Teststringcomparison1{
public static void main(String args[]){
String s1="Krishna";
String s2="Krishna";
String s3=new String("Krishna");
String s4="Abhineet";
System.out.println("s1.equals(s2)=>>"+s1.equals(s2));
System.out.println("s1.equals(s3)=>>"+s1.equals(s3));
System.out.println("s1.equals(s4)=>>"+s1.equals(s4)); } }

Example: It compares the content of the strings. It will return true if string matches, else returns false.(But match the
case). To ignore the case, use “equalsIgnoreCase())

class Teststringcomparison2{
public static void main(String args[]){
String s1="Kunj";
String s2="KUNJ";
System.out.println("s1.equals(s2)=>>"+s1.equals(s2));//false
System.out.println("s1.equalsIgnoreCase(s2)=>>"+s1.equalsIgnoreCase(s2));//true
} }
(B-2) Using == operator
compares two object references to check whether they refer to same instance.
This also, will return true on successful match else returns false.
class Test3{
public static void main(String args[]){
String s1="Kunj";
String s2="Kunj";
String s3=new String("Kunj");
System.out.println("s1==s2=>>"+(s1==s2));//true (because both refer to same instance)
System.out.println("s1==s3=>>"+(s1==s3));//false(because s3 refers to instance created in nonpool)
} }

(B-3) By CompareTo() method


Compares the given string with current string lexicographically. It returns positive number, negative number or 0.
It compares strings on the basis of Unicode value of each character in the strings(lexicographically)
public class CompareToExample{
public static void main(String[] args) {
String s1 = "Abhi";
if s1 > s2, it returns positive number String s2 = "Vinny";
if s1 < s2, it returns negative number String s3 = "Abhi";
if s1 == s2, it returns 0 int a = s1.compareTo(s2); //return -21 because s1 < s2
System.out.println("s1.compareTo(s2)=>>"+a);
a = s1.compareTo(s3); //return 0 because s1 == s3
System.out.println("s1.compareTo(s3)=>>"+a);
a = s2.compareTo(s1); //return 21 because s2 > s1
System.out.println("s2.compareTo(s1)=>>"+a); } }
(C) Substring

A part of string is called substring or it is a subset of another string.


In case of string:
startIndex: inclusive
endIndex: exclusive
(Index starts from 0).

We can get substring from the given string object by one of the two methods:

(i) public String substring(int startIndex):


returns new String object containing the substring of the given string from specified startIndex (inclusive).
(ii) public String substring(int startIndex, int endIndex):
returns new String object containing the substring of the given string from specified startIndex to endIndex.

Example :
public class TestSubstring{
public static void main(String args[]){
String s="Aviral Maitrey";
System.out.println(s.substring(7)); //Maitrey
System.out.println(s.substring(0,6)); // Aviral
}
}
(D) String toUpperCase() and toLowerCase() method
toUpperCase() : converts given string into uppercase letter
toLowerCase() : converts given string into lowercase letter.
Example: public class TestCase{
public static void main(String args[]){
String s="Abhineet";
System.out.println("s.toUpperCase()=>>"+s.toUpperCase()); //ABHINEET
System.out.println("s.toLowerCase()=>>"+s.toLowerCase()); //abhineet
System.out.println("Original String=>>"+s); //Abhineet(no change in
original)
} }
(E) String trim() method
eliminates white spaces before and after string
Example:
public class TestTrim
{
public static void main(String args[]){
String s=" Abhineet";
System.out.println("Actual string=>>"+s); // Abhineet(with whitespace)
System.out.println("Using trim=>>"+s.trim()); //Abhineet(no whitespace)
}
}
(F) startsWith() and endsWith() method
startsWith(): check whether the given string starts with given prefix or not and returns true when prefix matches the string else it returns
false.

endsWith(): check whether the string ends with the given suffix or not and returns true when suffix matches the string else it returns false.
Example: public class TestStartEnd{
public static void main(String args[]){
String s="Abhineet";
System.out.println("Given String is=>"+s);
System.out.println(s.startsWith("Se")); //false
System.out.println(s.endsWith("t")); //true
System.out.println(s.startsWith("Ab")); //true
System.out.println(s.startsWith("ab")); //false
System.out.println(s.endsWith("T")); //false
} }

(G) join() method


returns a string joined with given delimiter. Delimiter is copied for each elements.
Example: public class Testjoin {
public static void main(String[] args)
{
String date = String.join("/", "30","09","2010");
System.out.print("Date is=>>"+date);
String time = String.join(":", “03",“10",“10");
System.out.println(".........Time is=>>" +time); } }
(H) charAt() method
returns a character at specified index.

Example: public class TestcharAt{


public static void main(String args[]){
String s="Abhineet";
System.out.println("Given String is=>"+s);
System.out.println("s.charAt(0)=>>"+s.charAt(0)); //A
System.out.println("s.charAt(4)=>>"+s.charAt(4)); //n
}
}

(I) length() method


The string length() method returns length of the string.

public class Testlength{


Example: public static void main(String args[]){
String s="Abhineet";
System.out.println("Given String is=>"+s);
System.out.println("s.length()=>>"+s.length()); //8
}
}
(J) valueOf() method
used to convert primitive data types into Strings.

Example: public class TestvalueOf{


public static void main(String args[]){
int num=10;
String s=String.valueOf(num);
System.out.println(s+10);
System.out.println("type of num is: "+s.getClass().getName());
} }
(K) replace() method
replaces all occurrence of first sequence of character with second sequence of character.
Example:
public class TestReplace
{
public static void main(String args[])
{
String s1="Java is a programming language. \nJava is platform-independent. \nJava is an Island.
System.out.println("Given String is->>\n"+s1);
System.out.println("-----replace String------\n");
String replaceString=s1.replace("Java","Zava"); //replaces all occurrences of "Java" to "Zava"
System.out.println(replaceString);
} }
(L) indexOf() method
returns index of given character value or substring. If it is not found, it returns -1. The index counter starts from zero.

Example:

public class Testindexof


{
public static void main(String args[])
{
String s1="this is index of example";
//passing substring
int i1=s1.indexOf("is"); //returns the index of is substring
int i2=s1.indexOf("index"); //returns the index of index substring
System.out.println("index1=>"+ i1+" "+"index2=>>"+i2); //2 8
//passing substring with from index
int i3=s1.indexOf("is",4); //returns the index of is substring after 4th index
System.out.println("index3=>>"+i3); //5 i.e. the index of another is
//passing char value
int i4=s1.indexOf('s’); //returns the index of s char value
System.out.println("index4=>>"+i4);//3
}
}
(M) toCharArray() method
converts this string into character array.
It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.

public class Testtochararray {


public static void main(String[] args) {
String s1 = "Welcome to Web Tech";
System.out.println("Given String is=>>"+s1);
char[] ch = s1.toCharArray();
int len = ch.length;
System.out.println("Char Array length: " + len);
System.out.println("Char Array elements: ");
for (int i = 0; i < len; i++) {
System.out.print(ch[i]+" ");
}
}
}
StringBuffer class

used to create mutable (modifiable) string. It is same as String class except it is mutable i.e. it can be changed.
It is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.

Important Constructors of StringBuffer class


Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.

StringBuffer and StringBuilder classes are used for creating mutable string.
a) StringBuffer append() method
The append() method concatenates the given argument with provided string.

class SBconcat{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Hello Java
}
}

b) insert() method
inserts the given string with this string at the given position.
class SBinsert{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(2,"Java"); //now original string is changed
System.out.println(sb); //prints HeJavallo
}
}
c) StringBuffer replace() method
replaces the given string from the specified beginIndex and endIndex.
class SBreplace{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}

d) StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.

class Sbdelete
{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb); //prints Hlo
}
}
e) StringBuffer reverse() method
It reverses the current string. Prints from last index.
Example:
class SBreverse{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Kunj");
System.out.println("Original String:"+sb);
//sb.reverse();
System.out.println("Reversed String:"+sb.reverse()); } }

f) StringBuffer capacity() method


returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

Example:
class SBcapacity{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println("Default Capacity of sb:"+sb.capacity()); //default 16
sb.append("Hello");
System.out.println("After appending Hello into sb, capacity is=>>"+sb.capacity()); //now 16
sb.append("WT is my favourite subject");
System.out.println("Appending another string into sb, capacity is=>>"+sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
} }
StringBuilder class
StringBuilder also used for creating string object that is mutable and non synchronized. StringBuffer and StringBuilder
both are mutable but if synchronization is not required then it is recommend to use StringBuilder class.

Constructors of StringBuilder class

Constructor Description

StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(String str) creates a string Builder with the specified string.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.

1) StringBuilder append() method


It concatenates the given argument with this string.

class SBLappend{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Important methods of StringBuilder class

Method Description
public StringBuilder append(String s) is used to append the specified string with this string. The append() method is
overloaded like append(char), append(boolean), append(int), append(float),
append(double) etc.

public StringBuilder insert(int offset, String s) is used to insert the specified string with this string at the specified position. The
insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int,
int), insert(int, float), insert(int, double) etc.

public StringBuilder replace(int startIndex, int endIndex, is used to replace the string from specified startIndex and endIndex.
String str)
public StringBuilder delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and endIndex.

public StringBuilder reverse() is used to reverse the string.


public int capacity() is used to return the current capacity.

public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least equal to the given minimum.

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total number of characters.

public String substring(int beginIndex) is used to return the substring from the specified beginIndex.

public String substring(int beginIndex, int endIndex) is used to return the substring from the specified beginIndex and endIndex.
StringTokenizer class
A class that allows us to break a string into tokens based on provided delimiter.
It is simple way to break string. It is located into java.util package.

Methods of StringTokenizer class

Public method Description

boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the StringTokenizer object.

String nextToken(String delim) returns the next token based on the delimeter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.


(A)hasMoreTokens() methods
checks if there is more tokens available.

import java.util.StringTokenizer;
public class TestSThasmoretokens{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("My name is KUNJ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
} } }

(B) nextToken(String delim) method


returns the next token from the StringTokenizer object.

import java.util.*;
public class TestSTnextoken{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("My,name,is,KUNJ");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
}

You might also like