0% found this document useful (0 votes)
17 views

TM03-Abstraction-Packages-Exception Handling

Here is a program that takes input as the size of the array, elements of the array and an index from the user. It handles ArrayIndexOutOfBoundsException and NumberFormatException using try-catch blocks: ```java import java.util.Scanner; public class ArrayIndexDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter size of the array: "); int size = sc.nextInt(); int[] arr = new int[size]; System.out.println("Enter " + size + " elements:"); for(int i=0; i<size; i++) {

Uploaded by

kirishnakanth
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

TM03-Abstraction-Packages-Exception Handling

Here is a program that takes input as the size of the array, elements of the array and an index from the user. It handles ArrayIndexOutOfBoundsException and NumberFormatException using try-catch blocks: ```java import java.util.Scanner; public class ArrayIndexDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter size of the array: "); int size = sc.nextInt(); int[] arr = new int[size]; System.out.println("Enter " + size + " elements:"); for(int i=0; i<size; i++) {

Uploaded by

kirishnakanth
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Abstraction/Packages/Interfaces/Exception Handling

1.1. Create a class called GeneralBank which acts as base class for all banks. This
class has functionality getSavingInterestRate and getFixedInterestRate methods, which
return the saving a/c rate of interest and fixed account rate of interest the
specific bank gives. Since GeneralBank cannot say what percentage which bank would
give, make it abstract.

1.2. Create 2 subclasses of GeneralBank called ICICIBank and KotMBank. Override the
methods from base class. ICICI - Savings 4% Fixed 8.5% and KotMBank. - Savings 6%
Fixed 9%

1.3. Create a main method to test the above classes. Try one by one and absorb your
finding.
a) ICICIBank object reference instantiated with ICICIBank class.
b) KotMBank object reference instantiated with KotMBank class.
c) GeneralBank object reference instantiated with KotMBank class.
d) GeneralBank object reference instantiated with ICICIBank class.

Solution
import java.util.*;
abstract class GeneralBank
{
public abstract float getSavingInterestRate ();
public abstract float getFixedInterestRate ();
}
class ICICIBank extends GeneralBank
{

public float getSavingInterestRate ()


{
return 0.04f;
}

public float getFixedInterestRate ()


{
return 0.085f;
}
}

class KotMBank extends GeneralBank


{

public float getSavingInterestRate ()


{
return 0.06f;
}

public float getFixedInterestRate ()


{
return 0.09f;
}
}

public class BankMain{

public static void main(String []args){


ICICIBank i1=new ICICIBank();
System.out.println(i1. getSavingInterestRate ());
System.out.println(i1. getFixedInterestRate ());
KotMBank k1=new KotMBank ();
System.out.println(k1. getSavingInterestRate ());
System.out.println(k1. getFixedInterestRate ());
GeneralBank gb= new ICICIBank();
System.out.println(gb. getSavingInterestRate ());
System.out.println(gb. getFixedInterestRate ());
}
}

Exercise 3 : Create a package called com.automobile

Create a package called com.automobile. Define an abstract class called Vehicle.


Vehicle class has the following abstract methods:
public String getModelName()
public String getRegistrationNumber()
public String getOwnerName()

Create TwoWheeler subpackage under Automobile package


Hero class extends Automobile.vehicle class
public int getSpeed()
– Returns the current speed of the vehicle.
public void radio()
– provides facility to control the radio device
Honda class extends com.automobile.vehicle class
public int getSpeed()
– Returns the current speed of the vehicle.
public void cdplayer()
– provides facility to control the cd player device which is available in the car.
Create a test class to test the methods available in all these child class.

Solution

package com.automobile;
abstract class Vehicle {
public abstract String getModelName();
public abstract String getRegistrationNumber ();
public abstract String getOwnerName ();
}
public void display()
{
System.out.println(gender + " "+name+" "+email);
}
}
package com.automobile.TwoWheeler;
class Hero extends Vehicle {
public String getModelName()
{
return "Hero";
}
public String getRegistrationNumber ()
{
return "100";
}
public String getOwnerName ()
{
return "Owner1";
}
public int getSpeed()
{
return 10;
}
public void radio()
{
System.out.println("Radio Control Facility");
}
}

