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

Chapter - 3 Exception Handling - Multithreaded Programming

The document covers Java exception handling, multithreading, file handling, and string handling. It explains the types of exceptions, the consequences of uncaught exceptions, and the mechanisms for handling exceptions using try-catch blocks. Additionally, it discusses multithreading concepts, thread lifecycle, synchronization, and file operations with examples and code snippets.

Uploaded by

killaflamepyro
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 views36 pages

Chapter - 3 Exception Handling - Multithreaded Programming

The document covers Java exception handling, multithreading, file handling, and string handling. It explains the types of exceptions, the consequences of uncaught exceptions, and the mechanisms for handling exceptions using try-catch blocks. Additionally, it discusses multithreading concepts, thread lifecycle, synchronization, and file operations with examples and code snippets.

Uploaded by

killaflamepyro
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

Java & Internet Technology Prepared By: Prof.

Shital Pathar

Chapter – 3 Exception Handling ,Multithreading ,


File Handling ,String Handling

1. What is Exception.Explain types of exceptios.


2. Explain what happens when we don’t handle the exceptions? OR Explain uncaught exceptions.
3. Explain Exception handling mechanism with try and catch.
4. Explain multiple catch block with example.
5. Explain unreachable catch block.
6. Explain nested try statement.
7. Explain throw with example.
8. Explain throws with example.
9. Explain finally with example.
10. Explain thread.
11. Explain multithreading and life cycle of thread.
12. List thread class and its methods.
13. How to create thread?
14. Define sleep() method and write program for multithreading .
15. Write a program that executes two threads. One thread will print the even numbers and another thread
will print odd numbers from 1 to 10.
16. Explain thread priorities with ex.
17. What is synchronization ? Explain synchronized block and method.
18. Exception handling in Thread.
19. What is File and File Handling in java.
20. Explain basics of stream classes.
21. Write a program to perform write operation on the text file.
22. Write a program to perform read operation from the text file.
23. What is String class in java?
24. Write a program to copying one file to other .
25. Explain String operation or method in java.
26. What is StringBuffer class in java and define method of StringBuffer class.

1. What is Exception? Explain types of exceptios.

 An exception (or exceptional event) is a problem that arises during the execution of a program.
 When an Exception occurs the normal flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore these exceptions are to be handled.
 An exception is an abnormal condition that arises in a program at run time. In other words, an exception is a
run-time error
 When an exception is occurred , creates an exception object and then the normal flow of the program halts and
JRE tries to find someone that can handle the raised exception.
 The exception object contains a lot of debugging information such as method hierarchy, line number where the
exception occurred, type of exception etc. When the exception occurs in a method, the process of creating the
exception object and handing it over to runtime environment is called “throwing the exception”.
 All exception types are subclasses of a class Throwable. Thus, Throwable is at the top of the exception class
hierarchy.

Parul Institute Of Engineerring & Technology(CSE Department) Page 1


Java & Internet Technology Prepared By: Prof. Shital Pathar

Throwable

Exception Error

RuntimeException

 There are two subclasses of Throwable : Exception and Error.


 Exception class is used for exceptional conditions that user programs should catch. This is also the class that
you will subclass to create your own custom exception types. There is an important subclass of Exception,
called RuntimeException. Exceptions of this type are automatically defined for the programs that you write
and include things such as division by zero and invalid array indexing.
 Error class defines exceptions that are not expected to be caught under normal circumstances by your
program. Exceptions of type Error are used by the Java run-time system. Stack overflow is an example of
such an error.

 Types of Exception:
 There are mainly three types of exceptions

1.Checked Exception.
2.Unchecked Exception.
3.Error.

1.Checked Exception.
 A checked exception is an exception that occurs at the compile time, these are also called as compile time
exceptions. .The exception that can be predicated by the programmer falls under this category.
 For example, File that needs to be opened is not found.

Exception(class) Meaning
ClassNotFoundException A class can not found.
IllegalAccessException An illegal access to a class was attempted
InterruptedException A thread has been interrupted.
NoSuchFieldException A requested field does not exist
NoSuchMethodException A requested method does not exist

2.Unchecked Exception.
 An Unchecked exception is an exception that occurs at the time of execution, these are also called as Runtime
Exceptions, these include programming bugs, such as logic errors or improper use of an API. runtime
exceptions are ignored at the time of compilation.
 For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the
array .
Exception(class) Meaning
ArithmeticException Such as divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds

Parul Institute Of Engineerring & Technology(CSE Department) Page 2


Java & Internet Technology Prepared By: Prof. Shital Pathar
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.

3.Unrecoverable error.
 These are not exceptions at all, but problems that arise beyond the control of the user or the programmer.
 Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a
stack overflow occurs, an error will arise. This type of error is not possible to handle in code.

2.Explain what happens when we don’t handle the exceptions? OR Explain uncaught exceptions.

 When the Java run-time system detects the exception like divide by zero, it constructs a new exception object
and then throws this exception.
 This exception must be caught by an exception handler. If we don’t define handler in our program then the
exception is caught by the default handler provided by the Java run-time system.
 The default handler displays a string describing the exception, prints a stack trace from the point at which the
exception occurred, and terminates the program.
 If we define exception handler in our program then exception is handle by our program and appropriate
message is displayed on the screen.
 Ex:
class uncaught
{
public static void main(String args[])
{
int a=0;
int b=7/a;
}
}
 Output:Exception in thread "main" java.lang.ArithmeticException: / by zero at uncaught.main(a.java:6)

 As we don’t any mechanism for handling exception in the above program,so this will lead to an exception at
runtime and the java run-time system will construct an exception and then throw it.
 Then the default handler will handle the exception and will print the details of the exception.

3.Explain Exception handling mechanism with try and catch.

Parul Institute Of Engineerring & Technology(CSE Department) Page 3


Java & Internet Technology Prepared By: Prof. Shital Pathar
 Exception handling is the mechanism to handle runtime problems. We need to handle such problems to prevent
abnormal termination of program. So Exception handling mechanism minimizes the chances of a system crash
 Exception handling mechanism provides more specific information about program errors to user.
 Exception Handling is done by transferring the execution of a program to an appropriate exception handler
when exception occurs.
 Exception handler is a block of code to handle thrown exception. If program recover exception then program
can resume executing after the exception handler has executed.
 Exception handling is done using five keywords, try ,catch,throw,throws,finally.

 try block contains program statements those may generate errors. It means write the code that you want to
monitor inside a try block.
 After try block,include a catch block that specify exception type that you wish to catch.It means catch block
defines a block of statements to handle the generated exception inside the try block.
 If an exception occurs in try block ,the catch block that follows the try is checked,if the type of exception that
occurred match with the catch block then the exception is handed over to the catch block which then handles
it.

 structure of an exception-handling block


try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
 Here, ExceptionType is the type of exception that has occurred.
 exOb is object.

 Example:
