Professional Documents
Culture Documents
JAVA UNIT 03 (1)
JAVA UNIT 03 (1)
❖ INTRODUCTION
1.Compile-time errors
2. Run-time errors
● All Syntax errors will be detected and displayed by the Java compiler and
therefore these errors are known as compile time errors.
● whenever the compiler displays an error it will not create the . class file hence it is
necessary to fix all the errors before we can successfully compiled and run the
program.
● Sometimes programs may accompany successfully creating in “.class” file but
may not run properly.
● such programs may produce wrong results due to wrong logic or may terminate
due to errors such as stack overflow .
❖ EXCEPTION
● An exception is a condition that is caused by run-time error in a program.
● when the Java interpreter encounters an error while running the
● program it creates an exception object and throws it.
● When exceptions occur in program the normal flow of program terminates, to
continue the execution of program exception should be handled properly by
executing a segment of code called as Exception Handler and this mechanism is
called as exception handling.
● Exception handling mechanism takes corrective actions to resolve exceptions that
has occurred in the program to continue the normal flow of program execution.
EXCEPTION TYPES
● Checked exceptions − A checked exception is an exception that is checked
(notified) by the compiler at compilation-time, these are also called as compile
time exceptions. These exceptions cannot simply be ignored, the programmer
should take care of (handle) these exceptions.
● Unchecked exceptions − 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.
import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
MULTIPLE CATCH STATEMENTS
● If more than one exception can occur, then we use multiple catch blocks
● When an exception is thrown, each catch statement is inspected in order, and the
first one whose type matches that of the exception is executed
● After one catch statement executes, the others are bypassed
EXAMPLE:
❖ FINALLY
This block is executed whether an exception is handled or not.
EXAMPLE:
class FinallyExample{
public static void main(String[] args) {
try{
int a=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
finally{
System.out.println("finally block is executed");
}
}
}
O/P:
Arithmetic Exception Occures
finally block is executed
❖ throw keyword
● The Java throw keyword is used to explicitly throw an exception.
EXAMPLE:
if(age<18)
else
System.out.println("welcome to vote");
t1. validate(13);
In the given example,age value is 13 hence condition (age<18) i.e., 13<18 becomes
true and Arithmetic exception will be thrown using “throw”.
O/P:
EXAMPLE
import java.lang.*;
class MyException extends Exception{
MyException(int age)
{
if (age<18)
System.out.println("My Exception occurred,invalid age");
else
System.out.println("valid age");
}
}
public class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
throw new MyException(19);
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
O/P:
Starting of try block
valid age
Catch Block
MyException
In this example custom exception is thrown in Example1 class using ‘throw’ keyword in
try block,when exception is thrown MyException constructor of same class is invoked .
MyException class is consisting of user defined exception
❖ THROWS IN JAVA
//method code
}
EXAMPLE
if(age<18)
else
System.out.println("welcome to vote");
MULTITHREADING IN JAVA
INTRODUCTION
⦿ A Thread may be defined as a separate sequential flow of control within the main
program.
⦿ Threads are used in a program for achieving specific tasks.
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.
3. Running State:
⦿ Running means that the processor has given its time to the thread for its execution.
⦿ The thread runs until it relinquishes (give up) control on its own.
Blocked State:
⦿ A thread is set 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, or sleeping, or waiting in order to
satisfy certain requirements.
5. Dead State:
⦿ Every thread has a life cycle.
⦿ A running thread ends its life when it has completed executing its run ( ) method.
⦿ It is a natural death.
⦿ However, 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.
CREATING THREADS
⦿ Java defines two ways by which a thread can be created.
1. By implementing the Runnable interface.
2. By extending the Thread class.
Example 2:
public class B implements Runnable {
public static void main(String[] args) {
B b1= new B();
Thread t = new Thread(b1);
t.start();
}
public void run() {
System.out.println("This code is running in a thread");
}
}
Output: This code is running in a thread
⦿ This is another way to create a thread by a new class that extends Thread class.
Example:
class A extends Thread
{
public void run()
{
System.out.println(“thread started running..");}
}
Class MyThreadDemo{
public static void main( String args[] ) {
A obj = new A();
obj.start();
}
}
THREAD METHODS
Method Description
EXAMPLE:
class A extends Thread{
public void run() {
for(int i=1;i<=5;i++) {
if(i==2)
yield();
System.out.println("i=”+i); }
}
}
class B extends Thread{
public void run() {
for(int j=1;j<=5;j++) {
System.out.println("from thread B:j="+j);
if(j==3)
stop();
System.out.println("b="+b);
}
}
}
class C extends Thread{
public void run() {
for(int k=1;k<=5;k++) {
if(k==3)
try {
sleep(1000);
}
catch(Exception e) {
System.out.println("caught");
}
}
}
public class ThreadEx{
public static void main(String args[]) {
A a1=new A(); //creating threads
B b1=new B();
C c1=new C();
a1.start();
b1.start();
b1.suspend();
System.out.println("B suspended");
c1.start();
b1.resume();
}
}
THREAD PRIORITY
⦿ In java,each thread is assigned with a priority which affects the order of their
execution.
⦿ In java setPriority() method will be used to set the priority of a thread and
getPriority() is used to get the priority of any thread
Syntax: ThreadName.setPriority(intNumber);
⦿ Priority value can be set between 1 to 10.
MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10
Ex: a.setPriority(MIN_PRIORITY)
Example
class A extends Thread{
public void run() {
for(int i=1;i<=5;i++)
System.out.println("i=”+i);
}
}
class B extends Thread{
public void run() {
for(int j=1;j<=5;j++)
System.out.println("i=”+i);
}
}
SYNCHRONIZATION
⦿ Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
⦿ When multiple threads are competing for same resources then they may lead to
serious problems.For Example,if thread t1 is trying to read a record from file while
another thread t2 is writing the same file then thread t1 may read wrong data.This
problem can be eliminated by using synchronization technique in java.
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
OUTPUT:
5
100
15
200
20
300
20
400
25
500
EXAMPLE WITH SYNCHRONIZATION
class Table{
synchronized void printTable(int n){ //method synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e)
{
System.out.println(e);
}
}
}
}
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
OUTPUT:
5
10
15
20
25
100
200
300
400
500