0% found this document useful (0 votes)
3 views

Java IA II Scheme -1

Uploaded by

amvsbroken
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java IA II Scheme -1

Uploaded by

amvsbroken
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

RN SHETTY TRUST®

RNS INSTITUTE OF TECHNOLOGY


Autonomous Institution Affiliated to VTU, Recognized by GOK, Approved by AICTE
(NAAC ‘A+ Grade’ Accredited, NBA Accredited (UG - CSE, ECE, ISE, EIE and EEE)
Channasandra, Dr. Vishnuvardhan Road, Bengaluru - 560 098
Ph: (080)28611880,28611881 URL: www.rnsit.ac.in

DEPARTMENT OF CSE (DATA SCIENCE)

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

Scheme and Solution


Q. No Description Marks

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

1b. List and explain the uses of super keyword in java. 4M

• Accessing Superclass Members:


You can use super to access members (fields or methods) of the superclass in the subclass.
This is useful when a subclass has overridden a method or shadowed a field, and you want to refer to
the superclass version.
• Calling Superclass Constructor:
You can use super to call the constructor of the superclass from the constructor of the subclass.
This is helpful when you want to reuse the initialization logic of the superclass.
• Invoking Superclass Method in Overridden Method:
When a method is overridden in a subclass, you can use super to invoke the overridden method from
the superclass.
• Referring to Superclass Variables in Case of Name Conflict:
When a subclass has a field or variable with the same name as a field or variable in the superclass,
you can use super to differentiate and access the superclass version.

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

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike {
void run(){
System.out.println("running safely..");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
} }
Course Code: BCS306A Scheme and Solution

2b. Demonstrate dynamic method dispatch with an example. 4M

• 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

A r; // obtain a reference of type A


r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}}
3a. Develop a java program to create a class named shape. Create three sub classes namely: circle, triangle 6M
and square, each class has two member functions named draw () and erase(). Demonstrate polymorphism
concepts by developing suitable methods, defining member data and main program.
public class Shape {
void draw() {
System.out.println("Drawing a generic shape");
}
void erase() {
System.out.println("Erasing a generic shape");
}}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
void erase() {
System.out.println("Erasing a circle");
}}
class Triangle extends Shape {
void draw() {
System.out.println("Drawing a triangle");
}
void erase() {
System.out.println("Erasing a triangle");
}}
class Square extends Shape {
void draw() {
System.out.println("Drawing a square");
}

}
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

Honda honda= new Honda();


honda.run();
}}
c.) final with class: If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda();
honda.run();
} }
4a. Write a program to create an abstract class shape with abstract methods CalculateArea() and 6M
CalculatePerimeter(). Create subclasses Circle and Triangle that extends the Shape class and implement
the respective methods to calculate the area and perimeter of each shape.
package RNS;
abstract class Shape {
// Abstract methods to calculate area and perimeter
public abstract double calculateArea();
public abstract double calculatePerimeter();
class Circle extends Shape {
private double radius;
public Circle(doubleradius) {
this.radius = radius;
}
public double calculateArea() {
return Math.PI * radius * radius;
}
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}}
class Triangle extends Shape {
privatedoubleside1, side2, side3;
public Triangle(doubleside1, doubleside2, doubleside3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
Course Code: BCS306A Scheme and Solution

public double calculateArea() {


doubles = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
public double calculatePerimeter() {
returnside1 + side2 + side3;
}}
public class Program6 {
public static void main(String[] args) {
Circle circle = new Circle(5.0);
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());
Triangle triangle = new Triangle(3.0, 4.0, 5.0);
System.out.println("Triangle Area: " + triangle.calculateArea());
System.out.println("Triangle Perimeter: " + triangle.calculatePerimeter());
}}
Output:
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Triangle Area: 6.0
4b. Differentiate between
Triangle Perimeter: 12.0method overloading and method overriding. 4M
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

5b. Explain the concept of Chained Exception with example. 4M

• 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

public class NestedTryExample {


public static void main(String[] args) {
// Outer try block
try {
// Inner try block
try {
// Attempt to divide by zero, which will cause an ArithmeticException
int result = 10 / 0;
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
Course Code: BCS306A Scheme and Solution

7b. List and explain the classification of exceptions. 6M

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

8b. Explain the concept of multiple catch clauses. 5M

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

9a. What is package? Explain with example. 4M

A package is a collection of classes.


To create a package, include a package command as the first statement in a Java source file. Any class
declared within that file will belong to the specified package. If you omit the package statement, the class
names are put into the default package, which has no name.
General form of the package statement: package pkg;
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}
9b. Write a short note on access protection in JAVA packages. 6M
There are four categories of visibility for class members:
1. Subclasses in the same package
2. Non-subclasses in the same package
3. Subclasses in different packages
4. Classes that are neither in the same package nor subclasses
Course Code: BCS306A Scheme and Solution

10a. Write a short on Finding Packages and Classpath. 5M

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

A package is a collection of classes.


To create a package, include a package command as the first statement in a Java source file. Any class
declared within that file will belong to the specified package. If you omit the package statement, the class
names are put into the default package, which has no name.
General form of the package statement: package pkg;
Java includes the import statement to bring certain classes, or entire packages, into visibility. Once
imported, a class can be referred to directly, using only its name.
In a Java source file, import statements occur immediately following the package statement (if it exists)
and before any class definitions. The general form of the import statement is:
import pkg1[.pkg2].(classname|*);
import java.util.Date;
import java.io.*;
The import statement is optional. Any place you use a class name, you can use its fully qualified name,
which includes its full package hierarchy. For example,
import java.util.*;
class MyDate extends Date
{ ……………}
Can be written as –
class MyDate extends java.util.Date
{ …}
Example:
import java.util.*;
public class ImportingExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
i = read.nextInt();
System.out.println("You have entered a number " + i);
Random rand = new Random();
int num = rand.nextInt(100);
System.out.println("Randomly generated number " + num);
}
}
Note: Output to be written for all the programs.

You might also like