0% found this document useful (0 votes)
127 views16 pages

Module 4 Java Bank With Solutions Prathima G

The document provides a comprehensive guide on Java programming concepts, including packages, exception handling, and access modifiers. It explains how to create user-defined packages and exceptions, demonstrates nested try blocks, and outlines the access protection levels available in Java. Additionally, it includes example programs to illustrate these concepts effectively.

Uploaded by

Prathima G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views16 pages

Module 4 Java Bank With Solutions Prathima G

The document provides a comprehensive guide on Java programming concepts, including packages, exception handling, and access modifiers. It explains how to create user-defined packages and exceptions, demonstrates nested try blocks, and outlines the access protection levels available in Java. Additionally, it includes example programs to illustrate these concepts effectively.

Uploaded by

Prathima G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

Module 4 Question Bank with Solutions

1. Define package. Explain the steps involved in creating a user-defined


package with an example.
ANS:

A package in Java is a group of related classes, interfaces, and sub-packages that are
organized together under a common namespace. It helps in organizing code, avoiding name
conflicts, and providing access protection.

package mypackage;

public class MyClass {


void display() {
[Link]("This is a package example.");
}
}

Steps to Create a User-Defined Package

Creating a user-defined package involves three main steps:

Step 1: Create a Java file and declare the package

 At the very first line of the file, write the package statement.
 This tells Java that the class belongs to a specific package.

Example:
// File: [Link]
package mypackage;

public class MyPackageClass {


public void display() {
[Link]("This is my user-defined package.");
}
}

Step 2: Compile the file and generate the package folder

Use the -d option to tell Java where to place the package folder.

Command:
javac -d . [Link]

 -d . creates the package folder mypackage in the current directory.

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 1


2

 Inside this folder, the .class file will be placed.

Resulting Structure:

mypackage/
[Link]

Step 3: Use the package in another program

To use the class from the package, import it using the import statement.

Example:
// File: [Link]
import [Link];

public class TestPackage {


public static void main(String[] args) {
MyPackageClass obj = new MyPackageClass();
[Link]();
}
}

Step 4: Compile and run the program

Compile:
javac [Link]
Run:
java TestPackage

Output:
This is my user-defined package.

2. Write a program that contains one method that will throw an

IllegalAccessException and use proper exception handles so that the


exception should be printed.
ANS:

class ExceptionDemo {

void myMethod() throws IllegalAccessException {

throw new IllegalAccessException("Access not allowed!");

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 2


3

public static void main(String[] args) {

ExceptionDemo obj = new ExceptionDemo();

try {

[Link]();

catch (IllegalAccessException e) {

// Handling and printing the exception

[Link]("Exception caught: " + e);

[Link]("Program continues normally...");

[Link] an exception. What are the key terms used in exception handling? Explain.

ANS:

Definition of an Exception

An exception in Java is an undesirable or unexpected event that occurs during program


execution and disrupts the normal flow of the [Link] usually occurs due to errors such as
dividing by zero, accessing invalid array index, file not found, etc.

Java uses exception handling to detect such errors and handle them gracefully without
crashing the program.

Key Terms Used in Exception Handling

Below are the main terms involved in Java exception handling:

1. try

 The try block contains the code that may cause an exception.
 If an exception occurs inside the try block, it is thrown to the corresponding catch
block.

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 3


4

Example:

try {
int x = 10 / 0; // may cause exception
}

2. catch

 The catch block is used to handle the exception.


 It receives the exception thrown by the try block.

Example:

catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}

3. throw

 The throw keyword is used to manually throw an exception.


 Used inside a method or block.

Example:

throw new IllegalArgumentException("Invalid input");

4. throws

 The throws keyword is used in a method signature to declare that a method may throw
an exception.
 It tells the caller method to handle the exception.

Example:

void myMethod() throws IOException {


// code
}

5. finally

 The finally block contains code that will always execute whether an exception occurs
or not.
 Commonly used to close files, database connections, etc.

Example:

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 4


5

finally {
[Link]("Execution completed");
}

6. Exception

 An object representing the error.


 All exceptions are subclasses of the class Exception.

4. Explain the concept of importing packages in Java and provide an example


demonstrating the usage of the import statement.

ANS: Importing Packages in Java

In Java, a package groups related classes and interfaces.


To use a class that belongs to another package, we must import that package into our
program.

The import statement tells the compiler where to find the class so it can be accessed without
using its full package name.

Why import a package?

 To use predefined classes (like Scanner, ArrayList, etc.)


 To access classes from a user-defined package
 To improve code readability
 To avoid writing long qualified names like [Link]

Syntax of import statement

import [Link];

or to import all classes in a package:

import packageName.*;

Example Demonstrating import Statement

Example:

//Using Scanner class from [Link] package

import [Link]; // importing Scanner class

public class ImportExample {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]); // using imported class

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 5


6

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Hello, " + name);


}
}
Explanation:

 [Link] is the package.


 Scanner is the class inside that package.
 import [Link]; allows us to use Scanner directly.

Without import, we would need to write:

[Link] sc = new [Link]([Link]);

Summary (Exam-ready)

 Importing packages allows a Java program to use classes from other packages.
 It is done using the import statement.
 Example:
import [Link];.

5. How do you create your own exception class? Explain with a program.

ANS: In Java, you can create your own exception class by extending the

1. Exception class (for checked exceptions)


2. RuntimeException (for unchecked exceptions).

A user-defined exception is useful when you want to handle application-specific errors.

Steps to Create a User-Defined Exception

1. Create a class that extends Exception


2. Provide a constructor that calls the parent Exception constructor
3. Throw the exception using the throw keyword
4. Handle it using try–catch

Example Program: Creating and Using a Custom Exception

Custom Exception Class


// Creating a user-defined exception
class AgeException extends Exception
{
public AgeException(String message)

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 6


7

{
super(message); // calling the super class constructor
}
}
Main Program That Uses the Custom Exception
public class CustomExceptionDemo
{

// Method that checks age and throws custom exception


static void checkAge(int age) throws AgeException
{
if (age < 18)
{
throw new AgeException("Age must be 18 or above!");
} else {
[Link]("Access granted.");
}
}

public static void main(String[] args)


{
try
{
checkAge(15); // This will cause the exception
}
catch (AgeException e) {
[Link]("Custom Exception Caught: " + [Link]());
}

[Link]("Program continues...");
}
}

6. Demonstrate the working of a nested try block with an example.

ANS:

Nested try Block in Java

A nested try block means placing one try block inside another.
This allows handling different exceptions at different levels.

 The inner try handles exceptions related to a specific section of code.


 The outer try handles exceptions that are not caught by the inner one.

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 7


8

Example: Demonstrating Nested try Blocks

public class NestedTryExample


{
public static void main(String[] args) {

try {
// Outer try block
int[] arr = {10, 20, 30};

try {
// Inner try block
int result = arr[2] / 0; // ArithmeticException
[Link](result);
}
catch (ArithmeticException e) {
[Link]("Inner catch: Cannot divide by zero");
}
// Code that may throw ArrayIndexOutOfBoundsException
[Link](arr[5]); // Outer exception

}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Outer catch: Invalid array index");
}

[Link]("Program continues normally...");


}
}

Output
Inner catch: Cannot divide by zero
Outer catch: Invalid array index
Program continues normally...

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 8


9

7. Define Exception, Explain Exception Handling Mechanism provided in Java along


with syntax and Example.

ANS:

An exception in Java is an unexpected event or error that occurs during program execution
and disrupts the normal flow of the program.
Examples include dividing by zero, accessing invalid array index, file not found, etc.

Java provides an exception handling mechanism to detect and handle such errors gracefully
without stopping the program abruptly.

Exception Handling Mechanism in Java

Java handles exceptions using five key keywords:

1. try – Block that contains code which may cause an exception


2. catch – Used to handle the exception raised in try
3. throw – Used to manually throw an exception
4. throws – Declares exceptions a method might throw
5. finally – Block that always executes, whether exception occurs or not

Java uses this mechanism to ensure that programs do not terminate unexpectedly.

Syntax of Exception Handling

try
{
// Risky code that may cause an exception
}
catch (ExceptionType e)
{
// Handling code
}
Finally
{
// Code that always executes
}

Example Demonstrating Exception Handling

public class ExceptionHandlingDemo {

public static void main(String[] args) {

try {
int a = 10;

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 9


10

int b = 0;
int result = a / b; // ArithmeticException
[Link](result);
}
catch (ArithmeticException e) {
[Link]("Exception Caught: Cannot divide by zero");
}
finally {
[Link]("Finally block always executes.");
}

[Link]("Program continues normally...");


}
}

✓ Output
Exception Caught: Cannot divide by zero
Finally block always executes.
Program continues normally...

8. Build a Java Program to create a Package Balance Containing Account Class with
displayBalance() method and import the package in another package in another
program to access method of Account class

ANS:

PROGRAM STRUCTURE
Balance/[Link] → Package 1 (contains Account class)
bank/[Link] → Package 2 (imports Balance package)

Step 1: Create Package Balance with Account Class


File: [Link]
package Balance;

public class Account {


private double balance;

// Constructor
public Account(double balance) {
[Link] = balance;
}

// Method to display balance


public void displayBalance() {
[Link]("Current Balance: ₹" + balance);

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 10


11

}
}

Step 2: Compile the package

Use:

javac -d . [Link]

This creates the folder:

Balance/
[Link]

Step 3: Create Another Package & Import the Balance Package

File: [Link]
package bank;

import [Link]; // importing package

public class MainClass {


public static void main(String[] args) {

Account acc = new Account(5000.75); // Create object


[Link](); // Call method
}
}

Step 4: Compile MainClass


javac -d . [Link]

This creates:

bank/
[Link]

Step 5: Run the Program

Run using fully qualified class name:

java [Link]

Output
Current Balance: ₹5000.75

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 11


12

9. Examine the various levels of protection available for package and their implications
with suitable Examples.

ANS:Access Protection Levels in Java Packages

Java provides four access levels (access modifiers) to control how classes, methods, and
variables are accessed across packages:

1. private
2. default (no modifier)
3. protected
4. public

These access levels affect visibility within the same class, same package, and different
packages.

1. private Access

Meaning:

 Accessible only within the same class


 Not accessible within the same package
 Not accessible across packages

Example:
package pack1;

public class A {
private int data = 10;
private void show() {
[Link]("Private method");
}
}

package pack1;

public class B {
public static void main(String[] args) {
A obj = new A();
// [Link]; // ERROR: private member not accessible
// [Link](); // ERROR
}
}

Implication:

 Provides the strongest level of protection.

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 12


13

2. Default (Package-Private) Access

Meaning:

 No modifier used
 Accessible within the same package only
 Not accessible from another package

Example:
package pack1;

class A { // default class


void display() { // default method
[Link]("Default access");
}
}

package pack2;

public class B {
public static void main(String[] args) {
// A obj = new A(); // ERROR: default class not visible
}
}

Implication:

 Members are package-private: visible only inside the same package.

3. protected Access

Meaning:

 Accessible within the same package


 Accessible in other packages only through subclasses (inheritance)

Example:
package pack1;

public class A {
protected void show() {
[Link]("Protected method");
}
}

package pack2;
import pack1.A;

class B extends A {

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 13


14

public static void main(String[] args) {


B obj = new B();
[Link](); // allowed through inheritance
}
}

But this is NOT allowed:

A obj = new A();


[Link](); // ERROR (Not accessible without inheritance)

Implication:

 Good for sharing features with subclasses across packages.

4. public Access

Meaning:

 Accessible anywhere, in any package

Example:
package pack1;

public class A {
public void display() {
[Link]("Public method");
}
}

package pack2;
import pack1.A;

public class B {
public static void main(String[] args) {
A obj = new A(); // allowed
[Link](); // allowed
}
}

Implication:

 Most accessible: visible everywhere.

Modifier Same Class Same Package Subclass in Other Package Other Package

private ✔ Yes ✖ No ✖ No ✖ No

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 14


15

Modifier Same Class Same Package Subclass in Other Package Other Package

default ✔ Yes ✔ Yes ✖ No ✖ No

protected ✔ Yes ✔ Yes ✔ Yes (via inheritance) ✖ No

public ✔ Yes ✔ Yes ✔ Yes ✔ Yes

[Link] a Java Program for a Banking application to throw an exception where a


person tries to withdraw the amount even though he/she has lesser than minimum
balance(create a Custom Exception)

ANS:

Java Program – Custom Exception for Minimum Balance Check


// Custom Exception Class
class MinimumBalanceException extends Exception
{
public MinimumBalanceException(String message)
{
super(message);
}
}

// Banking Application
class BankAccount
{
private double balance;
private final double MIN_BALANCE = 1000.00; // Minimum required balance

public BankAccount(double balance)


{
[Link] = balance;
}

// Method to withdraw amount


public void withdraw(double amount) throws MinimumBalanceException
{
if (balance - amount < MIN_BALANCE)
{
throw new MinimumBalanceException("Withdrawal Denied! Balance will fall below
minimum limit.");
}
balance -= amount;
[Link]("Withdrawal Successful! Remaining Balance: ₹" + balance);

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 15


16

}
}

public class BankingApp


{
public static void main(String[] args)
{

BankAccount acc = new BankAccount(2000.00); // Initial balance

try
{
[Link](1500.00); // Attempting withdrawal → will cause exception
}
catch (MinimumBalanceException e) {
[Link]("Exception Caught: " + [Link]());
}

[Link]("Transaction Completed!");
}
}

Output
Exception Caught: Withdrawal Denied! Balance will fall below minimum limit.
Transaction Completed!

Explanation

 MinimumBalanceException → Custom exception for banking rule violation


 withdraw() method throws exception if withdrawal makes balance < ₹1000
 Exception handled using try–catch ensuring program doesn’t crash

Prathima G, Associate Professor,Dept od CSE(Data Science),[Link] College Page 16

You might also like