RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
String Handling :
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
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={'W','e','l','c','o','m','e'};
String s=new String(ch);
is same as:
String s="Welcome";
There are two ways to create String object:
• By string literal
• By new keyword
1) String Literal
Java String literal is created by using double
quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM
checks the "string constant pool" first. If the
string already exists in the pool, a reference to
the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance
is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome"; //It doesn't create a new instance
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a
heap (non-pool).
1|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
Java String class methods:
No. Method Description
1 char charAt(int index) It returns char value for the particular index
2 int length() It returns string length
3 String substring(int beginIndex) It returns substring for given begin index.
4 boolean contains(CharSequence It returns true or false after matching the sequence of char
s) value.
5 boolean equals(Object another) It checks the equality of string with the given object.
6 boolean isEmpty() It checks if string is empty.
7 String concat(String str) It concatenates the specified string.
8 String replace(char old, char It replaces all occurrences of the specified char value.
new)
9 int indexOf(int ch) It returns the specified char value index.
10 String toLowerCase() It returns a string in lowercase.
11 String toUpperCase() It returns a string in uppercase.
12 String trim() It removes beginning and ending spaces of this string.
String Buffer:
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class
in Java is the same as String class except it is mutable i.e. it can be changed. It provides an
alternative to the immutable String class, allowing you to modify the contents of a string without
creating a new object every time.
Here are some important features and methods of the StringBuffer class:
StringBuffer objects are mutable, meaning that you can change the contents of the buffer without
creating a new object.
The initial capacity of a StringBuffer can be specified when it is created, or it can be set later with
the ensureCapacity() method.
The append() method is used to add characters, strings, or other objects to the end of the buffer.
The insert() method is used to insert characters, strings, or other objects at a specified position in
the buffer.
The delete() method is used to remove characters from the buffer.
The reverse() method is used to reverse the order of the characters in the buffer.
2|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
public class StringBufferExample {
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" ");
sb.append("world");
String message = sb.toString();
System.out.println(message);
}
}
Output:
Hello world
String Builder :
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class
is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java
creates an immutable sequence of characters, the StringBuilder class provides an alternative to
String Class, as it creates a mutable sequence of characters. The function of StringBuilder is very
much similar to the StringBuffer class, as both of them provide an alternative to String Class by
making a mutable sequence of characters. However, the StringBuilder class differs from the
StringBuffer class on the basis of synchronization. The StringBuilder class provides no guarantee of
synchronization whereas the StringBuffer class does. Therefore this class is designed for use as a
drop-in replacement for StringBuffer in places where the StringBuffer was being used by a single
thread (as is generally the case). Where possible, it is recommended that this class be used in
preference to StringBuffer as it will be faster under most implementations. Instances of
StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is
recommended that StringBuffer be used. String Builder is not thread-safe and high in performance
compared to String buffer.
3|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
Comparison between String, StringBuilder, and StringBuffer:
Feature String StringBuilder StringBuffer
Introduction Introduced in JDK 1.0 Introduced in JDK 1.5 Introduced in JDK 1.0
Mutability Immutable Mutable Mutable
Thread Safety Thread Safe Not Thread Safe Thread Safe
Memory Efficiency High Efficient Less Efficient
Performance High(No- High(No- Low(Due to
Synchronization) Synchronization) Synchronization)
Usage This is used when we This is used when This is used when
want immutability. Thread safety is not Thread safety is
required. required.
4|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
Exception Handling :
Exception Handling in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle
runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException,
etc.
What are Java Exceptions?
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions
can be caught and handled by the program. When an exception occurs within a method, it creates an
object. This object is called the exception object. It contains information about the exception, such
as the name and description of the exception and the state of the program when the exception
occurred.
Major reasons why an exception Occurs:
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors
are usually beyond the control of the programmer, and we should not try to handle errors.
Difference between Error and Exception:
Let us discuss the most important part which is the differences between Error and Exception that is
as follows:
Error: An Error indicates a serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
5|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
Types of Exceptions:
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.
Java Exception Keywords:
Java provides five keywords that are used to handle the exception. The following table describes
each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch or
finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.
6|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
Example:
public class JavaExceptionExample
{
public static void main(String args[])
{
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e)
{System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}
7|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
File Handling :
In Java, a File is an abstract data type. A named location used to store related information is known
as a File. There are several File Operations like creating a new File, getting information about File,
writing into a File, reading from a File and deleting a File.
Stream
A series of data is referred to as a stream. In Java, Stream is classified into two types, i.e., Byte
Stream and Character Stream.
1) Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte stream is a
process in which an input is provided and executed with the byte data
2) Character Stream
Character Stream is mainly involved with character data. A file handling process with a character
stream is a process in which an input is provided and executed with the character data.
8|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
ByteStream Classes in Java:
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. These classes are part of the
java.io package.
The ByteStream classes are divided into two types of classes, i.e., InputStream and OutputStream.
These classes are abstract and the super classes of all the Input/Output stream classes.
Java FileInputStream Class-
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data
(streams of raw bytes) such as image data, audio, video etc.
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Java FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write byte-
oriented as well as character-oriented data through FileOutputStream class.
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
9|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
CharacterStream Classes in Java:
The java.io 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. For this purpose, the CharacterStream classes are divided into two types of
classes, I.e., Reader class and Writer class.
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.
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("Sample.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
10 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit IV
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.
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("Sample.txt");
fw.write("Welcome to java.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
11 | P a g e
Study Notes (For Private Circular Only)