class Honda extends Vehicle {


public String getModelName()
{
return "Honda";
}
public String getRegistrationNumber ()
{
return "200";
}
public String getOwnerName ()
{
return " Owner1";
}
public int getSpeed()
{
return 20;
}
public void cdplayer ()
{
System.out.println("cdplayer Control Facility");
}
}

import com.automobile.TwoWheeler;
public class automobilemain
public static void main(String []args){
Hero h1=new Hero();
h1. getModelName();
h1.getRegistrationNumber ();
h1.getOwnerName ();
h1.getSpeed();
h1.radio();

Honda h2=new Honda();


h2. getModelName();
h2.getRegistrationNumber ();
h2.getOwnerName ();
h2.getSpeed();
h2.cdplayer();
}
}

Exercise 1 : A Library needs to develop an online application


Interfac
A library needs to develop an online application for two types of es
users/roles, Adults and children. Both of these users should be able to
register an account.

Any user who is less than 12 years of age will be registered as a child
and they can borrow a “Kids” category book for 10 days, whereas an adult
can borrow “Fiction” category books which need to be returned within 7
days.

Note: In future, more users/roles might be added to the library where


similar rules will be enforced.

Develop Interfaces and classes for the categories mentioned above.


1. Create an interface LibraryUser with the following methods declared,
Method Name
registerAccount
requestBook
2. Create 2 classes “KidUsers” and “AdultUser” which implements the
LibraryUser interface.

3. Both the classes should have two instance variables as specified


below.
Instance variables Data type
age int
bookType String

4. The methods in the KidUser class should perform the following logic.
registerAccount function:
if age < 12, a message displaying “You have successfully registered under
a Kids Account” should be displayed in the console.
If(age>12), a message displaying, “Sorry, Age must be less than 12 to
register as a kid” should be displayed in the console.
requestBook function:
if bookType is “Kids”, a message displaying “Book Issued successfully,
please return the book within 10 days” should be displayed in the console.
Else, a message displaying, “Oops, you are allowed to take only kids
books” should be displayed in the console.
5. The methods in the AdultUser class should perform the following logic.
registerAccount function:
if age > 12, a message displaying “You have successfully registered under
an Adult Account” should be displayed in the console.
If age<12, a message displaying, “Sorry, Age must be greater than 12 to
register as an adult” should be displayed in the console.
requestBook function:
if bookType is “Fiction”, a message displaying “Book Issued successfully,
please return the book within 7 days” should be displayed in the console.
Else, a message displaying, “Oops, you are allowed to take only adult
Fiction books” should be displayed in the console.
6. Create a class “LibraryInterfaceDemo.java” with a main method which
performs the below functions,
Test case #1:
Create an instance of KidUser class.
Set the age as specified in the below table and invoke the registerAccount
method of the KidUser object

Age
10
18

Set the book Type as specified in the below table and invoke the
requestBook method of the KidUser object,

BookType
“Kids”
“Fiction”

Test case #2:

Create an instance of AdultUser class.


Set the age as specified in the below table and invoke the registerAccount
method of the AdultUser object

Age
5
23

Set the book Type as specified in the below table and invoke the
requestBook method of the AdultUser object
BookType
“Kids”
“Fiction”