class Exc2
{
public static void main(String args[])
{
int b=0, a=5;
try
{
System.out.println("sum=”+(a+b));
System.out.println("sub=”+(a-b));
System.out.println("div=”+(a/b));
}
catch (ArithmeticException e)
{
System.out.println("system message"+e.getMessage());
System.out.println("user message : divided by zero”);

Parul Institute Of Engineerring & Technology(CSE Department) Page 4


Java & Internet Technology Prepared By: Prof. Shital Pathar
}
}
}
 Output:
system message/ by zero
user message : divided by zero

4. Explain multiple catch block with example.

 In some cases ,more than one Exception may be generated in try{} block .To handle this type of situation ,you
can specify two or more catch{} block.
 Each catch{} block contain different type of exception. If an exception occurs in the try{} block, the exception
is passed to the first catch{} block in the list.
 If the exception type matches with the first catch{ }block it executed otherwise it is passed down to the next
catch{} block.
 After one catch{} stat. executes ,the others are bypassed.
 structure
try
{
// block of code to monitor for errors.
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb1)
{
// exception handler for ExceptionType2
}

 Example:
class Exc2
{
public static void main(String args[])
{
try
{
int a=args.length;
System.out.println("a=”+a);
int b=6/a;
int arr[]={1,2,3};
arr[5]=8;
}
catch (ArithmeticException e)
{
System.out.println("user message : divided by zero”);
}

Parul Institute Of Engineerring & Technology(CSE Department) Page 5


Java & Internet Technology Prepared By: Prof. Shital Pathar
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("array index out of bound”);
}

}
}
 Output: e:>java Exc2
a=0
user message : divided by zero
e:>java Exc2 hello
a=1
array index out of bound

5. What is unreachable catch block.

 When you use multiple catch{} statements, It is important that exception subclasses must come before any of
their superclasses.
 This is because a catch{} statement that uses a superclass will catch exceptions of that type plus any of its
subclasses.
 Thus a subclass would never be reached if it came after its superclass.
 Example:
class Exc2
{
public static void main(String args[])
{
try
{
int a=args.length;
System.out.println("a=”+a);
int b=6/a;
int arr[]={1,2,3};
arr[5]=8;
}
catch (Exception e)
{
System.out.println("user message : divided by zero”);
}
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("array index out of bound”);
}
}
}
 Output: compilation error : exception java.lang. ArrayIndexOutOfBoundsException has already been caught

Parul Institute Of Engineerring & Technology(CSE Department) Page 6


Java & Internet Technology Prepared By: Prof. Shital Pathar
6. Explain nested try{} blocks.

 The try{} block can be nested.That is try{} block can be inside the block of another try{}.
 Nested try{} block is used when a part of a block may cause one error while entire block may cause another
error.
 In case if inner try{} block does not have a catch handler for a particular exception then the outer try{} block
catch handlers are inspected for a match.

 Example:
class Exc2
{
public static void main(String args[])
{
try
{
int arr[]={0,2,3};
try
{
int a= 2/0;
}
catch (ArithmeticException e)
{
System.out.println("user message : divided by zero”);
}
arr[4]=5;
}
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("array index out of bound”);
}
}
}
 Output: user message : divided by zero
array index out of bound

7. Explain throw() .

 when an exception condition occurs the system automatically throw an exception to inform user that there is
something wrong. However we can also throw exception explicitly based on our own defined condition.
 In Java throw keyword is used to explicitly throw an exception. The flow of execution stops immediately after
the throw statement.
 syntax throw Throwableinstance;
 Throwableinstance must be an object of type Throwable or a subclass of Throwable .only object of Throwable
class or its subclasses can be thrown.

 creating instance of Throwable class:


 syntax: classname instancename =new classname(“msg”);

Parul Institute Of Engineerring & Technology(CSE Department) Page 7


Java & Internet Technology Prepared By: Prof. Shital Pathar
 EX: Throwable t1 = new Throwable(“error”);
 syntax: throw new classname(“msg”);
 EX: throw new ArithmeticException(“error”);

 Example1:
class Exc2
{
public static void main(String args[])
{
Throwable t1=new Throwable(“error”);
try
{
System.out.println("exception is thrown”);
throw t1;
}
catch (Throwable e)
{
System.out.println("exception here : “+e);
}
}
}
 Output: exception is thrown
exception here : error

 Example2:

class Exc2
{
void validate(int age)
{
try
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
catch (ArithmeticException e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
Exc2 e1=new Exc2();
e1.validate(13);
}

Parul Institute Of Engineerring & Technology(CSE Department) Page 8


Java & Internet Technology Prepared By: Prof. Shital Pathar
}
 Output: java.lang.ArithmeticException: not valid

8. Explain throws() .

 The Java throws keyword is used to declare an exception.


 It gives an information to the programmer that there may occur an exception so it is better for the programmer
to provide the exception handling code so that normal flow can be maintained.
 Any method capable of causing exceptions must list all the exceptions possible during its execution, so that
anyone calling that method gets a prior knowledge about which exceptions to handle.
 syntax method_type methodname(parameterlist) throws exception1,exception2,….. ,exception n
{
//body;
}

 Example:

class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
public static void main(String args[])
{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}

 Output: java.lang.ArithmeticException: not valid

9. Explain finally().

 Sometimes we have situations when a certain piece of code must be executed, no matters if try block is
executed successfully or not, this is done by a ‘finally’ block .
 It means “finally” is a keyword that executes a block of statements regardless of whether any exception is
generated or not.
 A ‘finally’ block is written followed by a try block or a catch block, code written inside a finally block is
always executed.

Parul Institute Of Engineerring & Technology(CSE Department) Page 9


Java & Internet Technology Prepared By: Prof. Shital Pathar

 Using a finally block you can execute any cleanup type statements ,return resources to the system ,and execute
other statements like closing file,closing the connection established with database etc..

 Example:

class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
 Output: finally block is always executed

10. Explain thread.

 Process:
 Process is part of computer program that is executed sequentially.

 Thread:
 Thread is lightweight subprocess , a smallest unit of processing.It is a seprate path of execution.

Parul Institute Of Engineerring & Technology(CSE Department) Page 10


Java & Internet Technology Prepared By: Prof. Shital Pathar
 Threads are independent ,if exception occurs in one thread ,it doesn’t affect other threads.It share common
memory area.
 Threading is a facility to allow multiple activities to coexist within a single process. Every Java program has at
least one thread -- the main thread. When a Java program starts, the JVM creates the main thread and calls the
program's main() method within that thread.
 The JVM also creates other threads that are mostly invisible to you for example, threads associated with
garbage collection, object finalization.

Thread1
Process2

Thread2
Thread3

Process3

OS
 Thread is executed inside the process.There is context switching between the threads.
 There can be multiple processes inside the OS and one process can have multiple threads.

Process Thread
Processes are heavy weight tasks. Threads are light weight tasks.
Processes requires their own separate address space. Threads share same address spaces.
Context switching from one process to other is costly. Context switching from one thread to other is cheap
compared to process.
Interprocess communication is costly and limited Interthread communication is cheap.
Multitasking processes requires more overhead. Multitasking threads requires less overhead.

11. Explain multithreading and life cycle of thread

 Java is a multi threaded programming language which means we can develop multi threaded program using
Java. Multithreading in java is a process of executing multiple threads simultaneously.
 It means Multithreaded program contains two or more parts that can run simultaneously. For ex. One thread is
writing content on a file at the same time another thread is performing spelling check.
 So single program can perform two or more tasks simultaneously.
 Multithreading enables you to write very efficient programs that make maximum use of the CPU.

 Life cycle of thread:

 There are some states while executing a thread . We define main five states in thread life cycle in java .
 new, runnable, running,blocked, terminated.
 The life cycle of the thread in java is controlled by JVM.

Parul Institute Of Engineerring & Technology(CSE Department) Page 11


Java & Internet Technology Prepared By: Prof. Shital Pathar

new start() runnable


resume()

yield() dispatch blocked

terminated
thread
completed running sleep

 New
 The thread is in new state if you create an instance of Thread class but before the call of start() method.It
means thread was created but has not started.

 Runnable
 When we call start() function on Thread object, it’s state is changed to Runnable. In this state The Thread
scheduler decides which thread runs and how long. but the scheduler has not selected it to be the running
thread.

 Running
 If a Thread is executing that means Thread is in Running stage.

 Blocked
 This is the state when the thread is still alive, but is currently not run.

 Terminated
 Once the thread finished executing, it’s state is changed to terminate and it’s considered to be not alive. when
its run() method exits , Thread reached in terminated state,means it can not run again.

12. List thread class and its methods.

 Java’s multithreading system is built upon a Thread class, its methods. and its interface Runnable.
 Some methods of Thread class are as below.

getName() Give thread’s name


setName() change a name of the thread
run() Entry point for the thread
sleep() suspend a thread for a period of time
isAlive() determine whether thread is running or not
join() wait for a thread to terminate
getPriority() give thread’s priority

Parul Institute Of Engineerring & Technology(CSE Department) Page 12


Java & Internet Technology Prepared By: Prof. Shital Pathar
setPriority() change priority of thread
suspend() suspends all processes of thread
resume() to resume the execution of suspended thread
stop() stops all processes in the thread.

13. How to create thread?

 There are two ways to create a thread:.


1. Extending java.lang.Thread class
2. Implementing java.lang.Runnable Interface.

extends implements
Thread

Thread (class) Runnable(interface)

 To execute a thread, first thread is created, then


 start() method is invoked on the thread. start() method starts the execution of the thread.JVM calls the run()
method on the thread.
 run() method is used to perform action for a thread.

1. Extending java.lang.Thread class

 For creating thread follow this step:

 create class which extends the java.lang.Thread class.


 write run() method in the subclass from the Thread class .In that we define the code executed by the Thread.
 Create object of this subclass.you may call Thread class constructor by subclass constructor.
 invoke the start() method on the object of the class ,to run thread .

 WAP to create single thread

class display extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
display t1=newdisplay();
t1.start();
}
}
 output: thread is running

Parul Institute Of Engineerring & Technology(CSE Department) Page 13


Java & Internet Technology Prepared By: Prof. Shital Pathar
2. implementing java.lang.Runnable Interface.

 For creating thread follow this step:

 create class which implements the java.lang.Runnable interface.


 write run() method in this class and create object of this class .object of this class is Runnable object.
 create object of Thread class by passing Runnable object as argument.
 invoke the start() method on the object of the thread class.

 WAP to create single thread

class display implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
display t1=new display();
Thread t2=new Thread(t1);
t2.start();
}
}
 output: thread is running

14. Define sleep() method and write program for multithreading.

 The sleep() method of Thread class is used to sleep a thread for specified amount of time.
 Syntax: sleep( milliseconds)
 it throw InterruptedException type exception.

class Test extends Thread


{
public void run()
{
for(int i=1;i<5;i++)
{
System.out.println(i);
}
}

Parul Institute Of Engineerring & Technology(CSE Department) Page 14


Java & Internet Technology Prepared By: Prof. Shital Pathar
public static void main(String args[])throws InterruptedException
{
Test m1=new Test();
Test m2=new Test();
m1.start();
sleep(2000);
m2.start();
sleep(2000);
}
}
output: 1
2
3
4
1
2
3
4

15. Explain thread priorities with ex.

 Each thread have a priority. Priorities are represented by a number between 1 and 10.
 In most cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

 There are three constants defined in Thread class:


 Thread.MIN_PRIORITY :The minimum priority of any thread.( value =1)
 Thread.MAX_PRIORITY : The maximum priority of any thread.( value =10)
 Thread.NORM_PRIORITY : The normal priority of any thread.( value =5).This is default priority.

 Methods:
setPriority : It is used to set the priority of thread.
getPriority : It is used to get the priority of thread.

 WAP to demonstration of thread priorities.

class Test extends Thread


{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[])
{
Test m1=new Test();

Parul Institute Of Engineerring & Technology(CSE Department) Page 15


Java & Internet Technology Prepared By: Prof. Shital Pathar
Test m2=new Test();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
 output: running thread name is:Thread-0
running thread priority is:1
running thread name is:Thread-1
running thread priority is: 10

16. Write a program that executes two threads. One thread will print the even numbers and another thread
will print odd numbers from 1 to 10.

 first method:

class thread2 extends Thread


{
int n;
thread2(String nm,int n1)
{
super(nm);
this.n=n1;
}
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(getName() + "\t" +this.n);
this.n=this.n+2;
}
}
public static void main(String args[])
{
thread2 t1 = new thread2("thread1", 1);
thread2 t2 = new thread2("thread2", 2 );
t1.start();
t2.start();
}
}

 output:
thread1 1
thread1 3

Parul Institute Of Engineerring & Technology(CSE Department) Page 16


Java & Internet Technology Prepared By: Prof. Shital Pathar
thread1 5
thread1 7
thread1 9
thread2 2
thread2 4
thread2 6
thread2 8
thread2 10
 second method:

class thread2 extends Thread


{
int n;
thread2(int n1)
{
this.n=n1;
}
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(getName() + "\t" +this.n);
this.n=this.n+2;
}
}
public static void main(String args[])
{
thread2 t1 = new thread2( 1);
thread2 t2 = new thread2( 2 );
t1.start();
t2.start();
}
}
 output:
Thread-0 1
Thread-1 2
Thread-1 4
Thread-1 6
Thread-1 8
Thread-1 10
Thread-0 3
Thread-0 5
Thread-0 7
Thread-0 9

17. What is synchronization? Explain synchronized block and method.

Parul Institute Of Engineerring & Technology(CSE Department) Page 17


Java & Internet Technology Prepared By: Prof. Shital Pathar
 In java while working with multiple threads, it may be possible that more than one thread share the same data
at a time. For ex. one thread read data when other thread tries to change it. This might generate error in result.
 In this case ,it is necessary to allow one thread to finish its task completely and then allow next thread to
execute. So thread Synchronization to allows a programmer to control threads that are sharing data.
 When two or more threads need access to share data, thread synchronization ensure that ,the data will be used
by only one thread at a time. To avoid this problem ,java uses monitor also known as “semaphore” to prevent
data from being loss by multiple threads.
 synchronization is mechanism which allows two or more threads to share all the available resources in a
sequential manner.
 java use synchronized keyword to ensure that only one thread is in a critical region. critical region is area
where only one thread is run at a time. once thread is in its critical region ,no other thread can enter to that
critical region. In this case ,another thread will has to wait until the current thread leaves its critical region.

 There are two ways to synchronized the execution of code.:


 Synchronized methods
 Synchronized blocks(statements).

 Synchronized methods:

 If you declare any method as synchronized, it is known as synchronized method.


 Synchronized method is used to lock an object for any shared resource.
 When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it
when the thread completes its task.

 WAP to demonstration of Synchronized methods .

class display
{
synchronized void show()
{
int i=0;
while(i<4)
System.out.println( i++ );
}
}
class mythread extends Thread
{
display d;
mythread(display d1)
{
d=d1;
}
public void run()
{
d.show();
}
public static void main(String args[]) throws InterruptedException

Parul Institute Of Engineerring & Technology(CSE Department) Page 18


Java & Internet Technology Prepared By: Prof. Shital Pathar
{
display m1 = new display();
mythread t1=new mythread(m1);
mythread t2=new mythread(m1);
t1.start();
t2.start();
}
}

 output: with synchronized method without synchronized method

0 0
1 0
2 1
3 1
0 2
1 2
2 3
3 3

 Synchronized block:

 Synchronized block can be used to perform synchronization on any specific resource of the method.
 Suppose you have 50 lines of code in your method,but you want to synchronize only 5 lines, you can use
synchronized block.

 WAP to demonstration of Synchronized block .

class display
{
void show()
{
int i=0,i1=0;
while(i<4)
System.out.println( "thread name" + i++ );
synchronized(this)
{
while(i1<2)
{
System.out.println( i1 );
i1++;
}
}
}
}
class mythread extends Thread

Parul Institute Of Engineerring & Technology(CSE Department) Page 19


Java & Internet Technology Prepared By: Prof. Shital Pathar
{
display d;
mythread(display d1)
{
d=d1;
}
public void run()
{
d.show();
}
public static void main(String args[]) throws InterruptedException
{
display m1 = new display();
mythread t1=new mythread(m1);
mythread t2=new mythread(m1);
t1.start();
t2.start();
}
}
 output

thread name0
thread name0
thread name1
thread name1
thread name2
thread name2
thread name3
thread name3
0
1
0
1

18. Exception handling in Thread.

 All uncaught exception are handled by code outside of the run() method before the thread terminates.
 But when an unchecked exception is thrown inside the run() method of a Thread object, the default behavior
is to write the stack trace in the console (or log it inside error log file) and exit the program.
 It is possible for a program to write a new default exception handler.
 Java provides us with a mechanism to catch and treat the unchecked exceptions thrown in a Thread object to
avoid the program ending. This can be done using UncaughtExceptionHandler.
 The default exception handler is the uncaught Exception() method of the Thread class. it is called when
exception is thrown from the run() method.

UncaughtExceptionHandler defined three level(Three methods)

Parul Institute Of Engineerring & Technology(CSE Department) Page 20


Java & Internet Technology Prepared By: Prof. Shital Pathar
 1. Thread.setDefaultUncaughtExceptionHandler():
 This method of Thread class can be used to provide a common exception handler for all the threads.
 2. Thread.setUncaughtExceptionHandler():
 This non static method of thread class which is used to provide handler to a Individual thread.
 3. ThreadGroup.UncaughtException():
 This method of Thread class can be used to provide a common exception handler for particular thread group.

 WAP to demonstration of Exception Handling in Thread .

import java.lang.*;
class thread2 extends Thread
{
public void run()
{
System.out.println(10/0);
throw new RuntimeException();
}
public static void main(String[] args)
{
thread2 t=new thread2();
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
System.out.println("error in " + t.getName() +e);
}
});
t.start();
}
}
}
 output: error in Thread-0 java.lang.ArithmeticException: / by zero

19. What is File and File Handling in java.

