UNIT-2 Exception Handling: Types of Errors
UNIT-2 Exception Handling: Types of Errors
UNIT-2
EXCEPTION HANDLING
In our daily life we will be committing so many mistakes. Similarly in the process of developing a software a
programmer will also perform many mistakes. In computer terminology those mistakes are called as BUGS or
ERRORS. The process of removing these errors in known as DEBUGGING.
Types of errors :
1. Compile-time errors
2. Run-time errors
3. Logical errors
Compile-time errors :
class demo
{
public static void main(String args[])
{
System.out.println("this is my first java program")
}
}
When we run this code it generates an error since semi-colon is missing after the statement :
System.out.println("this is my first java program")
Such errors are known as SYNTAX ERRORS and are caught when a program is compiled. These compile time errors
are found by java compiler i.e., javac
Logical errors :
Consider the following code. It is written to calculate the salary of employee after getting 15% hike added to his
basic salary.
class demo
{
public static void main(String args[])
{
double salary = 5000;
salary = salary * (15/100);
System.out.println("after incrementing salary = "+ salary);
}
}
But when the above code is executed the output will be : 750
1
OOPS USING JAVA UNIT-2
This is because :
The statement that was written to calculate the salary is wrong. That is , it written as :
salary = salary * (15/100);
but it must be written as : salary = salary + (salary * (15/100));
such errors are not caught by java compiler (javac) or JVM. Finding out those errors is the responsibility of the
programmer only.
Note : by comparing the output of a program with the manually calculated result the programmer can find the
presence of a logical error.
Run-time error :
A run- time error is called as exception.
An exception is an event that occurs during the execution of a program that disrupts the normal flow of
instructions.
Exceptions are detected by JVM at run-time.
Consider the following code :
class demo
{
public static void main()
{
System.out.println("this is my first java program");
}
}
The above code can be compiled but we cannot execute(run) the code. Since when ever we run the code using
statement java demo it generated error since JVM can’t find main() method with String args[] in the above code.
So it generates an error.
All exceptions occur at run-time only. But some exceptions are detected at run-time and some are detected at
compile-time.
The exceptions that are checked at compilation-time by java compiler are called as CHECKED EXCEPTIONS and
that are checked by JVM are called as UNCHECKED EXCEPTIONS.
Unchecked exceptions and errors are considered as unrecoverable and the programmer cannot do anything when
they occur.
2
OOPS USING JAVA UNIT-2
The programmer can write a java program with unchecked exceptions and errors and can compile the program. He
can see their effect only when he runs the program. So java compiler allows him to write a java program without
handling the unchecked exception and errors.
In case of checked exceptions the programmer should either handle them or throw them without handling them.
He cannot simply ignore them as java compiler would remind him of those errors.
here, IOException is an example for checked exception. So we threw it out of main() without handling it. This is
done by throws clause written after main(). We can also handle it using try and catch blocks. Suppose we are not
even throwing and handling then the java compiler will raise an error.
The point is that an exception occurs only at run-time. But a checked exception, whether we handle it or not it is
detected at compilation time.
So exception can be defined as run-time error that can be handled by programmer.
That is in case of exception the programmer can do something to avoid it. But in case of error programmer cannot
do anything and hence if error occurs it causes some damage.
All exceptions are declared as classes in java. Of course everything is a class in java. Even the errors are also
represented as classes. All these classes are descendants of a super class called as throwable.
3
OOPS USING JAVA UNIT-2
try block :-
The programmer should observe the statements in his program where there may be a possibility of
exceptions. Such statements should be written inside try block.
A try block looks as follows :-
try
{
Statements;
}
Try block first finds the error with in code limit and then throws it to catch block.
Each and every try block should have a minimum of one catch block.
The greatness of try block is that even if some exception arises inside it, the program will not be
terminated. When JVM understands that there is an exception it stores the exception details in an
exception stack and then jumps into catch block.
Catch block:-
Catch block catches the error thrown by try block and then prints them.
Catch block specifies the type of error.
A catch block looks as follows :-
catch (ExceptionClass reference)
{
Statements;
}
The reference variable above is automatically adjusted to refer the exception stack where the details of
the exception are available and those details can be displayed using the statement
System.out.println(reference); and also by using printStackTrace() method of throwable class which
fetches the details of exception from the exception stack.
Finally block:-
After writing try and catch blocks the programmer should ensure that clean up operations like closing the
files and terminating the threads. The programmer should write this code in the finally block.
Statements in finally block are executed irrespective whether there is an exception or not in the program.
The finally block looks as follows :-
finally
{
Statements;
}
This ensures that all the opened files are properly closed and all the running threads are properly
terminated. So the data in the files will not be corrupted and the user in on safe side.
Note: Performing the above tasks is called as “exception handling”. Remember in exception handling the
programmer is not preventing the exception, as in many cases it is not possible. But the programmer is
avoiding any damage that may happen to user data.
Types of exceptions:
4
OOPS USING JAVA UNIT-2
class exceptiondemo
{
public static void main(String[] args)
{
try
{
System.out.println("open files");
int n = args.length;
System.out.println(" n = "+ n);
int a = 45/n;
System.out.println("a = "+a);
}
catch(ArithmeticException ae)
{
ae.printStackTrace();
System.out.println(ae);
System.out.println("please enter data while running the program");
5
OOPS USING JAVA UNIT-2
finally
{
System.out.println("close files");
}
}
}
class exceptiondemo1
{
public static void main(String[] args)
{
try
{
System.out.println("open files");
int n = args.length;
System.out.println(" n = "+ n);
int a = 45/n;
System.out.println("a = "+a);
int b[] = { 10,20,30};
b[50]=100;
}
catch(ArithmeticException ae)
{
System.out.println(ae);
System.out.println("please enter data while running the program");
}
catch(ArrayIndexOutOfBoundsException aie)
{
aie.printStackTrace();
System.out.println("please see that array index is with in the range");
}
finally
{
System.out.println("close files");
}
}
}
Output :
6
OOPS USING JAVA UNIT-2
These exceptions are handled with the help of two catch blocks. In the above output, when values are not
passed while running the program one exception had occurred that is ArithmeticException and when we
are passing some values another exception is raising that is,
ArrayIndexOutOfBoundsException. This means even if there is scope for multiple exceptions, only one
exception at a time will occur.
Where the exception must be evaluated to an instance of Throwable class or it may subclasses. The throw
statement in commonly used for user defined exceptions.
class throwtest
{
static void test(Object o)
{
System.out.println(o.toString());
}
static void mythrow()
{
try
7
OOPS USING JAVA UNIT-2
{
throw new NullPointerException("this is done");
}
catch( NullPointerException e)
{
System.out.println("inside my throw");
throw e;
}
}
public static void main(String[] args)
{
try
{
test(null);
}
catch(NullPointerException e)
{
mythrow();
}
}
}
Output :
throws clause :
8
OOPS USING JAVA UNIT-2
Even if the programmer is not handling runtime exceptions, the java compiler will not give any error
related to runtime exceptions.
But the rule is that the programmer should handle checked exceptions.
In case the programmer does not want to handle the checked exceptions, he should throw them out using
throws clause.
Otherwise, there will be an error raised by java compiler.
import java.io.*;
class sample
{
String name;
void accept() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter name");
name = br.readLine();
}
void display()
{
System.out.println("name = "+name);
}
}
class exceptiondemo2
{
public static void main(String[] args) throws IOException
{
sample s = new sample();
s.accept();
s.display();
}
}
Output :
9
OOPS USING JAVA UNIT-2
USER-DEFINNED EXCEPTIONS
10
OOPS USING JAVA UNIT-2
}
catch(OwnException e)
{
System.out.println(e.getMessage());
}
}
}
Output :
MULTITHREADING
11
OOPS USING JAVA UNIT-2
Introduction to Threads:
All programmers are familiar with writing sequential programs. We must have written a program that displays
“hello world” or sorting programs or printing the prime series etc.,,,,
These kind of programs are called as sequential programs. That is each has:-
A beginning
An execution sequence and
An end.
At any given time during the run-time of the program there is a single point of execution.
A thread sometimes called as an execution context or light weight process- is a single sequential flow of
control within a program.
Threads are use to isolate tasks.
Each thread is a sequential flow of control within the same program (browser).
Definition of Thread:
A thread is a single sequential flow of control within a program.
THREAD
PROGRAM
TWO
THREADS
PROGRAM
12
OOPS USING JAVA UNIT-2
In a java program, if we write a group of statements then these statements are executed by JVM one-by-
one. This execution is called a thread, because JVM uses a thread to execute these statements. Thus,
thread represents a separate path of execution of a group of statements.
Creating threads :
Extend thread class: with this technique the new class inherits from the class Thread. The thread can start
running in the run() method of a class.
Implement Runnable interface: this technique is probably more common than extending the Thread
class. It is not required to define a new class to run the thread.
13
OOPS USING JAVA UNIT-2
For example: while sitting before a computer we can perform the following tasks at a time:
All the above mentioned 4 tasks are different from each other. But still we can perform them at a time. This is
nothing but multitasking. That is the processor is allocated for every one of them. This mechanism is also
known as PROCESS-BASED MULTI-TASKING.
Where as in multi-threading, we will be performing different tasks concurrently that are related to one other.
For example: suppose if we are playing a video game say a bike-race game. Then while playing the game we can
be able to see the following activities on the screen:
Main thread
_______________
_______________
_________
The objective of multitasking is to utilize the idle time of the CPU. Think of the CPU as the engine of your
car. Your engine keeps running regardless of whether the car is moving. Your objective is to keep your car
moving as much as possible so you can get the most miles from a gallon of gas. An idling engine wastes
gas.
14
OOPS USING JAVA UNIT-2
The same concept applies to the CPU in your computer. You want your CPU cycles to be processing
instructions and data rather than waiting for something to process. A CPU cycle is somewhat similar to
your engine running.
It may be hard to believe, but the CPU idles more than it processes in many desktop computers. Let’s say
that you are using a word processor to write a document. For the most part, the CPU is idle until you
enter a character from the keyboard or move the mouse. Multitasking is designed to use the fraction of a
second between strokes to process instructions from either another program or from a different part of
the same program.
Making efficient use of the CPU may not be too critical for applications running on a desktop computer
because most of us rarely need to run concurrent programs or run parts of the same program at the same
time. However, programs that run in a networked environment, such as those that process transactions
from many computers, need to make a CPU’s idle time productive.
stop
start
stop Dead
Active Running Runnable
Thread Killed Thread
yield
Suspend Resume
notify stop
sleep wait
(not Runnable)
We created a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled
for running.
15
OOPS USING JAVA UNIT-2
Runnable state:
The runnable state means that the thread is ready for execution and is waiting for the availability of the
processor. That is, the thread has joined the queue of threads that are waiting for execution. If all threads
have equal priority, then they are given time slots for execution in round robin, first-come, first-serve
manner.
If we want a thread to relinquish control to another thread of equal priority before its turn comes, we can
do so by using the yield() method.
Running state:
Running means that the processor has given its time to the thread for its execution. The thread runs until it
relinquishes control on its own or it is preempted by a higher priority thread.
Suspend () method:
A suspended thread can be revived by using the resume () method. This approach is useful when we want to
suspend a thread for some time due to certain reason, but do not want to kill it.
Sleep() method:
We can put a thread to sleep for a specified time period using the method sleep (time) where time is in
milliseconds. This means that the thread is out of the queue during this time period.the thread re-enters the
runnable state as soon as this time period is elapsed.
Notify () method:
It has been told to wait until some event occurs. This is done using the wait () method. The thread can be
scheduled to run again using the notify () method.
Blocked state:
A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state. This happens when the thread is suspended, sleeping , or waiting in order
to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore
fully qualified to run again.
Dead state:
Every thread has a life cycle. A running thread ends its life when is has completed executing its run()
method. We can kill it by sending the stop message to it at any state thus causing a premature death to it.
A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable”
(blocked) condition.
Write a program to find the thread used by JVM to execute the statements
class currentthread
{
public static void main(String[] args)
16
OOPS USING JAVA UNIT-2
{
System.out.println("let us find the current thread");
Thread t = Thread.currentThread();
System.out.println("current thread = "+ t);
System.out.println("it's name = "+ t.getName());
}
}
Output:
In the above program, currentThread() is static method in Thread class. So it is being called with class
name. Then this method gave an object ‘t’ of thread class. When it is displayed its contents are displayed
as : Thread[main,5,main]
Here Thread indicates that ‘t’ is a Thread class object.
First main indicates the name of thread running the current code.
We get 5 which represents the priority of thread. Every thread will have a priority number associated with
it. These priority numbers will be in the range of 1 to 10.
1 is minimum priority………….10 is maximum priority of thread.
Highest priority number thread will be given first preference while execution by JVM.
Default priority number of thread is 5.
The next main indicates the thread group name to which thread belongs to. A thread group represents a
group of threads as a single unit.
Note: The above program indicates that when any program is written in java, JVM internally uses a thread called
“main thread” to run the statements of the program. This thread is responsible for executing our statements and
displaying results.
17
OOPS USING JAVA UNIT-2
The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is declared like this:
Note : run() method is available both in thread class and Runnable interface.
1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An
object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The
Thread object now has a Runnable object that implements the run() method.
3. The start() method is invoked on the Thread object created in the previous step. The start() method returns
immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught
exception.
catch(InterruptedException e)
{
e.printStackTrace();
}
} } }
class MyThread
{
public static void main(String args[])
18
OOPS USING JAVA UNIT-2
{
ThreadDemo2 t1=new ThreadDemo2();
ThreadDemo2 t2=new ThreadDemo2();
1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed
by the thread.
19
OOPS USING JAVA UNIT-2
2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super()
call.
3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread
eligible for running.
t1.start();
}
}
Output:
20
OOPS USING JAVA UNIT-2
When creating threads, there are two reasons why implementing the Runnable interface may be
preferable to extending the Thread class:
Extending the Thread class means that the subclass cannot extend any other class, whereas a class
implementing the Runnable interface
has this option.
A class might only be interested in being runnable, and therefore, inheriting the full overhead of the
Thread class would be excessive.
TERMINATING A THREAD
21
OOPS USING JAVA UNIT-2
import java.io.*;
class mythread extends Thread
{
boolean stop = false;
public void run()
{
for(int i = 1; i<=25; i++)
{
System.out.println(i);
if(stop)
return;
}
}
}
class threddemo
{
public static void main(String[] args) throws IOException
{
mythread obj = new mythread();
Thread t = new Thread(obj);
t.start();
System.in.read();
obj.stop = true;
}
}
Output:
Thread Synchronization
22
OOPS USING JAVA UNIT-2
When a thread is already acting on an object, preventing any other thread from acting on the same object
is called as Thread synchronization or Thread safe.
Thread synchronization is recommended when multiple threads are acting on a single object
Output :
23
OOPS USING JAVA UNIT-2
avaialable berths = 1
1berths reserved forfirst person
avaialable berths = 0
sorry no berths
Inter-thread communication
In some cases it is required that 2 or more threads should communicate with each other.
Example: producer-consumer problem
When producer thread completes the generation of data then only the consumer thread should utilize
that data.
class communicate
{
public static void main(String[] args)
{
producer obj1 = new producer();
consumer obj2 = new consumer(obj1);
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
t2.start();
t1.start();
}
}
class producer extends Thread
{
StringBuffer sb ;
producer()
{
sb = new StringBuffer();
}
public void run()
{
synchronized(sb)
{
for(int i = 1;i<=20;i++)
{
try
24
OOPS USING JAVA UNIT-2
{
sb.append(i+" ");
Thread.sleep(1000);
System.out.println("appending");
}
catch(Exception e)
{
}
}
sb.notify();
}
}
}
class consumer extends Thread
{
producer p;
consumer(producer p)
{
this.p = p;
}
public void run()
{
synchronized(p.sb)
{
try
{
p.sb.wait();
}
catch(Exception e)
{
}
System.out.println(p.sb);
}
}
Output :
appending
appending
.
.
1 2 3 4 5 ……..20
When data generation is completed then sb.notify() statement in producer class sends a message to
wait() in the consumer class which unblocks the consumer class and allows to consume the data.
Some times instead of notify() another method called as notifyAll() has to be used to send an
acknowledgement message to all the waiting threads.
25
OOPS USING JAVA UNIT-2
Difference between sleep() and wait() methods is: that both those methods will block thread temporarily
from execution for some time. When sleep() is executed inside synchronized block, the object is still under
lock. When wait() is executed it breaks the synchronized block so that object is unlocked and available.
Thread priorities:
Each thread will have some priority number assigned to it.
When threads are executed a program called as “thread scheduler” which is a part of JVM will execute the
threads based on their priorities.
Thread with higher priority number will be given first preference for execution.
Thread.MIN_PRIORITY (1)
Thread.MAX_PRIORITY (10)
Thread deadlock: Deadlock describes a situation where two or more threads are blocked forever,
waiting for each other.
26
OOPS USING JAVA UNIT-2
There is no proper solution for avoiding dead lock. While writing program the programmer should take
care that dead lock is to be avoided in the program.
Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread. This
method is defined by Thread, and its general form is shown here:
The isAlive( ) method returns true if the thread upon which it is called is still running. It
returns falseotherwise. While isAlive( ) is occasionally useful, the method that you will more commonly use
to wait for a thread to finish is called join( ), shown here:
This method waits until the thread on which it is called terminates. Its name comes from the concept of the
calling thread waiting until the specified thread joins it. Additional forms of join( ) allow you to specify a
maximum amount of time that you want to wait for the specified thread to terminate.
Daemon thread: is a thread that executes continuously. Daemon threads are service providers for other
threads. It generally provides background processing.
yield() method:
Causes the currently executing thread object to temporarily pause and allow other threads to execute.
Now, it is very likely that your main thread will execute the loop five times before the run method of the new
thread is being executed, so all the calls to yield will happen only after the loop in the main thread is executed.
join will stop the current thread until the thread being called with join() is done executing.
interrupt will interrupt the thread it is being called on, causing InterruptedException.
yield allows a context switch to other threads, so this thread will not consume the entire CPU usage of the process.
27
OOPS USING JAVA UNIT-2
Inside main
Inside main
Inside main
Inside main
Inside main
Inside run
Inside run
Inside run
Inside run
Inside run
28
OOPS USING JAVA UNIT-2
In C-language:
compile-time allocation
int x=10; or
int x;
x=10;
run-time allocation
int x;
scanf(“%d”,&x);
In C++ language:
compile-time allocation
int x=10; or
int x;
x=10;
run-time allocation
int x;
cin>>x;
Also operators like new and delete, malloc and calloc can be used for dynamic memory allocation.
In java also, values can be assigned both at compile time and run time.
Accepting input through key board while executing the program is different in java
To accept input from key board while executing the program we need to use STREAM.
Example:
A stream can carry data from key board to memory; memory to printer; memory to file etc.,,
Similarly in order to move data from one place to other we need to use streams.
All the input stream and output streams are represented by the classes present in java.io package
29
OOPS USING JAVA UNIT-2
Thus, programmer can indicate what type of message he is displaying by using System.out or System.in
To accept the data from key board the steps to be followed are:
Now the environment has been set up to accept the values from key board
read() and readLine() methods are present in buffered reader class so input stream reader class should be
connected to buffered reader class.
30
OOPS USING JAVA UNIT-2
import java.io.*;
class chardemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a character");
char ch = (char) br.read();
System.out.println("entered character is " +ch);
}
}
Output
Even if we enter a string read() accepts only a character (first character of that string) see the below
output:
31
OOPS USING JAVA UNIT-2
import java.io.*;
class chardemo1
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a character");
int ch = br.read();
System.out.println("entered character is " +ch);
}
}
Output
import java.io.*;
class stdemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a string");
String ch = br.readLine();
System.out.println("entered character is " +ch);
}
}
Output
32
OOPS USING JAVA UNIT-2
except characters all other values will be treated as strings only..in java
so other values integers also should be type casted. But string is a class and it can’t be type casted just like
a normal data type
all basic data types are classes in java. So those classes and static methods present in them are to be used
to convert variables into a particular data type.
Example: Integer is a class.. parseInt is a static method in that class which converts any data type into
integer.
PROGRAM TO ACCEPT AN INTEGER FROM KEYBOARD
import java.io.*;
class intdemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter aa integer");
int ch = Integer.parseInt(br.readLine());
System.out.println("entered integer is " +ch);
}
}
Output
Double.parseDouble
Float.parseFloat
Byte.parseByte etc.,,,,
33
OOPS USING JAVA UNIT-2
STRING HANDLING
Strings, which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
In c and c++ string is a collection of characters that is terminated by a Null character. But it is not valid in
java.
In java, string which is declared is an object of String class. It is not a character array.
String class is a part of java.lang package, where all the necessary methods o work on strings are
available.
String class is a part of java.lang package but in java all classes can be considered as data types. So String
can be taken as a object. ( since, class is nothing but a user-defined data type)
Here we are converting string into character array. After the above declaration now create a string object
We can create an object to string class by allocating memory using new operator . this is similar to
creating an object to a class. In the above declaration first object is being declared the value is being
stored into it.
OPERATIONS ON STRINGS
1. Length of string : counts number of characters.
class string
{
public static void main(String[] args)
{
String s1= "wel come";
System.out.println(s1.length());
// output : 8 (white space is also counted )
} }
class string2
{
public static void main(String[] args)
{
String s1= "welcome";
34
OOPS USING JAVA UNIT-2
System.out.println( s1+ s2 );
// ouput : welcometo java lab
}
}
3. Replace
class string3
{
public static void main(String[] args)
{
String s1= "welcome";
System.out.println( s1.replace('c','k'));
//output : welkome
}
}
4. Comparision
class string4
{
public static void main(String[] args)
{
String s1= "welcome";
String s2 = "to java lab";
System.out.println( s3 .equalsIgnoreCase(s4));
//output : true
}
}
5. trim : this method is used to remove white spaces on either sides of given string. If white spaces are
present in between string then they cannot be removed.
35
OOPS USING JAVA UNIT-2
class string4
{
public static void main(String[] args)
{
String s3= " welcome ";
}
}
6. charAt : this method specifies the character at that particular position in a given string. Counting starts
from 0.
class string5
{
public static void main(String[] args)
{
String s4= "welcome to java lab";
System.out.println(s4.charAt(5)); //output : m
System.out.println(s4.charAt(8));//output: t
}
}
class string5
{
public static void main(String[] args)
{
String s4= "welcome to java lab";
System.out.println(s4.toUpperCase());
//output : WELCOME TO JAVA LAB
System.out.println(s5.toLowerCase());
//output :welcome to java lab
}
}
36
OOPS USING JAVA UNIT-2
8. indexOf : this method is used to find the position of first character in a given string.
class string5
{
public static void main(String[] args)
{
String s5= "welcome to java lab";
System.out.println(s5.indexOf("t")); //output : 8
System.out.println(s6.indexOf("n"));// output : -1
//If nothing is found then negative value is returned
}
}
9. lastIndexOf : prints position of last character in given string. If nothing is found it also returns negative
value. It returns the position of last occurrence of character in the given string.
class string5
{
public static void main(String[] args)
{
String s6= "madam";
System.out.println(s6.lastIndexOf("m")); //output : 4
}
}
10. substring : this method is useful to extract a part of the string from actual string.
class string5
{
public static void main(String[] args)
{
String s6= "this is notes on strings";
}
}
11. getChars : this method copies characters from a string into character array.
37
OOPS USING JAVA UNIT-2
class string6
{
public static void main(String[] args)
{
String s6= "this is notes on strings";
char a[ ] = new char [15];
s6.getChars(2,10,a,0);
System.out.println(a); // is is no
}
}
12. split : this method is useful to break a string into pieces a places represented by delimiter. Te resultant
pieces are returned into string type array. Suppose if delimiter is comma then string is cut into pieces
where ever comma occurs in the string.
class stringg
{
public static void main(String[] args) Ouput :
{
String s=" this is, ja,va lab"; this is
String str[ ];
str = s.split( "," ); java lab
for(int i=0;i<str.length;i++)
{
System.out.println(str[i]);
}
}
}
IMMUTABILITY OF STRINGS
class str
{
public static void main(String[] args)
{
String s1="hello";
String s2="world";
s1=s1+s2;
System.out.println(s1); // hello world
}
38
OOPS USING JAVA UNIT-2
s1=s1+s2; using this statement we are modifying the contents of string object s1. String objects are
immutable. If it is true then why the output is hello world instead of hello.?
Reason:
Java Virtual machine creates 2 objects s1 and s2 separately
s1 hello
s2world
when s1+s2 is written JVM creates a separate location to store the content of s1+s2.
(s1+s2) hello world
But the content of s1 is not modified. Instead the location to which s1 is pointing to is changed but not
the content. The old object’s reference contains hello and now it as lost its reference. It is said to be
unreferenced object. It will be removed by garbage collector from memory.
whenever we are creating a string object we are creating a string that cannot be changed.
That is once string object is created it cannot be modified. But all kinds of string operations can
be performed.
The difference is :- whenever a modification is made to string that modified string should be
assigned to a new string object.
The original string is left unchanged.
This approach is used because fixed strings can be implemented more efficiently than changed
one’s.
If in some cases the original string has to be modified then java has 2 options :-
String Buffer & String Builder. Both o them can hold strings that are modified after creation.
Since both of them part of java.lang package they are automatically available to all java
programs
For this purpose there are several methods available in string buffer class.
Objects can be created for string buffer class in the following way :
Note : we may or may not mention size of stringbuffer object but it can be expanded dynamically
( since it is mutable).
39
OOPS USING JAVA UNIT-2
1. append(): this method concatenates the string representation of any other type with the string
buffer object.
class stringbuffer
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("hello");
System.out.println(s.append("12345")); // output : hello12345
}
}
2. insert() : this method inserts one string into another string from the specified position.
class stringbuffer1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("java lab");
StringBuffer s2 =s1.insert(5, "programming");
System.out.println(s1); // output : java programming lab
}
}
class stringbuffer2
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("welcome");
s1.reverse();
System.out.println(s1); // output : emoclew
}
}
4. delete(int i, int j): this method deletes characters in a string from position ‘i’ to ‘j-1’.
class stringdelet
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("department");
System.out.println(s.delete(1,4)); // output : drtment
}
}
class LengthCapacity
40
OOPS USING JAVA UNIT-2
{
Output :
public static void main(String args[])
{
Length of sb1 = 0
StringBuffer sb1 = new StringBuffer(); Length of sb2 = 9
StringBuffer sb2 = new StringBuffer("ObjectOne"); Capacity of sb1 = 16
System.out.println("Length of sb1 = "+sb1.length()); Capacity of sb2 = 25
System.out.println("Length of sb2 = " +sb2.length());
System.out.println("Capacity of sb1 = "+sb1.capacity());
System.out.println("Capacity of sb2 = "+sb2.capacity());
}
}
THE TOPICS Reading and Writing Files, Print Writer Class WILL
BE DISCUSSED AS PART OF UNIT-5
41