Solution
interface LibraryUser
{
void registerAccount();
void requestBook();
}
class KidUsers implements LibraryUser
{
int age;
String booktype;
public KidUsers(int age, String booktype)
{
this.age=age;
this. booktype= booktype;
}
public void registerAccount()
{
if(age<12)
System.out.println("You have successfully registered under a Kids
Account");
else
System.out.println("Sorry, Age must be less than 12 to register as a
kid");
}
public void requestBook()
{
if(booktype.equals("Kids"))
System.out.println("Book Issued successfully, please return the book
within 10 days ");
else
System.out.println("Oops, you are allowed to take only kids books ");
}
}

class AdultUser implements LibraryUser


{
int age;
String booktype;
public AdultUser (int age, String booktype)
{
this.age=age;
this. booktype= booktype;
}

public void registerAccount()


{
if(age>12)
System.out.println("You have successfully registered under a Adult
Account");
else
System.out.println("Sorry, Age must be greater than 12 to register as
an Adult");
}
public void requestBook()
{
if(booktype.equals("Fiction"))
System.out.println("Book Issued successfully, please return the book
within 7 days ");
else
System.out.println("Oops, you are allowed to take only Adult Fiction
books ");
}
}

public class LibraryInterfaceDemo


{
public static void main(String a[])
{
KidUsers k1=new KidUsers(10,"Kids");
KidUsers k2=new KidUsers(18,"Fiction");
k1.registerAccount();
k1.requestBook();
k2.registerAccount();
k2.requestBook();
AdultUser a1=new AdultUser (5,"Kids");
AdultUser a2=new AdultUser (23,"Fiction");
a1.registerAccount();
a1.requestBook();
a2.registerAccount();
a2.requestBook();
}
}

Exercise 3 : Write a program that takes input as the size of the array

Write a program that takes as input the size of the array and the elements in the array. The program then asks the user to enter a
particular index and prints the element at that index. Index starts from zero.

This program may generate Array Index Out Of Bounds Exception or NumberFormatException . Use exception handling mechanisms to
handle this exception.

Sample Input and Output 1:


Enter the number of elements in the array
2
Enter the elements in the array
50
80
Enter the index of the array element you want to access
1
The array element at index 1 = 80
The array element successfully accessed

Sample Input and Output 2:


Enter the number of elements in the array
2
Enter the elements in the array
50
80
Enter the index of the array element you want to access
9
java.lang.ArrayIndexOutOfBoundsException

Sample Input and Output 3:


Enter the number of elements in the array
2
Enter the elements in the array
30
j
java.lang.NumberFormatException

import java.util.*;

public class ayyayexcep{

public static void main(String args[])


{
int a[];
Scanner s=new Scanner(System.in);
String index1;
int size,index;
try
{
System.out.println("Enter the size of an array");
size=s.nextInt();
a=new int[size];
System.out.println("Enter the elements of an array");
for(int i=0; i<size; i++)
a[i]=s.nextInt();
System.out.println("Enter the index of the array element you want
to access");
s.nextLine();
index1=s.nextLine();
index=Integer.parseInt(index1);
System.out.println("Aarray element at index " + index + " is" +
a[index]);
System.out.println("Aarray element successfully accessed");
}
catch(NumberFormatException e)
{

System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{

System.out.println(e);
}

}
}

Exercise 7 : A student portal provides user to register their profile.


A student portal provides user to register their profile. During registration the
system needs to validate the user should be located in India. If not the system
should throw an exception.
Step 1: Create a user defined exception class named “InvalidCountryException”.
Step 2: Overload the respective constructors.
Step 3: Create a main class “UserRegistration”, add the following method,
registerUser– The parameter are String username,String userCountry and add the
following logic,
• if userCountry is not equal to “India” throw a InvalidCountryException with the
message “User Outside India cannot be registered”
• if userCountry is equal to “India”, print the message “User registration done
successfully”
Invoke the method registerUser from the main method with the data specified and see
how the program behaves,
Name Country Expected Output
Mickey US InvalidCountryException should be thrown.
The message should be “User Outside India cannot be registered”
Mini India The message should be “User registration done successfully”
Sample Input and Output

Solution

import java.util.*;

class InvalidCountryException extends Exception


{
InvalidCountryException(String s)
{
super(s);
}
}

public class UserRegistration {


public void registerUser(String username,String userCountry) throws
InvalidCountryException
{
if(userCountry.equalsIgnoreCase("India"))
System.out.println("User registration done successfully");
else
throw new InvalidCountryException("User Outside India cannot be
registered");
}
public static void main(String a[])
{
String name,country;
Scanner s=new Scanner (System.in);
System.out.println("Enter the name and Country");
name=s.nextLine();
country=s.nextLine();
try
{
UserRegistration ur=new UserRegistration ();
ur.registerUser(name,country);
}
catch(InvalidCountryException e)
{
System.out.println(e.getMessage());
}
}
}

You might also like