 File is a collection of bytes stored in secondary storage device i.e. disk. Thus, File handling is used to read,
write, append or update a file without directly opening it.
 Types of File:
 Text File
 Binary File
 Text File contains only textual data. Text files may be saved in either a plain text (.TXT) format and rich text
(.RTF) format like files in our Notepad while Binary Files contains both textual data and custom binary data
like font size, text color and text style etc.

 File Handling
 The input and output operation that we have performed so far were done through screen and keyboard only.
After the termination of program all the entered data is lost because primary memory is volatile.

Parul Institute Of Engineerring & Technology(CSE Department) Page 21


Java & Internet Technology Prepared By: Prof. Shital Pathar
 If the data has to be used later, then it becomes necessary to keep it in permanent storage device.
 So the Java language provides the concept of file through which data can be stored on the disk or secondary
storage device. The stored data can be read whenever required.

20. Explain basics of stream classes.

 A stream is sequence of data.In java a stream is made of bytes.streams are pipelines for sending and receiving
information in java programs.
 When a stream of data is sent or received ,it is referred as writing and reading a streamClass.It is called a
stream because it’s like stream of water that continues to flow.
 In java, 3 streams are created for us automatically.
 1) System.out: standard output stream
 2) System.in: standard input stream
 3) System.err: standard error stream
 java uses streams to handle I/O operations through which the data is flowed from one location to another.
 The java Input/Output is a part of java.io package.

 InputStream : Java application uses an input stream to read data from a source, it may be a file,an
