Slip21

 Q1) Define a class MyDate(Day, Month, year) with methods to accept and display a MyDateobject. Accept date as dd,mm,yyyy. Throw user defined exception "InvalidDateException" if the date is invalid. [10 marks] 

class InvalidDateException extends Exception 

{

    public InvalidDateException() {

        System.out.println("Given Date is Invalid");

    }

}

class MyDate 

{

    int day,month,year;

    public MyDate(int day, int month, int year) 

    {

        try {

    if (isValidDate(day, month, year)) {

            this.day = day;

            this.month = month;

            this.year = year;

    System.out.println("Valid Date: "+day+"/"+month+"/"+year);

        } else 

            throw new InvalidDateException();

        

} catch (InvalidDateException e) {    }

    }

    boolean isValidDate(int day, int month, int year) 

    {

        if (month < 1 || month > 12) 

            return false;

        int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) 

            daysInMonth[1] = 29;

        return day > 0 && day <= daysInMonth[month - 1];

    }

    public static void main(String[] args) {

        

int d=Integer.parseInt(args[0]);

int m=Integer.parseInt(args[1]);

int y=Integer.parseInt(args[2]);

            MyDate date1 = new MyDate(d,m,y); 

          

    }

}


Q2) Create an employee class(id,name,deptname,salary). Define a default and parameterized constructor. Use ‘this’ keyword to initialize instance variables. Keep a count of objects created. Create objects using parameterized constructor and display the object count after each object is created. (Use static member and method). Also display the contents of each object.

class Employee

{

    int empid,salary;

    String name,dept;

    static int cnt=0;

    public Employee()

    {

        cnt++;

    }

    public Employee(int empid,String name,String dept,int salary)

    {

        this.empid=empid;

        this.name=name;

this.dept=dept;

        this.salary=salary;

cnt++;

    }

public String toString()

        {

                return "empid: "+empid+" Name : "+name+" Dept : "+dept+" salary : "+salary;

        }

}

class SetA1

{

public static void main(String args[])

        {

        Employee e1=new Employee(1,"AAAA","Computer",20000);

System.out.println("NO. of objects = "+Employee.cnt);

System.out.println(e1);

Employee e2=new Employee(2,"BBBB","Computer",25000);

System.out.println("NO. of objects = "+Employee.cnt);

System.out.println(e2);

Employee e3=new Employee(3,"CCCC","Math",21000);

System.out.println("NO. of objects = "+Employee.cnt);

System.out.println(e3);

Employee e4=new Employee(4,"DDDD","Commerce",30000);

System.out.println("NO. of objects = "+Employee.cnt);

System.out.println(e4);

        }

}


Comments

Popular posts from this blog

Slip1

Slip3

Slip2