0% found this document useful (0 votes)
24 views

Java Unit-4

Uploaded by

web
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Java Unit-4

Uploaded by

web
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

1

UNIT-4(OOPS Through Java)

Multithreading in Java
1. What is thread, multithreading?
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
Multithreading in java is a process of executing multiple threads simultaneously.
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process. Java Multithreading is mostly used in
games, animation, etc.
Advantages of Java Multithreading
1) Enhanced performance.
2) You can perform many operations together, so it saves time. We can achieve multitasking.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
4) Threads use a shared memory area. No need of Extra memory .

2. Explain life cycle of a Thread?( or Explain Thread states ?)


A thread can be in one of the five states. The life cycle of the thread in java is controlled by
JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1)New: The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2)Runnable: The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
3)Running: The thread is in running state if the thread scheduler has selected it.
4)Waiting (Blocked):This is the state when the thread is still alive, but is currently not eligible
to run.
5) Dead(Terminated) : A thread is in terminated or dead state when its run() method exits.
2
UNIT-4(OOPS Through Java)

3) How to create thread in java?


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a Thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class


1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
Output: thread is running...
3
UNIT-4(OOPS Through Java)

2) Java Thread Example by implementing Runnable interface


1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi3 m1=new Multi3();
7. Thread t1 =new Thread(m1);
8. t1.start();
9. } }
Output: thread is running...
4. Explain about Thread Priority?
Thread Priority: Each thread have a priority. Priorities are represented by a number between 1 and
10. In most cases, thread scheduler schedules the threads according to their priority. But it is not
guaranteed because it depends on JVM specification that which scheduling it chooses.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and
the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
1. class TestMultiPriority1 extends Thread{
2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
5. }
6. public static void main(String args[]){
7. TestMultiPriority1 m1=new TestMultiPriority1();
8. TestMultiPriority1 m2=new TestMultiPriority1();
9. m1.setPriority(Thread.MIN_PRIORITY);
10. m2.setPriority(Thread.MAX_PRIORITY);
11. m1.start();
12. m2.start();
13. } }
Output: running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
4
UNIT-4(OOPS Through Java)

Exception Handling
1. Explain types of error in java?
Compile time errors: Compile time errors refer to syntax and semantics in compile time. For
example, if you do operations that involves different types. Ex: adding a string with an int, or
dividing a string by a real. These are also refereed as Checked exceptions.
Run Time error: Run time errors are those that are detected when the program execute. For
example, division by zero. The compiler cannot know if the operation x/a-b will leads to division
by zero until the execution. These are also refereed Unchecked exceptions.
Errors: 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. They are also ignored
at the time of compilation.
2. What is an exception and explain types ?
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 can occur for many different reasons. Following are some scenarios.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run
out of memory.
There are two types of exceptions in Java:
1)Checked exceptions 2)Unchecked exceptions
5
UNIT-4(OOPS Through Java)

Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the
compiler checks them during compilation to see whether the programmer has handled them or
not. If these exceptions are not handled/declared in the program, you will get compilation error.
For example, SQLException, IOException, ClassNotFoundException etc.
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught
or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not
checked at compile-time so compiler does not check whether the programmer has handled them
or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe
exit.For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
public class Unchecked_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Errors − 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. They are also ignored
at the time of compilation.
6
UNIT-4(OOPS Through Java)

Exception Handling Mechanism


3.Explain about exception handling mechanism in java ?
In java, exception handling is done using five keywords,

Keyword Description

Try The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.

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 important 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 doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.

a) Using try and catch


Try is used to guard a block of code in which exception may occur. This block of code is called
guarded region.
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in guarded code, the catch block that follows the try is checked, if the type of
exception that occurred is listed in the catch block then the exception is handed over to the catch
block which then handles it.
Example using Try and catch
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
7
UNIT-4(OOPS Through Java)

c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
Output: Divided by zero
After exception is handled
An exception will thrown by this program as we are trying to divide a number by zero
inside try block. The program control is transferred outside try block. Thus the line "This line
will not be executed" is never parsed by the compiler. The exception thrown is handled
in catch block. Once the exception is handled, the program control is continue with the next line
in the program i.e after catch block. Thus the line "After exception is handled" is printed.

b) Multiple catch blocks:


A try block can be followed by multiple catch blocks. You can have any number of catch blocks
after a single try block. If an exception occurs in the guarded code the exception is passed to the
first catch block in the list. If the exception type of exception, matches with the first catch block
it gets caught, if not the exception is passed down to the next catch block. This continues until
the exception is caught or falls through all catches.
Example for Multiple Catch blocks
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
8
UNIT-4(OOPS Through Java)

{
System.out.println("array index out of bound exception");
}
}
}
Output: divide by zero
Note: At a time, only one exception is processed and only one respective catch block is
executed.

c) finally clause
A finally keyword is used to create a block of code that follows a try block. A finally
block of code is always executed whether an exception has occurred or not. Using a finally
block, it lets you run any cleanup type statements that you want to execute, no matter what
happens in the protected code. A finally block appears at the end of catch block.

Example demonstrating finally Clause


Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
9
UNIT-4(OOPS Through Java)

System.out.println("finally is always executed.");


}
}
}
Output : Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound
exception.

d) Java throw keyword


The Java throw keyword is used to explicitly throw an exception.We can throw either
checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to
throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.


throw exception;
Let's see the example of throw IOException.
throw new IOException("sorry device error);

Java throw keyword example


In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.
1. public class TestThrow1{
2. static void validate(int age){
3. if(age<18)
4. throw new ArithmeticException("not valid");
5. else
6. System.out.println("welcome to vote");
7. }
8. public static void main(String args[]){
9. validate(13);
10. System.out.println("rest of the code...");
11. }
12. }

Output:
Exception in thread main java.lang.ArithmeticException:not valid
10
UNIT-4(OOPS Through Java)

4. Explain difference between throw and throws in Java?


There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
No. throw throws
1) Java throw keyword is used to explicitly Java throws keyword is used to declare
throw an exception. an exception.
2) Checked exception cannot be propagated Checked exception can be propagated
using throw only. with throws.
3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method
signature.

5) You cannot throw multiple exceptions. public void method()throws


IOException,SQLException.

You might also like