Wednesday, March 30, 2011

A Sample Program on User-define Exception


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 Handle ArithmeticException in a Sample 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 ArithmeticException throw command Line Argument


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");
}
}
}

Saturday, March 19, 2011

How to Use Setters & Getters Methods in Java



public class Student {
private String studentNo;
private String studentName;
private float studentFee;

public float getStudentFee() {
return studentFee;
}
public void setStudentFee(float studentFee) {
this.studentFee = studentFee;
}
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}

}

Data Represent in the form User-defined Object (Bean)



public class Student {
private String studentNo;
private String studentName;
private float studentFee;

public float getStudentFee() {
return studentFee;
}
public void setStudentFee(float studentFee) {
this.studentFee = studentFee;
}
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}

}