Abstraction, Packages, Exception Handling
Abstraction, Packages, Exception Handling
Abstract Classes
1.Create an abstract class Compartment to represent a rail coach. Provide an abstract function
notice in this class. Derive FirstClass, Ladies, General, Luggage classes from the
compartment class. Override the notice function in each of them to print notice suitable to the
type of the compartment. Create a class TestCompartment. Write main function to do the
following: Declare an array of Compartment pointers of size 10. Create a compartment of a
type as decided by a randomly generated integer in the range 1 to 4. Check the polymorphic
behavior of the notice method.
Code:
abstract class Compartment
{
abstract void notice();
}
class FirstClass extends Compartment
{
void notice()
{
System.out.println("Its FIRSTCLASS");
}
}
class Ladies extends Compartment
{
void notice(){
System.out.println("Its LADIES Compartment");
}
}
class General extends Compartment
{
void notice()
{
System.out.println("Its GENERAL Compartment");
}
}
class Luggage extends Compartment
{
void notice()
{
System.out.println("Its LUGGAGE");
}
}
public class Abstract
{
public static void main(String[] args)
{
Compartment c[] = new Compartment[10];
double i = Math.random()*5;
int x = (int)i;
System.out.println(x);
switch(x)
{
case 1: c[0] = new FirstClass();
c[0].notice(); break;
case 2: c[1] = new Ladies();
c[1].notice();
break;
case 3: c[2] = new General();
c[2].notice();
break;
case 4: c[3] = new Luggage();
c[3].notice();
break;
default: System.out.println("Invalid Choice");
}
}
}
Interfaces
2. Write an interface called Playable, with a method void play(); Let this interface be placed in a
package called music. Write a class called Veena which implements Playable interface. Let this
class be placed in a package music.string Write a class called Saxophone which implements
Playable interface. Let this class be placed in a package music.wind Write another class Test in
a package called live. Then, a. Create an instance of Veena and call play() method b. Create an
instance of Saxophone and call play() method c. Place the above instances in a variable of type
Playable and then call play().
Code:
package live;
import music.Playable;
import music.string.Veena;
import music.wind.Saxophone;
public class Music {
public static void main (String[]args) {
Veena v = new Veena();
v.play();
Playable pv = new Veena();
pv.play();
Saxophone s = new Saxophone();
s.play();
Playable ps= new Saxophone();
ps.play();
}
}
package music;
public interface Playable {
void play();
}
package music.string;
import music.Playable;
public class Veena implements Playable {
Exception Handling
3.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.
This program may generate Array Index Out Of Bounds Exception. Use exception
handling mechanisms
to handle this exception. In the catch block, print the class name of the exception
thrown.
Code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Exception1{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements in the arrays");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements in the array: ");
try {
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
System.out.println("Enter the index of the array element you want to
access");
int index = sc.nextInt();
System.out.println("The array element at index " + index + " = " +
arr[index]);
System.out.println("The array element successfully accessed");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("java.lang.ArrayIndexOutOfBoundsException");
} catch (InputMismatchException e) {
System.out.println("java.util.InputMismatchException");
}
sc.close();
}
}
Code:
import java.util.InputMismatchException;
public class Exception2{
public static void main(String[] args) {
int n = args.length;
for (int i = 0; i < n; i++)
if (args[i].charAt(args[i].length() - 1) == ',')
args[i] = args[i].replace(",", "");
int[] arr = new int[n];
int sum = 0;
double avg = 0;
try {
for (int i = 0; i < n; i++)
arr[i] = Integer.parseInt(args[i]);
for (int i = 0; i < n; i++)
sum += arr[i];
avg = sum / n;
} catch (NumberFormatException e) {
System.out.println("NumberFormatException");
} catch (ArithmeticException e) {
System.out.println("ArithmeticException");
} catch (InputMismatchException e) {
System.out.println("InputMismatchException");
}
System.out.println("sum: " + sum);
System.out.println("avg: " + avg);
}
}
5. Write a Program to take care of Number Format Exception if user enters values
other than integer for calculating average marks of 2 students. The name of the students
and marks in 3 subjects are taken from the user while executing the program.
In the same Program write your own Exception classes to take care of Negative values
and values out of range (i.e. other than in the range of 0-100)
Solution:
NegativeValuesException.java
package com.pv6;
ValuesOutOfRangeException.java
package com.pv6;
NumberException1.java
package com.pv6;
import java.util.Scanner;
if (sc.hasNextInt())
subA = sc.nextInt();
else
throw new NumberFormatException();
if (sc.hasNextInt())
subB = sc.nextInt();
else
throw new NumberFormatException();
if (sc.hasNextInt())
subC = sc.nextInt();
else
throw new NumberFormatException();
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
catch (NegativeValuesException e) {
System.out.println(e.getMessage());
}
catch (ValuesOutOfRangeException e) {
System.out.println(e.getMessage());
}
sc.close();
6. 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.
Invoke the method registerUser from the main method with the data specified and see
how the program behaves.
Example1)
i/p:Mickey,US
o/p:InvalidCountryException should be thrown.
The message should be “User Outside India cannot be registered”
Example2)
i/p:Mini,India
o/p:User registration done successfully
Solution:
InvalidCountryException.java
package com.pv7;
UserRegistration.java
package com.pv7;
public class UserRegistration {
try {
registration.registerUser("Mickey", "US");
}
catch (InvalidCountryException e) {
}
}
7. Write a program to accept name and age of a person from the command
prompt(passed as arguments when you execute the class) and ensure that the age
entered is >=18 and < 60.
Display proper error messages.
The program must exit gracefully after displaying the error message in case the
arguments passed are not proper.
Solution:
InvalidAgeException.java
package com.pv8;
Age.java
package com.pv8;