array,peripheral device or socket.Input stream is automatically opened when you create it.

 OutputStream : Java application uses an output stream to write data to a destination, it may be a file,an
array,peripheral device or socket.Output stream is automatically opened when you create it.

InputStream And OutputStream

 InputStream Methods:
 read(): it reads bytes of data from a stream
 available(): this method returns the number of available bytes that can be read.
 close(): it closes the input stream.
 skip():it skips n bytes of input.

 OutputStreamMethods:
 write(): it writes a byte.
 available(): this method returns the number of available bytes that can be write.
 close(): it closes the output stream.
 flush():it flushes the stream. The buffered data is written to the Output stream.

Parul Institute Of Engineerring & Technology(CSE Department) Page 22


Java & Internet Technology Prepared By: Prof. Shital Pathar

 InputStream class
 InputStream class is an abstract class.It is the superclass of all classes representing an input stream of bytes.

 OutputStream class
 OutputStream class is an abstract class.It is the superclass of all classes representing an output stream of bytes.

21. Write a program in java to create a text file.

 Java File class represents the files and directory. This class is used for creation of files and directories, file
searching, file deletion, etc.
 createNewFile()The java.io.File.createNewFile() method atomically creates a new file named by this abstract
path name and return a boolean value :true or false.
 true if the file is created successful; false if the file is already exists or the operation failed.

Parul Institute Of Engineerring & Technology(CSE Department) Page 23


Java & Internet Technology Prepared By: Prof. Shital Pathar

import java.io.File;
class FileDemo
{
public static void main(String[] args)
{
boolean bool = false;
try
{
File f = new File("test.txt");
bool = f.createNewFile();
System.out.println("File created: "+bool);
}
catch(Exception e)
{
System.out.println("error”);
}
}
}
 output: file created true

22. Write a program to perform write operation on the text file.

 FileOutputStream class is output stream for writing data to a file.It write data as a form of bytes.For writing
characters use FileWriter.

import java.io.*;
class Test
{
public static void main(String args[])
{
try
{
FileOutputStream fout = new FileOutputStream("abc.txt");
String s="Hello";
byte b[]=s.getBytes(); //converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}
catch(Exception e)
{
system.out.println(e);
}
}
}

Parul Institute Of Engineerring & Technology(CSE Department) Page 24


Java & Internet Technology Prepared By: Prof. Shital Pathar
 output: success

23. Write a program to perform read operation from the text file.

 FileInputStream class is input stream for reading data from a file.It read data as a form of bytes. For reading
characters use FileReader.


import java.io.*;
class Test
{

public static void main(String args[])


{
try
{
FileInputStream fin=new FileInputStream("abc.txt");
int i;
while(i=fin.read())!=-1)
System.out.println((char)i);
fin.close();
System.out.println("success...");
}
catch(Exception e)
{
system.out.println(e);
}
}
}
 output: success

24. Write a program to copying one file to other .

import java.io.*;
class Test
{
public static void main(String args[])
{
try
{
FileOutputstream fout=new FileOutputStream("abc1.txt");
FileInputstream fin=new FileInputStream("abc.txt");
int i=0;
while(i=fin.read())!=-1)
fout.write(i);

Parul Institute Of Engineerring & Technology(CSE Department) Page 25


Java & Internet Technology Prepared By: Prof. Shital Pathar
fin.close();
System.out.println("success...");
}
catch(Exception e)
{
system.out.println(e);
}
}
}
 output: success

25. What is String class in java?

 Generally string is a sequence of characters enclosed within double quotes ex. “java” ,”123”
 But in java string is an object. String class is used to create String object.
 String objects are stored in a special memory area known as string constant pool inside the Heap memory.
 In java strings are immutable it means unmodifiable or unchangeable.
 Once string object is created its data or state can not be changed but a new string object is created.

o Creation:
1.Using string literal
2.Using new keyword

1.Using string literal


 String s=”hi”;
 Each time you create a string literal ,the JVM checks the string constant pool in memory first.
 If the string already exists in memory pool, a reference to the pooled instance returns.
 If the string does not exist in the pool a new string object is created and it is placed in the pool.

2.Using new keyword.


 String s=new String(”hi”);
 JVM will create a new String object in heap memory and literal “hi” will be placed in the string constant pool.
 Variable s will refer to the object in heap.

26. Explain String operation or method in java.

 String method
1. String length (length)
2. String concate (concat)
3. Changing case (toUpperCase ,toLowerCase)
4. Character extraction (substring , charAt , getChars ,startsWith , endsWith)
5. String comparision (= = , equals, equalsIgnoreCase ,compareTo)

1. String length (length)

Parul Institute Of Engineerring & Technology(CSE Department) Page 26


Java & Internet Technology Prepared By: Prof. Shital Pathar
 It return length of String object.it means total number of character in String.

Syntax: stringname.length()
Ex:
class c1
{
public static void main(String args[])
{
String s1=” hello”;
Systemout.println(“length of s1=”+ s1.length());
}
}
Output: length of s1= 5

2. String concate (concat)

 concate it means merge two string into third string.


 Using + operator
 using concat function
Syntax: string1 + string2 stringname.length()
string1.concat(string2)
Ex:
class c1
{
public static void main(String args[])
{
String s1=” hello”;
String s2= “hi” ;
String s3= s1.concat(s2);
Systemout.println(“concat string s3=”+s3);
}
}
Output: concat string s3 = hellohi

