JAVA Assignment 1
JAVA Assignment 1
1. S ingle Inheritance: A class inherits from a single superclass. This is the most basic
form and is straightforward to implement.
2. Multilevel Inheritance: A class inherits from a superclass, and another class inherits
from this subclass. This forms a chain-like structure of inheritance.
3. Hierarchical Inheritance: Multiple classes inherit from a single superclass. This allows
several classes to share common behavior defined in the parent class.
4. Hybrid Inheritance: A combination of multiple and hierarchical inheritance. Java doesn’t
directly support hybrid inheritance with classes to avoid ambiguity, but it can be achieved
using interfaces.
5. Multiple Inheritance: Achieved using interfaces in Java, as direct multiple inheritance of
classes is not supported due to the "diamond problem."
P
● romotes code reuse across multiple generations of classes.
● The final subclass inherits all the properties and methods of the preceding classes in the
hierarchy.
Output:
Dogclass indirectly inherits the
In this example, the eatmethod from the
Animalclass through
Mammalclass.
the
super
Applications of :
1. C alling Superclass Constructor: Use super()to call the constructor of the
superclass.
2. Accessing Superclass Methods: Use super.methodName()to invoke a method
from the superclass.
3. Accessing Superclass Fields: Use super.fieldNameto resolve field naming
conflicts when both the superclass and subclass define fields with the same name.
super
Example: Application of
Output:
sing
U super Dogclass successfully accesses properties and methods from the
, the Animal
class.
4. Explain abstract and final keyword with an example.
abstractand
ava provides the
J finalkeywords to definespecific characteristics of classes
and methods.
abstractKeyword:
he
T abstractkeyword is used to declare a class thatcannot be instantiated directly. It can
also be applied to methods that must be implemented by subclasses. Abstract classes act as
blueprints for other classes.
finalKeyword:
finalkeyword can:
The
. M
1 ark a class as non-inheritable.
2. Prevent method overriding when applied to methods.
3. Declare constants when applied to variables.
Method Overriding:
ethod overriding in Java occurs when a subclass provides a specific implementation for a
M
method that is already defined in its superclass. The overridden method in the subclass should
have the same name, return type, and parameters as the method in the superclass. Overriding
allows a subclass to provide its version of a method, enabling runtime polymorphism.
. T
1 he method must have the same name and parameter list.
2. The overriding method cannot have a lower access modifier than the overridden method.
3. The method must belong to an inheritance hierarchy.
ynamic method dispatch is a mechanism in Java where the call to an overridden method is
D
resolved at runtime rather than compile time. It allows Java to achieve runtime polymorphism by
determining the actual method to be invoked based on the object type, not the reference type.
Example:
Output:
ava 8 introduced default methods in interfaces to allow developers to define methods with a
J
body. This enables interfaces to evolve without breaking existing implementations.
7. How do you achieve multiple inheritance in java explain with an example.
ava does not support multiple inheritance with classes to avoid ambiguity (commonly known as
J
the diamond problem). However, it allows multiple inheritance using interfaces. A class can
implement multiple interfaces and inherit their behaviors.
Output:
. B
1 java.util
uilt-in Packages: Predefined packages like java.io
, , etc.
2. User-defined Packages: Custom packages created by the user.
packagekeyword.
1. Create a package using the
2. C -doption to place them in the appropriate directory
ompile the classes with the
structure.
3. Import the package into another program using the importkeyword.
4. Use the classes defined in the package.
Example:
Animal.java
Save the following code in .
Main.java
Save the following code in .
Step 4: Compile and Run
Output:
By organizing classes into packages, Java applications become modular and easier to maintain.
1.
private
2.
default(also known as "package-private")
3.
protected
4.
public
Let's break down each of these access modifiers with examples and implications.
privateAccess Modifier
1.
● V isibility: When no access modifier is specified (i.e., default access), the member is
accessible only within classes that are part of thesame package. It is not accessible
from outside the package.
● Implications: This level allows classes within the same package to interact with each
other more freely, but it restricts access from classes outside the package.
protectedAccess Modifier
3.
publicAccess Modifier
4.
Output:
0.Write a program that contains one method that will throw an
1
IllegalAccessException and use proper exception handles so that the
exception should be printed.
n
A IllegalAccessExceptionis a checked exception that occurs when a program attempts
to reflectively access a field, method, or constructor that it does not have access to. This often
happens in scenarios involving reflection, but it can also be manually thrown.
Output:
Explanation:
checkAccess()method explicitly throws an
1. The IllegalAccessException
.
main()method, the exception is caught using a
2. In the try-catchblock.
3. T e.getMessage()method provides the custom message passed when the
he
exception is thrown.
4. Thee.printStackTrace()method displays the exception’s stack trace.
. C
1 atch blocks are evaluated in the order they appear.
2. The first matching catch block is executed, and the remaining blocks are ignored.
3. The most specific exceptions should come first, followed by more generic exceptions
Exception
(e.g., ).
Example:
Output:
Explanation:
12. How do you create your own exception class? Explain with a program.
reating a custom exception class allows developers to define specific error conditions for their
C
applications. This is particularly useful when built-in exceptions do not adequately describe the
problem.
. E
1 Exceptionclass (or
xtend the RuntimeExceptionfor unchecked exceptions).
2. Define constructors to pass custom messages and exception details.
toString()for custom behavior.
3. Optionally override methods like
Example:
Output:
Explanation:
MyExceptionclass is a custom checked exception.
1. The
validateAge()method throws
2. The MyExceptionif the
ageis less than 18.
main()method.
3. The exception is caught and handled in the
Example:
Output:
Explanation:
1. E xception:An exception is an event that disrupts the normal flow of the program. It’s an
object that wraps an error, such as division by zero, file not found, or accessing an array
out of bounds.
2. Try Block:This is the block where you write code that might throw an exception. If an
exception occurs, the catch block (if defined) will handle it.
3. Catch Block:This block is used to catch exceptions that occur in the try block. You can
define multiple catch blocks to handle different types of exceptions.
4. Finally Block:This block is optional and executes regardless of whether an exception
occurs or not. It's typically used for cleanup tasks like closing resources.
5. Throw Keyword:This is used to explicitly throw an exception from a method or block of
code.
6. Throws Keyword:It is used in the method signature to declare that the method might
throw certain exceptions. This allows the calling method to handle or propagate the
exception.
Output:
In the example, anArrayIndexOutOfBoundsExceptionis thrown because the array
has only 5 elements, but the code attempts to access the 11th element. The exception is
catchblock, and the
caught in the finallyblock executes regardless of the outcome.
● T
hese are exceptions that are not checked at compile time but are checked at runtime.
Unchecked exceptions are subclasses ofRuntimeException .
NullPointerException
● Example: ArithmeticException
, ,
ArrayIndexOutOfBoundsException
.
1. ArithmeticException:
● Occurs when an illegal arithmetic operation is performed, such as dividing by zero.
2. NullPointerException:
● Occurs when a program attempts to use an object reference that is null
3. ArrayIndexOutOfBoundsException:
● H
appens when trying to access an array with an invalid index (less than 0 or greater
than the array length)
Output:
Explanation:
. C
1 hecked Exceptions:Exceptions that are checked at compile-time.
2. Unchecked Exceptions (RuntimeExceptions):Exceptions that are checked at
runtime.
These built-in exception classes form the foundation of Java's exception-handling mechanism.
Here are some of the commonly used built-in exception classes in Java:
ArithmeticException
1.
T
● hrown when an exceptional arithmetic condition occurs, such as division by zero.
int result = 10 / 0;
● Example:
NullPointerException
2.
ArrayIndexOutOfBoundsException
3.
● T hrown when trying to access an array with an invalid index (either negative or beyond
the size of the array).
● Example: int[] arr = new int[3]; arr[5] = 10;
FileNotFoundException
4.
T
● hrown when an attempt to open the file denoted by a specified pathname has failed.
FileReader file = new FileReader("nonexistent_file.txt");
● Example:
IOException
5.
T
● hrown when an input/output operation fails or is interrupted.
BufferedReader br = new BufferedReader(new
● Example:
FileReader("file.txt"));
ClassNotFoundException
6.
● T hrown when an application tries to load a class by its name, but the class cannot be
found.
Class.forName("com.example.NonExistentClass");
● Example:
NumberFormatException
7.
● T
hrown when a string cannot be parsed into a numeric type (e.g., attempting to convert
a non-numeric string to an integer).
int number = Integer.parseInt("abc");
● Example:
IllegalArgumentException
8.
T
● hrown to indicate that a method has been passed an illegal or inappropriate argument.
● Example:Thread.sleep(-1000);(sleep duration cannot be negative)
InterruptedException
9.
● T hrown when a thread is interrupted during a blocking operation (e.g., sleeping or
waiting).
● Example: Thread.sleep(1000);might throw InterruptedExceptionif the thread
is interrupted during sleep.
Example Program Demonstrating Built-in Exceptions:
Output: