OOP Java - IMP M 4
OOP Java - IMP M 4
rd
3 SEM Exam – Important Questions
MODULE – 4
1. Which are the ways to access package from another package? Explain with example
Ans:
In Java, there are several ways to access a package from another package:
Both methods achieve the same result and allow classes from different packages to interact with
each other.
Suppose you have an existing package named com.example and you want to add a new class
named MyClass to this package.
2. Package Declaration:
Include the package declaration at the beginning of the file using the package keyword
followed by the package name.
3. Class Definition:
Define the class MyClass as you would with any other class.
You can add fields, methods, constructors, etc., as needed within the class.
4. Accessing the New Class:
Once the new class MyClass is added to the package com.example, it can be accessed from
other classes within the same package or from other packages using appropriate import
statements.
Here's an example of how to use the newly added class MyClass from another class:
In this example:
By following these steps, you can easily add new classes to existing packages in Java.
3. What is package? How do we create it? Give the example to create and to access
package.
Ans:
A package in Java is a way to organize classes into namespaces, providing a hierarchical structure
to the codebase. It helps in organizing large projects by grouping related classes together.
Packages also help in preventing naming conflicts between classes from different sources.
1. Creating a Package:
To create a package, you need to include a package declaration at the beginning of your
Java source files.
The syntax for declaring a package is package package_name;.
You must include the package declaration as the first non-comment line in your Java file.
Place your Java source files in a directory structure that matches the package name.
Example of creating a package named com.example:
In this example, MyClass is in the package com.example. The Java file is stored in the directory
structure com/example/MyClass.java.
2. Accessing a Package:
To access a class from a package, you need to use the fully qualified name of the class.
Alternatively, you can use the import statement to import the package or specific classes
from the package.
Example of accessing the MyClass from the com.example package:
In this example, OtherClass imports MyClass from the com.example package and creates an
instance of MyClass to call its display() method.
By following these steps, you can create and access packages in Java, allowing you to organize and
manage your code more effectively.
Access protection in Java is implemented through access modifiers, which define the visibility and
accessibility of classes, methods, and variables within Java code. There are four access modifiers in
Java:
1. public:
The public access modifier allows unrestricted access to a class, method, or variable from
any other class or package.
Classes, methods, and variables declared as public can be accessed from anywhere.
2. protected:
The protected access modifier restricts access to the declared class, method, or variable to
its own package and subclasses.
It allows access within the same package as well as by subclasses, even if they are in different
packages.
3. default (no modifier):
If no access modifier is specified, the default access modifier is applied.
The default access modifier restricts access to the declared class, method, or variable to
within the same package.
Classes, methods, and variables with default access are accessible only within the same
package and not by subclasses outside the package.
4. private:
The private access modifier restricts access to the declared class member to within the
same class only.
It provides the highest level of encapsulation and hides the member from other classes and
subclasses, including those in the same package.
Use Cases:
Use public when you want unrestricted access to a class, method, or variable.
Use protected when you want to restrict access to the same package and subclasses.
Use the default access modifier when you want to restrict access to the same package.
Use private when you want to restrict access to the same class only, providing maximum
encapsulation.
7. Define an interface. Explain how to define and implement an interface with an example
Ans: Interface in Java:
An interface in Java is a reference type that defines a set of abstract methods.
It is a blueprint of a class and is used to achieve abstraction and multiple inheritance in Java.
Interfaces can contain constants, default methods, static methods, and nested types.
To define an interface, you use the interface keyword followed by the interface name and its
members.
To implement an interface in a class, you use the implements keyword followed by the interface
name.
The class implementing an interface must provide implementations for all the abstract methods
declared in the interface.
Example:
In this example:
We define an interface Shape with two abstract methods area() and perimeter().
The Circle class implements the Shape interface and provides implementations for both methods.
We create an instance of Circle and call its area() and perimeter() methods to calculate the
area and perimeter of the circle, respectively.
8. Differentiate abstract base class and an interface.
Ans:
Abstract Base Class: An abstract base class is used to define a common base
for related classes. It provides a template for derived classes to inherit common
behavior and attributes.
Interface: An interface is used to define a contract that classes can implement.
It specifies a set of methods that implementing classes must define, allowing
for polymorphism and multiple
9. How do you define variables inside interface? List out the characteristics of such
variables
Ans:
In Java, you can define variables inside an interface. These variables are implicitly public, static,
and final. Here are the characteristics of such variables:
1. Implicit Modifiers:
Variables declared inside an interface are implicitly public, static, and final.
This means they are accessible to all classes, can be accessed without creating an instance of
the interface, and their values cannot be changed once assigned.
2. Initialization:
Variables inside an interface must be initialized at the time of declaration.
They cannot have a default value, and you must assign a value to them when declaring.
3. Access:
Interface variables are accessible using the interface name followed by the dot ( .) operator.
They can be accessed directly from the interface or through implementing classes.
4. Constant Declarations:
Since interface variables are implicitly final, they are considered constants and their values
cannot be modified after initialization.
They represent constant values that are shared among all classes that implement the
interface.
5. Usage:
Interface variables are commonly used to define constants that are relevant to all classes
implementing the interface.
They provide a way to ensure consistent behavior across different implementations of the
interface.
Example:
10. Define an exception. What are the key terms used in exception handling? Explain.
Ans:
Definition of an Exception: An exception in Java is an event that disrupts the normal flow of
program execution. It represents an abnormal condition or error that occurs during the execution
of a program. When an exception occurs, an object representing that exception is created and
thrown out of the method where the error occurred. This allows the program to handle the
exception at an appropriate place in the code.
This demonstrates how exceptions can be caught and handled at different levels of nesting using
nested try blocks.
12. Write a program which contains one method which will throw Illegal Access Exception
and use proper exception handles so that exception should be printed.
Here's a simple Java program that contains a method throwException() which throws an
IllegalAccessException. We handle this exception using a try-catch block to print the exception
message.
In this program:
When executed, this program will print the message "Exception caught: Illegal Access Exception
occurred", indicating that the IllegalAccessException was caught and handled properly.
1. Hierarchy: Exceptions are organized into a hierarchy with Throwable as the top-level class,
followed by Error and Exception subclasses.
2. Error: Represents serious, unrecoverable issues like OutOfMemoryError or StackOverflowError,
usually not handled programmatically.
3. Exception: Represents recoverable issues and is further categorized into checked and unchecked
exceptions.
4. Checked Exceptions: Checked at compile-time, ensuring they're handled or declared in the code.
Examples: IOException, SQLException.
5. Unchecked Exceptions: Not checked at compile-time, often resulting from programming errors
like NullPointerException or ArithmeticException.
6. Purpose: Built-in exceptions provide a structured approach to handle exceptional conditions in
programs, promoting robust error handling and program reliability.
b. Uncaught Exceptions:
1. Definition: An uncaught exception is one that's thrown during program execution but not caught
and handled by surrounding code.
2. Propagation: Uncaught exceptions propagate up the call stack until reaching the top-level of the
program.
3. Termination: If an exception remains uncaught at the top level, it results in the termination of the
program, displaying an error message.
4. .: Handling uncaught exceptions is crucial for ensuring program reliability, preventing unexpected
termination, and providing meaningful error messages.
5. Exception Handling Mechanism: In Java, developers use try-catch blocks to catch and handle
exceptions, allowing for graceful recovery from errors.
6. Best Practices: Proper exception handling involves logging errors, displaying user-friendly
messages, and performing necessary cleanup operations to maintain program integrity.
14. How do you create your own exception class? Explain with a program.
Ans:
To create a custom exception class in Java, you typically extend one of the existing exception classes, such as
Exception or RuntimeException, depending on whether you want to create a checked or unchecked
exception. Here's how you can create your own exception class with a simple program:
In this program:
We define a custom exception class CustomException that extends RuntimeException. This makes
CustomException an unchecked exception.
The constructor of CustomException accepts a message that describes the exception.
In the main method, we simulate a condition where an age check fails (age < 18), leading to the
creation and throwing of a CustomException.
The try-catch block catches the CustomException, and the error message is printed to the
console.
This demonstrates how to create and use a custom exception class in Java. You can extend this
example to create checked exceptions by extending Exception instead of RuntimeException, and
you can add additional methods or properties to your custom exception class as needed.
Output:
1. Definition: Chained exceptions, introduced in Java 1.4, allow an exception to encapsulate another
exception that caused it, forming a chain of exceptions.
2. Purpose: Chained exceptions provide more detailed information about the cause of an exception,
especially in complex error scenarios where multiple exceptions might occur.
3. Encapsulation: Each exception in the chain retains information about the exception that caused it,
allowing developers to trace back to the root cause of an error.
4. Accessibility: The getCause() method is used to retrieve the exception that caused the current
exception, enabling easy access to the chained exceptions.
5. Usage: Chained exceptions are commonly used in situations where an exception occurs within a
catch block, and it's necessary to preserve the original exception while throwing a new one.
The divide method attempts to perform a division operation that may result in an
ArithmeticException if num2 is zero.
In the main method, we call divide(10, 0) within a try-catch block to catch the potential
ArithmeticException.
If an ArithmeticException occurs, we catch it, wrap it in a new RuntimeException, and rethrow it,
chaining the original exception.
The chained exception retains the information about the original ArithmeticException, providing
more context about the error.