Wednesday, April 6, 2011

A Sample Multithreading Program


Thread can be created 2 ways.
1. our thread name should be extends Thread
2. our thread name should be implements Runnable Interface

here the following program 2 threads are there.Mythread1,Mythread2 respectively..these two's are extends Thread.Thread is born when the our thread is created when the start() method calling on the particural thread object..

class Mythread1 extends Thread{
public void run(){
for(int i=1;i<=30;i++)

System.out.println(i);

}
}
class Mythread2 extends Thread{
public void run(){
for(int i=31;i<=50;i++)
System.out.println(i);
}
}
class MythreadTest{
public static void main(String args[]) throws Exception {
Mythread1 t1=new Mythread1();
Mythread2 t2=new Mythread2();
t2.start();
t1.start();

}
}

Sample Program for How to create User Defined Exception in Java Application


class MyException extends Exception{
}
class voting{
public static void isEligible(int age) throws MyException{
if(age<19)
throw new MyException();
else
System.out.println("can caste vote");
}
}
class MyTest{
public static void main(String args[]){
try{
int age=Integer.parseInt(args[0]);
voting.isEligible(age);
}
catch(MyException e){
e.printStackTrace();
System.out.println("Invalid Age can't vote");
}
catch(NumberFormatException e){
e.printStackTrace();
System.out.println("please supply age must be digits");
}
catch(Exception e){
e.getMessage();
}
}
}

Without Handling Exception in Sample Java Program


When the following program is compiling it is not giving any error.compiled Successfully.At the time of execution it Contains ArithematicException logica error in the program.

class WithoutHandle{
public static void main(String args[])
{
System.out.println("started");
int n,d,q=1;
n=Integer.parseInt(args[0]);
d=Integer.parseInt(args[1]);
q=n/d;
System.out.println("the result");
System.out.println("complete");
}
}

How to handle ArithematicException in Java


class WithHandle{
public static void main(String args[])
{
System.out.println("started");
int n,d,q=1;
n=Integer.parseInt(args[0]);
d=Integer.parseInt(args[1]);
try{
q=n/d;
System.out.println("the result value is"+q);
}
catch(ArithmeticException e){
System.out.println("Divisible fails...2nd value shouldn't be 0");
}
}
}