3. Changing case (toUpperCase ,toLowerCase)

 toUpperCase method is used to change case of string from lower to uppercase


 toLowerCase method is used to change case of string from luppercase to lowercase.

Syntax: stringname.toUpperCase()
stringname.toLowerCase()
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello”;

Parul Institute Of Engineerring & Technology(CSE Department) Page 27


Java & Internet Technology Prepared By: Prof. Shital Pathar
Systemout.println(“uppercase=”+s1.toUpperCase());
Systemout.println(“lowercase=”+s1.toLowerCase());
Systemout.println(“original string=”+s1);
}
}
Output: uppercase = HELLO
lowercase =hello
original string = Hello

4. Character extraction (substring , charAt , getChars ,startsWith , endsWith)

o substring
 A part of string is called substring. it means substring is a subset of another String.

Syntax: stringname.substring( int startindex) or stringname.substring( int startindex , endindex)


 startindex: specify the index at which the substring will begin.
 endindex : specify the stopping point.
 string return contains all the characters from the beginning index up to ,but not including the ending index.

Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello hi how r u”;
Systemout.println(“substring is =”+s1.substring(6));
Systemout.println(“substring is =”+s1.substring(0,7));
}
}
Output: substring is = hi how r u
substring is = Hello h

o charAt()

 To extract a single character from String .


 It returns the character at a specific index of a string

Syntax: stringname.charAt(index)
index:it is index of character that you want to display. index value must be integer.
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello hi how r u”;
Systemout.println(“single character is =”+s1.charAt(1));
Systemout.println(“single character is =”+s1.charAt(11));

Parul Institute Of Engineerring & Technology(CSE Department) Page 28


Java & Internet Technology Prepared By: Prof. Shital Pathar
}
}
Output: single character is =e
single character is =w

o getChars()

 To extract more than one character at a time from String .

Syntax: stringname.getChars( start, end , target[],targetstart)


start : specifies the index of beginning of the substring.
end : specifies the index of ending of substring.
target[] : specifies array that will receive the character.
targetstart : specifies at which index the substring will be copied.
Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello hi how r u”;
char buf[ ] =new char [4];
s1.getChars(7, 12, buf , 0);
Systemout.println(“substring is =”+ buf );
}
}
Output: substring is = hi how

o startsWith() and endsWith()

 startsWith(string) : this method determines whether a given string begins with a specified string.If string
begin with specified string then true is returned otherwise false is returned.
 endsWith(string) : this method determines whether a given string end with a specified string. If string
end with specified string then true is returned otherwise false is returned.

Syntax: stringname.startsWith(string)
stringname.endsWith(string)

Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello hi how r u”;
Systemout.println(“s1.startsWith(“He”) );
Systemout.println(“s1.startsWith(“ab”) );
Systemout.println(“s1.endsWith(“u”) );
Systemout.println(“s1.startsWith(“r”) );

Parul Institute Of Engineerring & Technology(CSE Department) Page 29


Java & Internet Technology Prepared By: Prof. Shital Pathar
}
}
Output: true
false
true
false

5. String comparision ( equals, equalsIgnoreCase ,= = ,compareTo)

o equals

 This method compare content of string .if content are same then it returns true otherwise it returns false.

 Syntax: stringname1.equals(stringname2)

Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello “;
String s2=”Hello”;
String s3= new String(“Hello”);
String s4=” hi”;
Systemout.println(“s1.equals(s2) );
Systemout.println(“s1.equals(s3) );
Systemout.println(“s1.equals(s4) );
}
}
Output: true
true
false

o equalsIgnorCase

 This method compare content of string but it will ignore case . so HELLO and hello is same.

 Syntax: stringname1.equalsIgnorCase(stringname2)

Ex:
class c1
{
public static void main(String args[])
{
String s1=” HELLO “;
String s2=”hello”;

Parul Institute Of Engineerring & Technology(CSE Department) Page 30


Java & Internet Technology Prepared By: Prof. Shital Pathar
Systemout.println(“s1.equalsIgnorCase(s2) );
}
}
Output: true

o ==

 The = = operator compares two object references to see whether they refer to the same instance.If two object
refer same instance the it will return true otherwise it returns false.

 Syntax: stringname1 = = stringname2

Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello “;
String s2=”Hello”;
String s3= new String(“Hello”);
String s4=” hi”;
Systemout.println(“s1 = = s2 ); // both s1 and s2 refer same instance.
Systemout.println(“s1 = = s3) ); //both s1 and s3 refer different instance.
}
}
Output: true
false

o compareTo

 ThecompareTo methos compare values of two string and it returns integer value .
 If two strings are same it will return zero
 If string1 is greater than string2 then it will return greater than zero.
 If string1 is less than string2 then it will return less than zero.

 Syntax: stringname1.compareTo(stringname2)

