Java Unit3
Java Unit3
io)
Exception handling - Fundamentals, Exception types, Uncaught exceptions, using try and
catch, multiple catch clauses, nested try statements, throw, throws and finally, built-in
exceptions, creating own exception subclasses.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams, Reading
console Input and Writing Console Output, File class, Reading and Writing Files, Random
access file operations, The Console class, Serialization, Enumerations, Autoboxing, Generics.
Exception handling:
An exception is an unexpected event that occurs during program execution. It affects the flow
of the program instructions which can cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to
handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5; //exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10.statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements will be executed. That is why
we use exception handling in Java.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Errors
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.
Exceptions
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 state of the program when the exception occurred.
RuntimeException
A runtime exception happens due to a programming error. They are also known
as unchecked exceptions.
These exceptions are not checked at compile-time but run-time. Some of the common runtime
exceptions are:
Improper use of an API - IllegalArgumentException
Null pointer access (missing the initialization of a variable) - NullPointerException
Out-of-bounds array access - ArrayIndexOutOfBoundsException
Dividing a number by 0 - ArithmeticException
We can think about it in this way. “If it is a runtime exception, it is your fault”.
The NullPointerException would not have occurred if we had checked whether the variable
was initialized or not before using it.
An ArrayIndexOutOfBoundsException would not have occurred if we tested the array index
against the array bounds.
IOException
An IOException is also known as a checked exception. They are checked by the compiler at
the compile-time and the programmer is prompted to handle these exceptions.
Some of the examples of checked exceptions are:
Trying to open a file that doesn’t exist results in FileNotFoundException
Trying to read past the end of a file
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as
the unchecked exception. However, according to Oracle, there are three types of exceptions
namely:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Keywor Description
d
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.
E:\>java JavaExceptionExample
Exception in thread "main" java.lang.ArithmeticException: / by zero
at JavaExceptionExample.main(JavaExceptionExample.java:5)
2. toString() – This method prints exception information in the format of Name of the
exception: description of the exception.
Example:
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
}
Output:
java.lang.ArithmeticException: / by zero
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
Output:
/ by zero
Let's see an example of Java Exception Handling in which we are using a try-catch statement
to handle the exception.
JavaExceptionExample.java
Output:
E:\>javac JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){ E:\>java JavaExceptionExample
try{ java.lang.ArithmeticException: / by zero
//code that may raise exception rest of the code...
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Multiple catch clauses:
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if we have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed onto
the stack.
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
System.out.println("other statement");
}
// catch block of outer try block
catch (Exception e) {
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
E:\>javac NestedTryBlock.java
E:\>java NestedTryBlock
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
other statement
normal flow..
Throw statement:
program:
//user defined exception
class Eligible extends Exception {
String str;
Eligible(String s) {
str = s;
}
public String toString() {
return ("user defined Exception is " + str);
}
public static void main(String[] args)throws Eligible {
int age = 15;
try {
if (age < 18) {
throw new Eligible("not eligible for vote");
} else {
System.out.println("eligible for vote");
}
} catch (Eligible e) {
Output:
System.out.println(e); E:\>javac Eligible.java
} E:\>java Eligible
finally user defined Exception is not eligible for
{ vote
System.out.println("Finally block"); Finally block
rest of code
}
System.out.println("rest of code");
}
}
throws is a keyword in Java which is used in the signature of method to indicate that this
method might throw one of the listed type exceptions. The caller to these methods has to
handle the exception using a try-catch block.
Syntax:
accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 …
{
// code
}
exception_list is a comma separated list of all the
exceptions which a method might throw.
Example:
public static void findFile() throws NullPointerException, IOException,
InvalidClassException {
// code that may produce NullPointerException
………
Finally block:
Java finally block is a block used to execute important code such as closing the connection,
etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occurs
or not.
Example:
public class TestFinallyBlock1{
public static void main(String args[]){
try {
E:\>javac TestFinallyBlock.java
E:\>java TestFinallyBlock
Inside the try block
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestFinallyBlock.main(TestFinallyBlock.java:9)
List of checked exceptions in Java
The following table shows the list of several checked exceptions.
S.
No. Exception Class with Description
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and
the specified class cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an
object, but that the object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers
do not allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the
newInstance method in class Class , but the specified class object cannot be
instantiated because it is an interface or is an abstract class.
5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.
6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at
compile time, a NoSuchMethodException occurs during reflection when we try to
access a method that does not exist.
1 ArithmeticException
It handles the arithmetic exceptions like dividion by zero
S.
No. Exception Class with Description
2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.
3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type
of object into an array of objects
4 AssertionError
It is used to indicate that an assertion has failed
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to
another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal
or inappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or
has attempted to notify other threads that wait on an object's monitor, without
owning the specified monitor.
8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to
modify the state of the thread when it is illegal.
10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as
an array , vector , string , and so forth.
11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
S.
No. Exception Class with Description
It is thrown when we try to convert a string into a numeric value such as float or
integer, but the format of the input string is not appropriate or illegal.
14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is
either negative, or greater than the size of the string itself.
16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.
The Stream:
A stream is a sequence of data. Streams facilitate translating data from one place to another.
Different streams are needed to send and receive data through different sources, such as to
receive data from keyboard, we need a stream and to send data to a file, we need another
stream. Without streams it is not possible to move data in java.
System class also contains three predefined stream variables, in, out, and err. These
fields are declared as public and static within System.
System.out refers to the standard output stream. By default, this is the console.
System.in refers to standard input, which is the keyboard by default.
System.err refers to the standard error stream, which also is the console by default.
System.in is an object of type InputStream;
System.out and System.err are objects of type PrintStream.
Standard Input: Accessed through in which is used to read input from the keyboard.
Standard Output: Accessed through out which is used to write output to the display
(console).
Standard Error: Accessed through err which is used to write error output to the
display (console).
There are two brands of Stream in Java Programming Language:
1. Input Stream:
The Input Stream provides the functionality of taking the Input from a Source. The Input
Stream provides the set of Objects and pipelines together to provide us the functionality of
Input the collection in I/O File.
2. Output Stream:
The Output Stream provides the functionality of writing the data to the Destination. The
Output Stream provides the set of Objects and pipelines together to provide us the
functionality of Output to the collection in I/O File.
Fig: Flow of data in standard Input-Output streams and file streams
The Java Input/Output (I/O) is a part of java.io package. This package contains a relatively
large number of classes that support input and output operations. These classes may be
categorized into groups based on the data type on which they operate.
1. Byte Stream Classes that provide support for handling I/O operations on bytes.
2. Character Stream Classes that provide support for managing I/O operations
on characters.
These two groups may further be classified based on their purpose. Figure below shows how
stream classes are grouped based on their functions. Byte stream and Character stream classes
contain specialized input and output stream classes to deal with input and output operations
independently on various types of streams.
The subclasses inherited from the InputStream class can be seen in a hierarchy manner shown
below:
Methods of InputStream
The InputStream class provides different methods that are implemented by its subclasses. Here
are some of the commonly used methods:
read() - reads one byte of data from the input stream
read(byte[] array) - reads bytes from the stream and stores in the specified array
available() - returns the number of bytes available in the input stream
mark() - marks the position in the input stream up to which data has been read
reset() - returns the control to the point in the stream where the mark was set
markSupported() - checks if the mark() and reset() method is supported in the stream
skips() - skips and discards the specified number of bytes from the input stream
close() - closes the input stream
OutputStream Classes
The OutputStream class is a sibling to InputStream that is used for writing byte and array of
bytes to an output source. Similar to input sources, an output source can be anything such as a
file, a string, or memory containing the data. Like an input stream, an output stream is
automatically opened when we create it. We can explicitly close an output stream with
the close() method, or let it be closed implicitly when the object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy structure shown
below:
Methods of OutputStream
The OutputStream class provides different methods that are implemented by its subclasses.
Here are some of the methods:
write() - writes the specified byte to the output stream
write(byte[] array) - writes the bytes from the specified array to the output stream
flush() - forces to write all data present in output stream to the destination
close() - closes the output stream
2. Character Stream Classes
Java offers another type of streams called Character Streams, which are used to read from the
input device and write to the output device in units of 16-bit (Unicode) characters. In some
cases, character streams are more efficient than byte streams. The oldest version of Java (Java
1.0) did not include character streams and, thus, all I/O was byte-oriented. Character streams
were added by Java 1.1, and certain byte-oriented classes and methods were deprecated.
Character streams are defined by using two class hierarchies. At the top there are two abstract
classes, Reader and Writer. These abstract classes handle Unicode character (16-bit)
streams. Java has several concrete subclasses of each of these. The abstract
classes Reader and Writer define several key methods that the other stream classes implement.
Two of the most important methods are read() and write(), which read and write characters of
data, respectively. These methods are overridden by derived stream classes.
abstract void close() It closes the stream and releases any system resources
associated with it.
void mark(int readAheadLimit) It marks the present position in the stream.
Boolean markSupported() It tells whether this stream supports the mark() operation.
abstract int read(char[] cbuf, int off, int It reads characters into a portion of an array.
len)
int read(CharBuffer target) It attempts to read characters into the specified character
buffer.
Writer append(CharSequence csq, int start, It appends a subsequence of the specified character
int end) sequence to this writer.
abstract void write(char[] cbuf, int off, int len) It writes a portion of an array of characters.
void write(String str, int off, int len) It writes a portion of a string.
Java provides different ways to take input and provide output on the console.
We use the object of Bufferedredaer class to take input from the keyboard
To use these classes, we need to use the java.io package. Let’s see an example to understand
this method of reading input from the console.
Example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedReaderDemo
{
public static void main(String[] args) throws IOException
{
InputStreamReader input = new InputStreamReader(System.in);
//Taking the input data using the BufferedReader class
BufferedReader br= new BufferedReader(input);
The other use of Scanner class is to parse the strings and primitive types with the help of java
regular expressions.
The Scanner class is present in the java.util package. This class obtains the input from
System.in (standard input stream).
Advantages
The Scanner class provides useful methods like nextInt(), nextDouble(), nextFloat(), etc,
for parsing primitive data types.
The Scanner class uses regular expressions and we can use these regular expressions to find
tokens.
Drawback
The methods of Scanner class for reading values are not synchronized
Methods:
To read the values of various data types, the Scanner class provides several methods. The
following table shows these methods:
Method Description
nextBoolean() This method reads a boolean value from the user
import java.util.Scanner;
public class ScannerClassDemo
{
// Java program to understand the use of Scanner in Java
public static void main(String args[]) Output:
{ E:\pgms>javac ScannerClassDemo.java
// Using Scanner for Getting Input from User E:\pgms>java ScannerClassDemo
Scanner sc = new Scanner(System.in); Enter a string
ram
System.out.println("Enter a string"); You entered string: ram
Enter a number
String string = sc.nextLine(); 1001
System.out.println("You entered string: " +string); You entered integer: 1001
Enter a float number
System.out.println("Enter a number"); 78.9076
int num = sc.nextInt(); You entered float: 78.9076
System.out.println("You entered integer: " +num);
we use the Console class, the JVM associated system console isn't available if we run the code
within an IDE such as Eclipse or IntelliJ IDEA.
There are several methods in Console class that help in reading input texts and passwords
from the console, without displaying it on the screen.
Methods of Java Console class
Method Description
String readLine() This method reads a single line of text from the console.
char[] readPassword() It is used to read a password that is visible on the console screen.
Advantages
Reading password without displaying the characters of the password on the console.
Reading methods of the console class are synchronized.
We can also use the format string syntax with the Console class
Drawback
It does not work in a non-interactive environment (such as in an IDE).
Example:
import java.io.*;
Output:
E:\pgms>javac ConsoleDemo.java
public class ConsoleDemo { E:\pgms>java ConsoleDemo
public static void main(String[] args) Enter username : satya
{ Username : satya
// Create the console object Enter password :
Password : [C@3b9a45b3
Console cnsl= System.console();
if (cnsl == null) {
System.out.println("No console available");
return;
}
// Read line
String str = cnsl.readLine("Enter username : ");
// Print username
System.out.println("Username : " + str);
// Print password
System.out.println("Password : " + ch);
}
}
Writing console output in java
In java, there are two methods to write console output. Using the 2 following methods, we can
write output data to the console.
File class:
The File is a built-in class in Java. In java, the File class has been defined in
the java.io package. The File class represents a reference to a file or directory. The File class
has various methods to perform operations like creating a file or directory, reading from a file,
updating file content, and deleting a file or directory.
S.No. Constructor with Description
1 File(String pathname)
It creates a new File instance by converting the givenpathname string into an abstract
pathname. If the given string isthe empty string, then the result is the empty abstract
pathname.
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract
pathname.
import java.io.File;
FileWriter Class:
Java FileWriter class of java.io package is used to write data in character form to file.
Java FileWriter class is used to write character-oriented data to a file. This class
extends OutputStreamWriter. This class provides methods to write strings directly so we don't
need to convert string to a byte array.
o FileWriter is meant for writing streams of characters. For writing streams of raw
bytes, consider using a FileOutputStream.
o FileWriter creates the output file if it is not present already.
Method Description
void write(String text) This method is used to write the string into FileWriter.
void write(char c) This method is used to write the char into FileWriter.
void write(char[] c) Thi method is used to write char array into FileWriter.
try {
// Creates a FileWriter
FileWriter output = new FileWriter("output.txt");
FileReader class:
The FileReader class of the java.io package can be used to read data (in characters) from files.
It extends the InputSreamReader class.
Create a FileReader
In order to create a file reader, we must import the java.io.FileReader package first. Once we
import the package, here is how we can create the file reader.
1. Using the name of the file
FileReader input = new FileReader(String name);
Here, we have created a file reader that will be linked to the file specified by the name.
2. Using an object of the file
FileReader input = new FileReader(File fileObj);
Here, we have created a file reader that will be linked to the file specified by the object of the
file.
Methods of FileReader
The FileReader class provides implementations for different methods present in
the Reader class.
read() Method
read() - reads a single character from the reader
read(char[] array) - reads the characters from the reader and stores in the specified array
read(char[] array, int start, int length) - reads the number of characters equal to length from
the reader and stores in the specified array starting from the position start
For example:
we have a file named input.txt with the following content.
This is a line of text inside the file.
Let's try to read the file using FileReader.
import java.io.FileReader;
class Main {
public static void main(String[] args) {
try {
// Creates a reader using the FileReader
FileReader input = new FileReader("input.txt");
// Reads characters
input.read(array);
System.out.println("Data in the file: ");
System.out.println(array); Output
Data in the file:
This is a line of text inside the file.
// Closes the reader
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
In the above example, we have created a file reader named input. The file reader is linked with
the file input.txt.
FileInputStream input = new FileInputStream("input.txt");
To read data from the file, we have used the read() method.
Note: The file input.txt should be present in the current working directory.
RandomAccessFile:
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 we do the read write operations. 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.
Constructor Description
Access Modes
Using the RandomAccessFile, a file may created in th following modes.
r - Creates the file with read mode; Calling write methods will result in an IOException.
rw - Creates the file with read and write mode.
rwd - Creates the file with read and write mode - synchronously. All updates to file
content is written to the disk synchronously.
rws - Creates the file with read and write mode - synchronously. All updates to file
content or meta data is written to the disk synchronously.
Method:
void close() It closes this random access file stream and releases any system
resources associated with the stream.
int readInt() It reads a signed 32-bit integer from this file.
Example:
import java.io.RandomAccessFile;
import java.io.*;
class RaFile
{
public static void main(String args[])throws IOException
{
RandomAccessFile rf=null;
try{
rf=new RandomAccessFile("output.txt","rw");
rf.seek(34);
Output:
rf.writeUTF("Hyderabad"); E:\>javac RaFile.java
rf.seek(10); E:\>java RaFile
int b; file to display capital
while((b=rf.read())!= -1) Hyderabad,,amaravathi
{
System.out.print((char)b);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(rf != null)
{
rf.close();
}
}
}
}
Java Enum:
Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named
values separated by commas. These named values are also known as elements or enumerators
or enum instances. Since the values in the enum type are constant, we should always represent
them in UPPERCASE letters.
You can use an Enum type when we need a fixed set of pre-defined constant values that are
known at the compile-time itself. Examples can be days of the week, seasons of the year, etc.
default:
System.out.println(" WORNG WEEK NAME");
break;
}
}
}
}
Serialization:
Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the actual
Java object in memory. This mechanism is used to persist the object.
The byte stream created is platform independent. So, the object serialized on one platform
can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.
// Default constructor
public Student(int a, String b)
{
this.a = a;
this.b = b;
}
}
class Test
{
public static void main(String[] args)
{
Student object = new Student(1001, "ram");
String filename = "file.ser";
// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
in.close();
file.close();
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}
}
}
Example:
class BoxingExample1{
public static void main(String args[]){
int a=50;
Output:
Integer a2=new Integer(a);//Boxing
Integer a3=5; //Boxing 50 5
System.out.println(a2+" "+a3);
}
}
The automatic conversion of wrapper class type into corresponding primitive type, is known
as Unboxing. Let's see the example of unboxing:
class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;
System.out.println(a); 50
}}
Generics in Java:
Generics means parameterized types. The idea is to allow type (Integer, String, … etc.,
and user-defined types) to be a parameter to methods, classes, and interfaces. Using
Generics, it is possible to create classes that work with different data types.
Note: Generics does not work with primitive types (int, float, char, etc).
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store
other objects.
E:\>java GenericsDemo
Generic Class returns: 5
Generic Class returns: Java Programming
Java StringBuffer Class:
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.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Example:
class StringBufferExample{
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
}
}
Output:
Hellojava
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH
StringBuilder class:
StringBuilder class has been added in JDK1.5 which has same features like StringBuffer class.
StringBuilder class objects are also mutable as the stringBuffer Objects.
Difference:
StringBuffer is class is synchronized and StringBuilder is not.