Professional Documents
Culture Documents
Name: Section: Roll NO: - : Final ..
Name: Section: Roll NO: - : Final ..
1. Illustrate with an example, how a class in Java can be prevented from getting
inherited?
In Java, when we have a need of preventing a class from being inherited, we pre
precede the class declaration with final.
Declaring a class as final implicitly declares all of its methods as final, too. It is to
be noted that the use of final along with abstract is illegal since an abstract class is
incomplete on it's own and relies on it's subclasses to provide complete
implementations.
As the comments imply, it is illegal for Beta to inherit Alpha since Alpha is declared
as final.
2. Define two user defined exception ‘EvenNumberException’ and
‘OddNumberException’. Write a Java class which has a method which checks
whether a given number if even or not. The method throws
‘EvenNumberException’ or ‘OddNumberException’ if the number is even or odd
respectively. Illustrate the handling of the exception with suitabe sequence of
codes.
import java.io.*;
import java.util.Scanner;
import java.lang.Exception;
class Odd{
static void checkodd(int num) throws OddNumberException{
if ( num % 2 != 0 )
throw new OddNumberException("Odd no");
}
}
class main{
public static void main(String args[]){
int num;
System.out.println("Enter an Integer number:");
Scanner input = new Scanner(System.in);
try{
num = input.nextInt();
E.checkeven(num);
O.checkodd(num);
}
catch(EvenNumberException e){
System.out.println(e);
}
catch(OddNumberException e){
System.out.println(e);
}
}
}
A thread can be in one of the five states: new, runnable, running, non-runnable
and terminated.
According to sun, there is only 4 states in thread life cycle in java new,
runnable, non-runnable and terminated. There is no running state.
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) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to
run.
5) Terminated