Java IA II Scheme -1
Java IA II Scheme -1
CIE – TEST II
Course: Object Oriented Programming with Java Course Code: BCS306A Semester: 3
Max. Marks: 50 Date: 15/11/2024 Faculty Name: Aishwarya G
1a. Define inheritance. Explain the different types of inheritance with syntax.
Inheritance is one of the key concepts in object-oriented programming (OOP). It allows a new class
(subclass/derived class) to inherit the attributes and behaviors of an existing class (superclass/base class).
This promotes code reuse and facilitates the creation of a hierarchy of classes.
In Java, there are two main types of inheritance:
1. Single Inheritance:
• A class can only inherit from one superclass.
• Java supports single inheritance only.
class Animal {
void eat() {
System.out.println("Animal is eating");
}}
// Derived class (subclass) inheriting from Animal
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}}
public class InheritanceExample {
public static void main(String[] args) {
// Creating an object of the subclass
Dog myDog = new Dog();
// Accessing methods from both superclass and subclass
myDog.eat(); // Inherited from Animal
myDog.bark(); // Defined in Dog
Course Code: BCS306A Scheme and Solution
2. Multilevel Inheritance: 6M
• A class can inherit from another class, and then a third class can inherit from the second class.
• This forms a chain of inheritance.
// Base class (superclass)
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
// Intermediate class inheriting from Animal
class Mammal extends Animal {
void run() {
System.out.println("Mammal is running");
}
}
// Derived class inheriting from Mammal
class Dog extends Mammal {
void bark() {
System.out.println("Dog is barking");
}
}
public class MultilevelInheritanceExample {
public static void main(String[] args) {
// Creating an object of the subclass
Dog myDog = new Dog();
// Accessing methods from all levels of inheritance
myDog.eat(); // Inherited from Animal
myDog.run(); // Inherited from Mammal
myDog.bark(); // Defined in Dog
}
}
Course Code: BCS306A Scheme and Solution
2a. What is abstraction? Explain with an example program the concept of abstract classes and methods. 6M
Abstraction is a process of hiding the implementation details and showing only functionality to the
user. A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
abstract class Animal {
abstract void sound(); // Abstract method
void sleep() { // Regular method
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Woof");
}
}
Course Code: BCS306A Scheme and Solution
• Method overriding forms the basis for one of Java’s most powerful concepts: dynamic method
dispatch. Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time. Dynamic method dispatch is important because this is
how Java implements run-time polymorphism.
• Restating an important principle: a superclass reference variable can refer to a subclass object.
• Java uses this fact to resolve calls to overridden methods at run time.
• When an overridden method is called through a superclass reference, Java determines which version
of that method to execute based upon the type of the object being referred to at the time the call occurs.
Thus, this determination is made at run time.
• When different types of objects are referred to, different versions of an overridden method will be
called. In other words, it is the type of the
class A {
void callme() {
System.out.println("Inside A's callme method");
}}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
Course Code: BCS306A Scheme and Solution
}
Course Code: BCS306A Scheme and Solution
void erase() {
System.out.println("Erasing a square");
}}
public static void main(String[] args) {
// Create an array of Shape objects
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();
// Demonstrate polymorphism
for (Shape shape : shapes) {
shape.draw(); // Polymorphic method invocation
shape.erase(); // Polymorphic method invocation
System.out.println(); // Separate output for each shape
}}
3b. Explain the usage of final keyword with inheritance. 4M
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be: variable, method, class.
a.) final variable:
class Bike9{
final int speedlimit=90;
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}}
o/p: compile time error
b.) final with method: If you make any method as final, you cannot override it.
class Bike {
final void run({
System.out.println("running");
}}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph"); }
public static void main(String args[]){
Course Code: BCS306A Scheme and Solution
5a. Develop a java program to raise a custom exception(user defined exception) for DivisionByzero using 6M
try , catch, throw and finally.
package RNS;
import java.util.*;
// Custom exception class for Division By Zero
classDivisionByZeroExceptionextends Exception {
public DivisionByZeroException(String message) {
super(message);
}}
// Class with a method that performs division and handles the custom exception
class Calculator {
public static double divide(intnumerator, intdenominator) throws DivisionByZeroException {
// Check for Division By Zero
if (denominator == 0) {
throw new DivisionByZeroException("Division By Zero is not allowed");
}
// Perform division
return (double) numerator / denominator;
}}
public class Program9 {
public static void main(String[] args) {
try {
// Provide values for numerator and denominator
System.out.println("enter the value of numerator");
Scanner sc=new Scanner(System.in);
intnumerator = sc.nextInt();
System.out.println("enter the value of denominator");
intdenominator = sc.nextInt();
// Calling the divide method that may throw DivisionByZeroException
Double result = Calculator.divide(numerator, denominator);
System.out.println("Result of division: " + result);
} catch (DivisionByZeroException e) {
// Handling the custom exception
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}}}
Course Code: BCS306A Scheme and Solution
• A chained exception is when one exception is caused by another.It helps trace the root cause of
an error when one issue leads to another.
public class ChainedExceptionDemo {
public static void main(String[] args) {
try { // Step 1: A block that throws an exception (like division by zero)
divide(10, 0);
} catch (ArithmeticException e) {
// Step 2: Wrap it in a new exception
throw new RuntimeException("Calculation failed", e);
}}
public static int divide(int a, int b) {
return a / b; // This will throw ArithmeticException for b = 0
}}
6a. Define an exception. What are the key terms used in exception handling? Explain with suitable example. 6M
• A chained exception is when one exception is caused by another.
• It helps trace the root cause of an error when one issue leads to another.
public class ChainedExceptionDemo {
public static void main(String[] args) {
try
{
// Step 1: A block that throws an exception (like division by zero)
divide(10, 0);
}
catch (ArithmeticException e)
{
// Step 2: Wrap it in a new exception
throw new RuntimeException("Calculation failed", e);
}
}
public static int divide(int a, int b) {
return a / b; // This will throw ArithmeticException for b = 0
}
}
Course Code: BCS306A Scheme and Solution
6b. List the difference between "throw" and "throws" in java Exception handling. 4M
1.) throw:
The throw keyword is used to explicitly throw an exception within a method.
It is used when a programmer encounters an exceptional condition that they want to
explicitly throw to the calling method or catch block.
The throw statement must be followed by an instance of a class that extends Throwable
(either Exception or Error).
It is commonly used inside methods to handle exceptional situations locally.
2.) throws:
The throws keyword is used in method declarations to indicate that the method may throw
certain types of exceptions during its execution.
It is used when the method does not handle the exception itself but wants to delegate the
responsibility of handling the exception to its caller.
The throws clause lists the exceptions that a method might throw, allowing the caller to
handle those exceptions.
It is used to declare checked exceptions that a method might throw, and it specifies the types
of exceptions that the method is capable of throwing.
7a. With an example JAVA program explain Nested try Statements in Exception Handling. 4M
Exception handling in Java is a powerful mechanism that allows developers to manage and respond to
runtime errors, ensuring that programs run smoothly and any unexpected issues are handled gracefully.
Types of Exceptions:
Checked Exceptions: Exceptions checked at compile-time. They are external issues like file access or
network problems. Examples include IOException, SQLException, and FileNotFoundException.
Unchecked Exceptions: Not checked at compile time. These are programming errors like
NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.
Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two
subclasses that partition exceptions into two distinct branches.
• One branch is headed by Exception.
• Another branch is headed by Error.
8a. In Java, is exception handling implicit or explicit or both? Explain with the help of Java program. 5M
In Java, exception handling can be both implicit and explicit. This means that the language provides
mechanisms for both automatically handling exceptions (implicit) and for the programmer to manually
handle them (explicit).
Implicit Exception Handling: This occurs when an exception is not caught within the method where it
occurs, and the method does not declare the exception using throws. In such cases, the exception is
propagated up the call stack until it is caught by a higher-level method or it reaches the main method,
causing the program to terminate if it is still unhandled.
Explicit Exception Handling: This is when the programmer uses try-catch blocks to catch and handle
exceptions directly within the code, or declares the exceptions in the method signature using throws.
Course Code: BCS306A Scheme and Solution
import java.io.IOException;
public class ExceptionHandlingExample {
// This method declares that it throws an IOException (explicit handling)
public void readFile(String fileName) throws IOException {
if (fileName == null) {
// This will be caught explicitly in the main method
throw new IllegalArgumentException("File name cannot be null");
}
// Simulate an IOException
throw new IOException("Error reading file");
}
// This method does not declare any exceptions (implicit handling)
public void processFile() {
try {
// Trying to call readFile method, which throws IOException
readFile(null);
} catch (IOException e) {
// Explicitly catching IOException
System.out.println("Caught IOException in processFile: " + e.getMessage());
}
// Not catching IllegalArgumentException, so it is implicitly handled
}
public static void main(String[] args) {
ExceptionHandlingExample example = new ExceptionHandlingExample();
try {
example.processFile();
} catch (IllegalArgumentException e) {
// Explicitly catching IllegalArgumentException in the main method
System.out.println("Caught IllegalArgumentException in main: " + e.getMessage());
}
}
}
Course Code: BCS306A Scheme and Solution
If you have to perform different tasks at the occurrence of different Exceptions, use multiple catch block.
Used to handle a specific type of exceptions.
public class Mainl{
public static void main(String args[]) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch (Exception e) {
System.out.println("common task completed");
}
catch (ArithmeticException e) {
System.out.println(e+“ taskl is completed");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("task 2 completed");
}
System.out.println("rest of the code”);
}
Course Code: BCS306A Scheme and Solution
As we have seen, packages are reflected with directories. This will raise the question that - how does
Java run-time know where to look for the packages that we create?
By default, Java run-time uses current working directory as a starting point. So, if our package
is in a sub-directory of current working directory, then it will be found.
We can set directory path using CLASSPATH environment variable.
We can use –classpath option with javac and java to specify the path of our classes.
Assume that we have created a package MyPackage. When the second two options are used, the class
path must not include MyPackage. It must simply specify the path to MyPackage. For example, in a
Windows environment, if the path to MyPackage is C:\MyPrograms\Java\MyPackage
Then the class path to MyPackage is C:\MyPrograms\Java
Consider the program given below –
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
Course Code: BCS306A Scheme and Solution
10b. How do you create and import package? Explain with example program. 5M