Wednesday, October 15, 2008

Core Java Sample examples

Program to create multiple threads from a single class?

class Thr3{
static public void main(String[] args)throws Exception{
Thread th1 = new MyThr3("thread one");
Thread th2 = new MyThr3("thread two");
Thread th3 = new MyThr3("thread three");

th2.setPriority(Thread.MAX_PRIORITY);
th1.setPriority(Thread.MIN_PRIORITY);
th3.setPriority(Thread.NORM_PRIORITY);

th1.start();
th2.start();
th3.start();
}
}

class MyThr3 extends Thread{
// we are using a constructor so that we can force to set the name
// for thread
public MyThr3(String name){
setName(name);
}
public void run(){
for(int i= 0;i <10;>

Program is a simple java Application which uses employee data type?

class useemployee {
public static void main(String args[]){
System.out.println(" no of emps = " + employee.getnoemps());
employee e1 = new employee("x","addr1",2000.0f,1);
System.out.println(" no of emps = " + employee.getnoemps());
employee e2 = new employee("y","addr1",2000.0f,2);
System.out.println(" salary of e1 =" + e1.incsalary(12.2f));
System.out.println(" salary of e2 =" + e2.incsalary(12.2f));
System.out.println(" no of emps = " + employee.getnoemps());
}
}

Write a Program is a simple java Application to showThe difference between class methods and instance methods?

class usestaticclass {
public static void main(String args[]){
//staticclass.method1();
//staticclass.method2();
// staticclass.method3();
staticclass s1 = new staticclass();
System.out.println(" after creating first object");
staticclass s2 = new staticclass();
staticclass.method1();
s2.method3();
}
}

How Handle errors in java?

class except {

public void Error () throws Exception{
// try to create an object of type xyz for which a class
//file doesn't exist. In C language the compiler doesn't check
//whether you are handling error or not, but java checks whether
//you are handling or not
Object o = Class.forName("xyz").newInstance();
}

public static void main(String args[]) throws Exception{

except e = new except();
// we are not handling the error here
System.out.println(" before method call");
e.Error();
System.out.println(" after method call");
}
}

Write a program to shows how to use try - finally blocks?

class except{
public void Error() throws mychkexception{
throw (new mychkexception(" exception my myunchkexception"));
}

public static void main(String args[]){

except5 e = new except5();
// we are not handling the error here
System.out.println(" before method call");
try{
e.Error();
} catch (mychkexception mye){
System.out.println(mye);
}finally{
System.out.println("This part of code executes irrespective of the errors that occur in try block" );
}
}
}

No comments: