Java programs on Abstractions Packages and Exception Handling Complete Hands-on Coding


 

1. Create a class called GeneralBank that acts as a base class for all banks. 

 This class has getSavingsInterestRate and getFixedDepositInterestRate methods, 

 which returns the savings account interest rate and fixed deposit account interest rate that the specific bank gives. 

 Since GeneralBank cannot say what percentage which bank would give, make these methods abstract.

Create two subclasses of GeneralBank called ICICIBank and KotMBank. Override the inherited methods from the base class. The following are the interest rates of these banks.

ICICIBank - Savings 4% Fixed 8.5% and 

KotMBank - Savings 6% Fixed 9%.

Create a main method to test the above classes and their methods. Try one by one and observe your findings

a) ICICIBank i=new ICICIBank();

b) KotMBank k=new KotMBank();

c) GeneralBank g=new KotMBank();

d) GeneralBank g=new ICICIBank();


1:  abstract class GeneralBank {  
2:       abstract double getSavingsInterestRate();  
3:       abstract double getFixedDepositInterestRate();  
4:  }  
5:  class ICICIBank extends GeneralBank {  
6:       @Override  
7:       double getSavingsInterestRate() {  
8:            // TODO Auto-generated method stub  
9:            return 4;  
10:       }  
11:       @Override  
12:       double getFixedDepositInterestRate() {  
13:            // TODO Auto-generated method stub  
14:            return 8.5;  
15:       }  
16:  }  
17:  class KotMBank extends GeneralBank {  
18:       @Override  
19:       double getSavingsInterestRate() {  
20:            // TODO Auto-generated method stub  
21:            return 6;  
22:       }  
23:       @Override  
24:       double getFixedDepositInterestRate() {  
25:            // TODO Auto-generated method stub  
26:            return 9;  
27:       }  
28:  }  
29:  public class Solution {  
30:       public static void main(String[] args) {  
31:            // TODO Auto-generated method stub  
32:            ICICIBank iciciBank = new ICICIBank();  
33:            KotMBank kotMBank = new KotMBank();  
34:            System.out.println("ICICI BANK: " +   
35:                      "Fixed Rate = " + iciciBank.getFixedDepositInterestRate() + "%, " +   
36:                      "Saving Rate = " + iciciBank.getSavingsInterestRate() + "%");  
37:            System.out.println("KOTAK MAHINDRA BANK: " +   
38:                      "Fixed Rate = " + kotMBank.getFixedDepositInterestRate() + "%, " +   
39:                      "Saving Rate = " + kotMBank.getSavingsInterestRate() + "%");  
40:            System.out.println("----------------------------------------------------------");  
41:            GeneralBank gBank1 = new ICICIBank();  
42:            GeneralBank gBank2 = new KotMBank();  
43:            System.out.println("GENERAL BANK1: " +   
44:                      "Fixed Rate = " + gBank1.getFixedDepositInterestRate() + "%, " +   
45:                      "Saving Rate = " + gBank1.getSavingsInterestRate() + "%");  
46:            System.out.println("GENERAL BANK2: " +   
47:          "Fixed Rate = " + gBank2.getFixedDepositInterestRate() + "%, " +   
48:          "Saving Rate = " + gBank2.getSavingsInterestRate() + "%");       
49:       }  
50:  }  

2. Create an abstract class Compartment to represent a rail coach. Provide an abstract function notice in this class. 

public abstract String notice();

Derive FirstClass, Ladies, General, Luggage classes from the compartment class. 

Override the notice function in each of them to print notice message that is suitable to the specific type of  compartment.

Create a class TestCompartment.Write main function to do the following:

Declare an array of Compartment 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.

[i.e based on the random  number genererated, the first compartment can be Luggage, the second one could be Ladies and so on..]


1:  import java.util.Random;  
2:  abstract class Compartment {  
3:       public abstract String notice();  
4:  }  
5:  class FirstClass extends Compartment {  
6:       @Override  
7:       public String notice() {  
8:            // TODO Auto-generated method stub  
9:            return "You are in First Class Compartment";  
10:       }  
11:  }  
12:  class Ladies extends Compartment {  
13:       @Override  
14:       public String notice() {  
15:            // TODO Auto-generated method stub  
16:            return "You are in Ladies Compartment";  
17:       }  
18:  }  
19:  class General extends Compartment {  
20:       @Override  
21:       public String notice() {  
22:            // TODO Auto-generated method stub  
23:            return "You are in General Compartment";  
24:       }  
25:  }  
26:  class Luggage extends Compartment {  
27:       @Override  
28:       public String notice() {  
29:            // TODO Auto-generated method stub  
30:            return "You are in Lugguage Compartment";  
31:       }  
32:  }  
33:  public class TestCompartment {  
34:       public static void main(String[] args) {  
35:            // TODO Auto-generated method stub  
36:            Compartment[] compartments = new Compartment[10];  
37:            Random random = new Random();  
38:              for (int i = 0; i < 10; i++) {  
39:                   int randomNum = random.nextInt((4 - 1) + 1) + 1;  
40:                   if (randomNum == 1)  
41:                        compartments[i] = new Luggage();  
42:                   else if (randomNum == 2)  
43:                        compartments[i] = new Ladies();  
44:                   else if (randomNum == 3)  
45:                        compartments[i] = new General();  
46:                   else if (randomNum == 4)  
47:                        compartments[i] = new FirstClass();  
48:                   System.out.println(compartments[i].notice());  
49:              }  
50:       }  
51:  }  

3. Create an abstract class Instrument which is having the abstract function play. 

Create three more sub classes from Instrument which is Piano, Flute, Guitar. 

Override the play method inside all three classes printing a message 

“Piano is playing  tan tan tan tan  ”  for Piano class

“Flute is playing  toot toot toot toot”  for Flute class

“Guitar is playing  tin  tin  tin ”  for Guitar class 

Create an array of 10 Instruments.

Assign different type of instrument to Instrument reference.

Check for the polymorphic behavior of  play method.

Use the instanceof operator to print which object is stored at which index of instrument array.


1:  import java.util.Random;  
2:  abstract class Instrument {  
3:       abstract void play();  
4:  }  
5:  class Piano extends Instrument {  
6:       @Override  
7:       void play() {  
8:            // TODO Auto-generated method stub  
9:            System.out.println("Piano is playing tan tan tan tan ");  
10:       }  
11:  }  
12:  class Flute extends Instrument {  
13:       @Override  
14:       void play() {  
15:            // TODO Auto-generated method stub  
16:            System.out.println("Flute is playing toot toot toot toot ");       
17:       }  
18:  }  
19:  class Guitar extends Instrument {  
20:       @Override  
21:       void play() {  
22:            // TODO Auto-generated method stub  
23:            System.out.println("Piano is playing tin tin tin ");  
24:       }  
25:  }  
26:  public class Solution {  
27:       public static void main(String[] args) {  
28:            // TODO Auto-generated method stub  
29:  Instrument[] instruments = new Instrument[10];  
30:            Random random = new Random();  
31:              for (int i = 0; i < 10; i++) {  
32:                   int randomNum = random.nextInt((3 - 1) + 1) + 1;  
33:                   if (randomNum == 1)  
34:                        instruments[i] = new Piano();  
35:                   else if (randomNum == 2)  
36:                        instruments[i] = new Flute();  
37:                   else if (randomNum == 3)  
38:                        instruments[i] = new Guitar();  
39:              }  
40:            // checking polymorphic behaviour  
41:              for (int i = 0; i < 10; i++) {  
42:                  if(instruments[i] instanceof Piano)  
43:                    System.out.print("Instrument " + i + " is of type Piano, ");  
44:                  if(instruments[i] instanceof Flute)  
45:                    System.out.print("Instrument " + i + " is of type Flute, ");  
46:                  if(instruments[i] instanceof Guitar)  
47:                    System.out.print("Instrument "+ i + " is of type Guitar, ");  
48:                  instruments[i].play();  
49:             }  
50:       }  
51:  }  

4. Get an input String from user and parse it to integer, if it is not a number it will throw number format exception Catch it 

and print "Entered input is not a valid format for an integer." or else print the square of that number. (Refer Sample Input and Output). 

Sample input and output 1: 

Enter an integer: 12

The square value is 144

The work has been done successfully

Sample input and output 2:

Enter an integer: Java

Entered input is not a valid format for an integer.


1:  import java.util.Scanner;  
2:  public class Solution {  
3:       public static void main(String[] args) {  
4:            // TODO Auto-generated method stub  
5:            Scanner scan = new Scanner(System.in);  
6:            System.out.println("Enter an integer: ");  
7:            String stringNum = scan.nextLine();  
8:            try {  
9:                 int intNum = Integer.parseInt(stringNum);  
10:                 System.out.println("The square is "+ intNum * intNum);  
11:                 System.out.println("The work has been done successfully");  
12:            }  
13:            catch(NumberFormatException e) {  
14:                 System.out.println("Entered input is not a valid format for an integer.");  
15:            }  
16:       }  

5. 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.

Sample Input and Output 1:

Enter the number of elements in the array

3

Enter the elements in the array

20

90

4

Enter the index of the array element you want to access

2

The array element at index 2 = 4

The array element successfully accessed

Sample Input and Output 2:

Enter the number of elements in the array

3

Enter the elements in the array

20

90

4

Enter the index of the array element you want to access

6

java.lang.ArrayIndexOutOfBoundsException

1:  import java.util.Scanner;  
2:  public class Solution {  
3:       public static void main(String[] args) {  
4:            // TODO Auto-generated method stub  
5:            Scanner scan = new Scanner(System.in);  
6:            System.out.println("Enter the number of elemets in the array");  
7:            int len = scan.nextInt();  
8:            int[] array = new int[len];  
9:            System.out.println("Enter the elements in the array");  
10:            for(int i = 0; i < array.length; i++) {  
11:                 array[i] = scan.nextInt();  
12:            }  
13:            System.out.println("Enter the index of the array you want to access");  
14:            int keyIndex = scan.nextInt();   
15:            try {  
16:                 System.out.println("The array element at index "+ keyIndex +" = "+ array[keyIndex]);  
17:                 System.out.println("The array element successfully accessed");  
18:            }  
19:            catch(ArrayIndexOutOfBoundsException e) {  
20:                 System.out.println(e.getClass());  
21:            }       
22:       }  
23:  }  

6. 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


1:  import java.util.InputMismatchException;  
2:  import java.util.Scanner;  
3:  public class Solution {  
4:       public static void main(String[] args) {  
5:            // TODO Auto-generated method stub  
6:            Scanner scan = new Scanner(System.in);  
7:            System.out.println("Enter the number of elemets in the array");  
8:            int len = scan.nextInt();  
9:            int[] array = new int[len];  
10:            System.out.println("Enter the elements in the array");  
11:            try {  
12:                 for(int i = 0; i < array.length; i++)  
13:                      array[i] = scan.nextInt();  
14:                 System.out.println("Enter the index of the array you want to access");  
15:                 int keyIndex = scan.nextInt();  
16:                 System.out.println("The array element at index "+ keyIndex +" = "+ array[keyIndex]);  
17:                 System.out.println("The array element successfully accessed");  
18:            }  
19:            catch(ArrayIndexOutOfBoundsException e) {  
20:                 System.out.println(e);  
21:            }  
22:            catch(InputMismatchException e) {  
23:                 System.out.println("java.lang.NumberFormatException");  
24:            }  
25:       }  
26:  }  


For more Hands-on coding Examples: Click Here