Ex:
class c1
{
public static void main(String args[])
{
String s1=” Hello “;
String s2=”Hello”;
String s3=”hi”;
Systemout.println(s1.compareTo(s2);
Systemout.println (s1.compareTo(s3);

Parul Institute Of Engineerring & Technology(CSE Department) Page 31


Java & Internet Technology Prepared By: Prof. Shital Pathar
}
}
Output: 0
1

27. What is StringBuffer class in java.

 StringBuffer is another class to create String object.


 Using String class we can create immutable(nomodification) string.
 So StringBuffer class is used to create mutable (modified) string.
 StringBuffer class is same as String class except it is mutable(modified).

o StringBuffer class constructors:

1.StringBuffer() :- Creates empty string buffer with initial capacity of 16.


2.StringBuffer(String str) :- Creates String buffer with specified string.
3.StringBuffer(int capacity) :- creates empty string buffer with the specified capacity as length.

o EX:
 StringBuffer s1=new StringBuffer();
 StringBuffer s2= new StringBuffer(“hello”);
 StringBuffer s3=new StringBuffer(20);

Method of StringBuffer class

1. length()
2. capacity()
3. append()
4. insert()
5. delete() & deleteCharAt()
6. reverse()
7. replace()
8. charAt()
9. substring()
10. equals()
11. indexof()

1. length()

 It return length of String object.it means total number of character in String.

Syntax: stringname.length()

Ex: class c1
{

Parul Institute Of Engineerring & Technology(CSE Department) Page 32


Java & Internet Technology Prepared By: Prof. Shital Pathar
public static void main(String args[])
{
StringBuffer s1=new StringBuffer();
StringBuffer s2= new StringBuffer(“hello”);
Systemout.println(“length of s1=”+ s1.length());
System.out.println(“length of s2=”+ s2.length());
}
}
Output: length of s1= 0
length of s2=5

2. capacity()

 It return allocated capacity of String object. It means how many character can be stored by string.

Syntax: stringname.capacity()
Ex:
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer();
StringBuffer s2=new StringBuffer("hello");
StringBuffer s3=new StringBuffer(20);
System.out.println(“capacity of s1=”+s1.capacity());
System.out.println((“capacity of s2=”+s2.capacity());
System.out.println((“capacity of s3=”+s3.capacity());
}
}

Output: capacity of s1= 16


capacity of s1=21
capacity of 20

3. append()

 The append() method concat string that is define in(“”) to end of string.

Syntax: stringname.append(string)
Ex:
class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer();

Parul Institute Of Engineerring & Technology(CSE Department) Page 33


Java & Internet Technology Prepared By: Prof. Shital Pathar
StringBuffer s2=new StringBuffer("hello");
s1.append("how r u");
System.out.println(“s1 string=”+s1);
s2.append("hi");
System.out.println(“s2 string=”+s2);
}
}
Output: s1 string= how r u
s2 string = hellohi

4. insert()

 The insert () method insert(add) one string into another string.

Syntax: stringname.insert(index,string)
Ex: s1.insert(2,”ab”) : insert “ab” into string s1 at 2nd index.

class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I java");
System.out.println(s1.insert(2,"like"));
System.out.println(“s1 string=”+s1);
}
}
Output: s1 string= I like java

5. deleteCharAt() & delete()

 The deleteCharAt () method delete the character that is specified in the index.
 The delete() method deletes sequence of characters from specified start index to end index

Syntax: stringname.deleteChatAt(index)
stringname.delete(startindex,endindex)

Ex: s1.deleteCharAt(2):delete a character which index is 2.


s1.delete(4,7) :delete charactes from 4th index to 6th index. character which has 7th index is not
deleted.

class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I like java");

Parul Institute Of Engineerring & Technology(CSE Department) Page 34


Java & Internet Technology Prepared By: Prof. Shital Pathar
s1.delete(4,7);
System.out.println(“s1 string=”+s1);
s1.deleteCharAt(0);
System.out.println(“string s1=”+s1);
}
}
Output: s1 string= I lijava
s1 string= lijava

6. reverse()

 The reverse () method reverse the character that is specified in the string.

Syntax: stringname.reverse()

Ex: class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I like java");
s1.reverse();
System.out.println(“string s1=”+s1);
}
}
Output: s1 string= avaj ekil I

7. replace()

 The replace () method replace(change) the one set of characters with another set of characters.

Syntax: stringname.replace(startindex,endindex,string)

Ex: s1.replace(2,6,”is”) :change charactes from 2nd index to 5th index by “is” . character which has 6th
index is not changed

class c1
{
public static void main(String args[ ])
{
StringBuffer s1=new StringBuffer("I like java");
s1.replace(2,6,”is”);
System.out.println(“string s1=”+s1);
}
}
Output: s1 string= I is java

Parul Institute Of Engineerring & Technology(CSE Department) Page 35


Java & Internet Technology Prepared By: Prof. Shital Pathar

LIST OF QUESTIONS:

1. List four different inbuilt exceptions of java.


2. Write a Java Program to develop user defined exception for ‘Divide by Zero’
3. Explain ArrayIndexOutOfBound Exception in Java with example
4. Explain Multiple Catch block with program example.
5. Write a program and explain try…catch block.
6. Explain following (i) throw (ii) finally (i) throws (ii) checked exception
7. Define thread. State two ways to create a thread.
8. Explain thread priorities with ex.
9. Explain life cycle of a thread.
10. Write a program that executes two threads. One thread will print the even numbers and another thread will
print odd numbers from 1 to 50.
11. Explain basics of stream classes
12. Write a program in java to create a text file and perform read operation on the text file.
13. Write a program in java to create a text file and perform write operation on the text file.
14. Write a program in Java to create, write, modify, read operations on a Text file.
15. List methods of String class. Explain how to use String class .
16. List methods of String Buffer class. Explain how to use String buffer class
17. Write a Java program to read two strings from command line argument and check the equality of two string using
string function.

Parul Institute Of Engineerring & Technology(CSE Department) Page 36

You might also like